/* ifndef KERBEROS this entire file is useless; ftp_pass() simply calls
 * pass() (from ftpd.c) with the password given as an argument.
 */

#ifndef KERBEROS
int ftp_pass(password)
   char *password;
{
     pass(password);
}
#else

#include <stdio.h>
#include <krb.h>
#include <pwd.h>
#include <sys/wait.h>
#include <syslog.h>
#include <sys/file.h>

#ifndef LIFE
#define LIFE	96
#endif

#define exists(s)	(access(s, F_OK)==0)

int		has_tickets = 0;
extern char	**kinit_argv;
extern int	kinit_argc, debug, logged_in;

int ftp_kdest()
{
     return (dest_tkt());
}

int ftp_pass(password)
   char	*password;
{
     int     			lifetime, kerrno, pid, kerberos, attach;
     int			aerror;
     char    			inst[INST_SZ], realm[REALM_SZ];
     char			tkt_file[100], **temp;
     extern struct passwd	*pw;
     union wait			status;

     *inst = *realm = '\0';
     kerberos = attach = 1;
     kerrno = aerror = has_tickets = 0;
     lifetime = 96;
     temp = kinit_argv;
     
     while (**(++temp)) {
	  if ((*temp)[0] == '-') {
	       switch ((*temp)[1]) {
	       case 'i':
		    temp++;
		    strcpy(inst, *temp);
		    break;
	       case 'r':
		    temp++;
		    strcpy(realm, *temp);
		    break;
	       case 'l':
		    temp++;
		    lifetime = atoi(*temp) / 5;
		    break;
	       case 'k':
		    kerberos = 0;
		    break;
	       case 'a':
		    attach = 0;
		    break;
	       }
	  }
     }

     if (kerberos) {
	  strcpy(tkt_file,"/tmp/ftp_tktXXXXXX");
	  mktemp(tkt_file);
	  setenv("KRBTKFILE", tkt_file, 1);
	  
	  setuid(0);
	  if ((*realm) || (! (kerrno = krb_get_lrealm(realm, 1)))) {
	       if (lifetime > LIFE) lifetime = LIFE;
	       kerrno = krb_get_pw_in_tkt(kinit_argv[0], inst, realm, "krbtgt",
					  realm, lifetime, password);
	       chown(tkt_file, pw->pw_uid, -1);
	  }

	  if ((! kerrno) && exists(SRV_FILE))
	       kerrno = ck_tkt();
	  
	  has_tickets = (kerrno==0);

	  if (has_tickets) logged_in = 1;
	  else logged_in = 0;
     }

     if ((! kerberos) || kerrno) {
	  has_tickets = 0;
	  pass(password);
     }
     else {
	  if (attach) {
	       lreply(230, "User logged in with tickets.");
	       aerror = ftp_attach(kinit_argv[0]);
	       if (aerror) reply(230, "Attach exit code: %d", aerror);
	       else reply(230, "Homedir attached.");
	  }
	  else reply(230, "User logged in with tickets.");
     }

     free_vector(kinit_argv, kinit_argc);
     kinit_argv = NULL;

     /* Checkers!  Get away from that erase button!
      *   (Stupid dog...)
      */
     bzero(password, strlen(password));
}

#endif /*def KERBEROS*/
