#include "slav_locl.h"
#include <stdarg.h>
#include <sys/wait.h>

#include "kprop.h"

RCSID("$Id: kpropd.c,v 2.6 1996/06/17 04:42:39 assar Exp $");

#ifndef SBINDIR
#define SBINDIR "/usr/athena/sbin"
#endif

struct sockaddr_in master, slave;

char *database = DBM_FILE;

char *lockfile = DB_DIR "/slave_propagation";

char *logfile = K_LOGFIL;

char *kdb_util = SBINDIR "/kdb_util";

char *kdb_util_command = "load";

char *srvtab = "";

char realm[REALM_SZ];

void
x_log(char *fmt, ...)
{
    char buf[1024];
    va_list ap;
    va_start(ap, fmt);
    vsprintf(buf, fmt, ap);
    klog(L_KRB_PERR, buf);
    va_end(ap);
}

int
copy_data(int from, int to, des_cblock *session, des_key_schedule schedule)
{
    unsigned char tmp[4];
    char buf[KPROP_BUFSIZ + 26];
    u_int32_t length;
    int n;
    
    int kerr;
    MSG_DAT m;

    while(1){
	n = krb_net_read(from, tmp, 4);
	if(n == 0)
	    break;
	if(n < 0){
	    x_log("krb_net_read: %s", strerror(errno));
	    return -1;
	}
	if(n != 4){
	    x_log("Premature end of data");
	    return -1;
	}
	length = (tmp[0] << 24) | (tmp[1] << 16) | (tmp[2] << 8) | tmp[3];
	if(length > sizeof(buf)){
	    x_log("Giant packet received: %d", length);
	    return -1;
	}
	if(krb_net_read(from, buf, length) != length){
	    x_log("Premature end of data");
	    return -1;
	}
	kerr = krb_rd_priv (buf, length, schedule, session, &master, &slave, &m);
	if(kerr != KSUCCESS){
	    x_log("Kerberos error: %s", krb_get_err_text(kerr));
	    return -1;
	}
	write(to, m.app_data, m.app_length);
    }
    return 0;
}


int
kprop(int s)
{
    char buf[128];
    int n;
    KTEXT_ST ticket;
    AUTH_DAT ad;
    char sinst[INST_SZ];
    char command[1024];
    des_key_schedule schedule;
    int mode;
    int kerr;
    int lock;
    
    n = sizeof(master);
    if(getpeername(s, (struct sockaddr*)&master, &n) < 0){
	x_log("getpeername: %s", strerror(errno));
	return -1;
    }
    
    n = sizeof(slave);
    if(getsockname(s, (struct sockaddr*)&slave, &n) < 0){
	x_log("getsockname: %s", strerror(errno));
	return -1;
    }

    x_log("Connection from %s", inet_ntoa(master.sin_addr));

    n = krb_net_read(s, buf, KPROP_PROT_VERSION_LEN + 2);
    if(n < KPROP_PROT_VERSION_LEN + 2){
	x_log("Premature end of data");
	return -1;
    }
    if(memcmp(buf, KPROP_PROT_VERSION, KPROP_PROT_VERSION_LEN) != 0){
	x_log("Bad protocol version string received");
	return -1;
    }
    mode = (buf[n-2] << 8) | buf[n-1];
    if(mode != KPROP_TRANSFER_PRIVATE){
	x_log("Bad transfer mode received: %d", mode);
	return -1;
    }
    k_getsockinst(s, sinst);
    kerr = krb_recvauth(KOPT_DO_MUTUAL, s, &ticket,
			KPROP_SERVICE_NAME, sinst,
			&master, &slave,
			&ad, srvtab, schedule, 
			buf);
    if(kerr != KSUCCESS){
	x_log("Kerberos error: %s", krb_get_err_text(kerr));
	return -1;
    }
    des_set_key(&ad.session, schedule);
    
    lock = open(lockfile, O_WRONLY|O_CREAT, 0600);
    if(lock < 0){
	x_log("Failed to open file: %s", strerror(errno));
	return -1;
    }
    if(k_flock(lock, K_LOCK_EX | K_LOCK_NB)){
	close(lock);
	x_log("Failed to lock file: %s", strerror(errno));
	return -1;
    }
    
    if(ftruncate(lock, 0) < 0){
	close(lock);
	x_log("Failed to lock file: %s", strerror(errno));
	return -1;
    }

    if(copy_data(s, lock, &ad.session, schedule)){
	close(lock);
	return -1;
    }
    close(lock);
    sprintf(command, "%s %s %s %s", kdb_util, kdb_util_command, 
	    lockfile, database);
    if(system(command) == 0){
	x_log("Propagation finished successfully");
	return 0;
    }
    x_log("*** Propagation failed ***");
    return -1;
}

void
doit(void)
{
    struct sockaddr_in sa;
    int sa_len;
    int s, s2;
    int ret;

    sa_len = sizeof(sa);
    ret = getpeername(0, (struct sockaddr*)&sa, &sa_len);
    if(ret < 0 && (errno == ENOTSOCK || errno == EINVAL)){
	s = socket(AF_INET, SOCK_STREAM, 0);
	if(s < 0){
	    x_log("socket: %s", strerror(errno));
	    exit(1);
	}
	memset(&sa, 0, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port = k_getportbyname ("krb_prop", "tcp", htons(754));
	sa_len = sizeof(sa);
	ret = bind(s, (struct sockaddr*)&sa, sizeof(sa));
	if(ret < 0){
	    k_log("bind: %s", strerror(errno));
	    exit(1);
	}
	listen(s, 5);
	while(1){
	    sa_len = sizeof(sa);
	    s2 = accept(s, (struct sockaddr*)&sa, &sa_len);
	    switch(fork()){
	    case -1:
		x_log("fork: %s", strerror(errno));
		exit(1);
	    case 0:
		kprop(s2);
		exit(1);
	    default: {
		    int status;
		    close(s2);
		    wait(&status);
		}
	    }
	}
    }
    if(ret < 0){
	x_log("getpeername: %s", strerror(errno));
	exit(1);
    }
    kprop(0);
}

extern int optopt;
extern char *optarg;

static void
usage ()
{
     fprintf (stderr, 
	      "Usage: kpropd [-d database] [-l log] [-m] [-[p|P] program] "
	      "[-r realm] [-s srvtab]\n");
     exit (1);
}

int main(int argc, char **argv)
{
    int opt;

    krb_get_lrealm(realm, 1);
    
    while((opt = getopt(argc, argv, ":d:l:mp:P:r:s:")) >= 0){
	switch(opt){
	case 'd':
	    database = optarg;
	    break;
	case 'l':
	    logfile = optarg;
	    break;
	case 'm':
	    kdb_util_command = "merge";
	    break;
	case 'p':
	case 'P':
	    kdb_util = optarg;
	    break;
	case 'r':
	    strcpy(realm, optarg);
	    break;
	case 's':
	    srvtab = optarg;
	    break;
	default:
	    x_log("Bad option: -%c", optopt);
	    usage ();
	    exit(1);
	}
    }
    kset_logfile(logfile);
    doit();
}
