/*
 * inquir-krb-update.c
 * 8 November 1990
 * Gregory D. Troxel
 */

#ifndef sun
#include <libc.h>
#endif

#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int getpeername(int s, struct sockaddr *name, int *namelen);

#include <krb.h>

void error(char *s);

extern int errno;
extern char *sys_errlist[];

#include "inquir.h"

void
error(char *s)
    {
    char sys[1024];

    printf("-%s\r\n", s);
    fflush(stdout);
    exit(0);
    }

main()
    {
    int len, netlen, privlen;
    int i;
    char buf[BUFSIZE];
    struct sockaddr_in myaddr;
    struct sockaddr_in hisaddr;
    int hislen = sizeof(struct sockaddr_in);

    AUTH_DAT ad;
    des_key_schedule sched;
    MSG_DAT msg_data;

    KTEXT_ST auth_data;

    char hostname[256];
    struct hostent *hp;
    int mylen;

    char com[1024];
    FILE *fp; 

    setup_strings();

    /* get my address - kerberos needs it for mk/rd_priv */
    mylen = sizeof (myaddr);
    if (getsockname (1, (struct sockaddr *) &myaddr, &mylen) < 0)
	error("Couldn't get my address");

    /* get his addr */
    if ( getpeername(0, (struct sockaddr *) &hisaddr, &hislen) < 0 )
	{
	char err[1024];
	sprintf(err, "getpeername %d %s", errno, sys_errlist[errno]);
	error(err);
	}

    if( read(0, &netlen, sizeof(int)) != sizeof(int) )
	error("can't read length - auth");
    auth_data.length = len = ntohl(netlen);

    if( read(0, auth_data.dat, len) != len )
	error("can't read auth");

    i = krb_rd_req(&auth_data,
	INQUIR_PRINCIPAL, INQUIR_INSTANCE,
	hisaddr.sin_addr.s_addr, &ad, Srvtab);
    if ( i != KSUCCESS )
	{
	char out[256];
	sprintf(out, "krb_rd_req lost (%d): %s\n", i, krb_err_txt[i]);
	error(out);
	}

    /* make key schedule - needed for rd/mk_priv later */
    des_key_sched(ad.session, sched);

    if( read(0, &netlen, sizeof(int)) != sizeof(int) )
	error("can't read length - priv");
    len = ntohl(netlen);

    if( read(0, buf, len) != len )
	error("can't read priv");

    /* read priv message */
    i = krb_rd_priv(buf, len, sched, ad.session, &hisaddr, &myaddr, &msg_data);
    if( i != KSUCCESS )
	{
	char out[256];
	sprintf(out, "krb_rd_priv lost (%d): %s\n", i, krb_err_txt[i]);
	error(out);
	}

    /* here is data - I don't know what you want to do with it! */
    if ( !strcmp(ad.pinst, "") && !strcmp(ad.prealm, "LCS.MIT.EDU") )
	sprintf(com, "/etc/tcpmuxd.servers/inquir-update %s", ad.pname);
    else
	sprintf(com, "/etc/tcpmuxd.servers/inquir-update %s.%s@%s",
	    ad.pname, ad.pinst, ad.prealm);

    fp = popen(com, "w");
    fwrite(msg_data.app_data, msg_data.app_length, 1, fp);
    pclose(fp);

    return(0);
    }
