/*
 * 5799-WZQ (C) COPYRIGHT = NONE
 * LICENSED MATERIALS - PROPERTY OF IBM
 */
/* $Header:krb_auth.c 12.0$ */
/* $ACIS:krb_auth.c 12.0$ */
/* $Source: /ibm/acis/usr/src/ibm/rvd/server/RCS/krb_auth.c,v $ */

#ifndef lint
static char *rcsid = "$Header:krb_auth.c 12.0$";
#endif


#ifndef lint
static char rcsid_main_c[] = "$Header:krb_auth.c 12.0$";
#endif lint

/* Copyright 1984 by the Massachusetts Institute of Technology */
/* See permission and disclaimer notice in the file "notice.h" */
#ifdef KERBEROS
#include "notice.h"

#include <sys/types.h>
#include <krb.h>
#include "logging.h"

#ifndef TRUE
#define TRUE  1
#define FALSE 0
#endif

#ifndef	NULL
#define NULL 0
#endif

#define INSTANCE_LEN 128

static char	instance[INSTANCE_LEN];	/* Used to store local machine name. */
static struct	auth_dat auth_data;	/* Authenticated data storage.	*/


/* This routine takes a pointer to an authenticator and returns a
 * pointer to a username or NULL, if the authentication failed.
 * VERY IMPORTANT: auth_to_user assumes the authenticator has not
 * yet been decanonicalized and does the work here.  Do not decanon...
 * twice, the authenticator will be screwed up.
 */
char *
auth_to_user(authent, from_addr)
	KTEXT	authent;
	u_long	from_addr;
{
	int	status;
	struct	auth_dat *adp = &auth_data;

	/* Initialize instance string, if necessary.
	 */
	if (instance[0] == '\0') {
		if (gethostname(instance, INSTANCE_LEN) != 0) {
		    if (loglevel(LOG_ERROR))
			syslog(LOG_INFO, "auth_to_user: gethostname failed");
		    return(NULL);
		}
	}

	/* Decanonicalize the authenticator.  SEE NOTE.
	 */
	(void)ctl_canon(authent);

	/* Check authentication and get ticket values.
	 */
	status = rd_ap_req(authent, "rvdsrv", instance, from_addr, adp, "");
	if (status != RD_AP_OK) {
		if (loglevel(LOG_CLIENT_ERROR)) {
			syslog(LOG_INFO, "authentication failed:");
			syslog(LOG_INFO, "error was %s", krb_err_txt[status]);
		}
		return(NULL);
	}
	return(adp->pname);
}


/* This routine is used by spinup to verify that a user has access to
 * a pack for a particular capability.  It returns TRUE is the authenticated
 * user name is the same as "name" or if the authenticated user is on the
 * operations access control list.
 */
authenticate(authent, name, from_addr)
	KTEXT	authent;	/* Pointer to the authenticator. */
	char	*name;
	u_long	from_addr;
{
	char	*auth_name;
	struct	auth_dat *adp = &auth_data;

	auth_name = auth_to_user(authent, from_addr);
	if (auth_name == NULL)
		return(FALSE);

	/* Compare the given name with the authenticated name.
	 */
	if (strncmp(name, auth_name, ANAME_SZ) == 0)
		return(TRUE);
	
	if (priv_user(auth_name, FALSE, FALSE))
		return(TRUE);

	if (loglevel(LOG_CLIENT_ERROR)) {
		syslog(LOG_INFO, "authentication failed:");
		syslog(LOG_INFO, "%s is not pack owner or operator", 
				adp->pname);
	}
	return(FALSE);
}
#endif KERBEROS
