/* auth_gss.c -- GSSAPI authorization for Cyrus IMAP
 * $Id:  $
 * Copyright (c) 2004 Alexey Melnikov, Isode Limited.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <config.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>

#ifdef HAVE_GSSAPI_H
#include <gssapi.h>
#else
#include <gssapi/gssapi.h>
#endif

#include "auth.h"
#include "xmalloc.h"

const char *auth_method_desc = "gss";

struct auth_state {
    char *userid; /* Canonified Userid */
};

/*
 * Determine if the user is a member of 'identifier'
 * Returns one of:
 * 	0	User does not match identifier
 * 	1	identifier matches everybody
 *	2	User is in the group that is identifier
 *	3	User is identifer
 */
int auth_memberof(struct auth_state *auth_state, const char *identifier)
{
    char *ident;
    int ret=0;

    if (strcmp(identifier,"anyone") == 0) return 1;
    if (!auth_state && !strcmp(identifier, "anonymous")) return 3;
    else if(!auth_state) return 0;
    if (strcmp(identifier,auth_state->userid) == 0) return 3;
    if (strcmp(auth_state->userid,"anonymous") == 0) return 0;

    ident = auth_canonifyid(identifier,0);

    if(!strcmp(ident, auth_state->userid)) {
	ret = 3;
    }
    
    return ret;
}

/*
 * Convert 'identifier' into canonical form.
 * Returns a pointer to a static buffer containing the canonical form
 * or NULL if 'identifier' is invalid.
 */
char *auth_canonifyid(const char *identifier, size_t len)
{
    static char *retbuf = NULL;
    gss_buffer_desc name_with_realm;
    gss_buffer_desc name_without_realm;
    gss_buffer_desc name_token;
    gss_name_t without = NULL;
    gss_name_t fullname = NULL;
    int striprealm = 0;
    char *realmbegin;
    OM_uint32 maj_stat, min_stat;


    if(retbuf) free(retbuf);
    retbuf = NULL;


    if(!identifier) return NULL;
    if(!len) len = strlen(identifier);

    if (strcasecmp(identifier, "anonymous") == 0)
	return "anonymous";
    
    if (strcasecmp(identifier, "anyone") == 0) 
	return "anyone";



    name_with_realm.value = strdup(identifier);
    if (name_with_realm.value == NULL) {
	return (NULL);
    }
    name_with_realm.length = strlen( (char *) name_with_realm.value );
	    
    maj_stat = gss_import_name (&min_stat,
				&name_with_realm,
	    /* Solaris 8/9 gss_import_name doesn't accept GSS_C_NULL_OID here,
	       so use GSS_C_NT_USER_NAME instead if available.  */
#ifdef HAVE_GSS_C_NT_USER_NAME
				GSS_C_NT_USER_NAME,
#else
				GSS_C_NULL_OID,
#endif
				&fullname);

    if (GSS_ERROR(maj_stat)) {
	free(name_with_realm.value);
	return (NULL);
    }

    free(name_with_realm.value);

/* If the id contains a realm get the identifier for the user
   without the realm and see if it's the same id (i.e. 
   tmartin == tmartin@ANDREW.CMU.EDU. If this is the case we just want
   to return the id (i.e. just "tmartin") */
    realmbegin = strchr(identifier, (int) '@');
    if (realmbegin != NULL) {
	name_without_realm.value = strdup(identifier);
	if (name_without_realm.value == NULL) {
	    if (fullname)
		gss_release_name(&min_stat, &fullname);
	    return (NULL);
	}

	strcpy(name_without_realm.value, identifier);
	    
	/* cut off string at '@' */
	((char *)name_without_realm.value)[identifier - realmbegin] = '\0';
	    
	name_without_realm.length = strlen( (char *) name_without_realm.value );
	    
	maj_stat = gss_import_name (&min_stat,
				    &name_without_realm,
	    /* Solaris 8/9 gss_import_name doesn't accept GSS_C_NULL_OID here,
	       so use GSS_C_NT_USER_NAME instead if available.  */
#ifdef HAVE_GSS_C_NT_USER_NAME
				    GSS_C_NT_USER_NAME,
#else
				    GSS_C_NULL_OID,
#endif
				    &without);
	    
	if (GSS_ERROR(maj_stat)) {
	    free(name_without_realm.value);
	    if (fullname)
		gss_release_name(&min_stat, &fullname);
	    return (NULL);
	}
	    
	free(name_without_realm.value);

	maj_stat = gss_compare_name(&min_stat,
				    fullname,
				    without,
				    &striprealm); /* striprealm == equal */
	    
	if (GSS_ERROR(maj_stat)) {
	    if (without)
		gss_release_name(&min_stat, &without);
	    if (fullname)
		gss_release_name(&min_stat, &fullname);
	    return (NULL);
	}

	gss_release_name(&min_stat, &without);
    }

    name_token.value = NULL;
    maj_stat = gss_display_name (&min_stat,
				 fullname,
				 &name_token,
				 NULL);
	
    if (fullname)
	gss_release_name(&min_stat, &fullname);

    if (GSS_ERROR(maj_stat)) {
	return (NULL);
    }

    if (name_token.value) {
	retbuf = strdup (name_token.value);
	gss_release_buffer(&min_stat, &name_token);
    }

    /* we have the canonical name pointed to by p -- strip realm if local */
    if (striprealm) {
	realmbegin = strrchr(retbuf, '@');
	if (realmbegin) *realmbegin = '\0';
    }

    return (retbuf);
}

/*
 * Set the current user to 'identifier'.
 */
struct auth_state *auth_newstate(const char *identifier)
{
    struct auth_state *newstate;
    char *ident;
    ident = auth_canonifyid(identifier, 0);
    if (!ident) return NULL;

    newstate = (struct auth_state *)xmalloc(sizeof(struct auth_state));
    newstate->userid = xstrdup(ident);   

    return newstate;
}

void auth_freestate(struct auth_state *auth_state)
{
    if(!auth_state) return;
    
    free(auth_state->userid);
    free(auth_state);
}

