/*
 * snkfiles - provide interface to SNK related files
 *
 * Part of the SNK extension to logdaemon
 *
 * Written by William LeFebvre, Argonne National Laboratory
 */

#include <string.h>
#include <stdio.h>
#include <syslog.h>

#ifdef SYSV4
#include <rpcsvc/ypclnt.h>
#include <rpcsvc/yp_prot.h>
#endif

#include "snk.h"

/* int getscent(struct scent *sc, char *name)
 *	Get an entry from the snkcards file that corresponds to the
 *	user "name".  If no entry is found in the local file, then
 *	check YP.  Return 0 on success, -1 on failure.
 */

int getscent(sc, name)

struct scent *sc;
char *name;

{
    FILE *scfile;
    static char buf[128];
    char *default_domain;
    char *value;
    int valuelen;
    int line = 0;

    /* check cardfile first */
    if ((scfile = fopen(SCFILE, "r")) != NULL)
    {
	/* look up requested name in database */
	while (fgets(buf, sizeof(buf), scfile) != NULL)
	{
	    line++;
	    if (buf[0] == '#')
	        continue;       /* comment */
	    sc->name = strtok(buf, ": \t");
	    sc->serial = strtok((char *) 0, ": \t\n");
	    if (sc->name == 0 || sc->serial == 0) {
		syslog(LOG_ERR, "%s, line %d: malformed entry", SCFILE, line);
		continue;
	    }
	    if (strcmp(sc->name, name) == 0)
	    {
		fclose(scfile);
		return(0);
	    }
	}
	fclose(scfile);
    }

    /* not found, yet */
    /* now check YP */
    if (yp_get_default_domain(&default_domain) == 0 &&
	yp_match(default_domain, SCMAP, name, strlen(name),
		 &value, &valuelen) == 0)
    {
	/* make sure the result does not overrun our buffer */
	if (strlen(name) + valuelen + 2 > sizeof(buf)) {
	    syslog(LOG_ERR, "%s: preposterous entry for %s", SCMAP, name);
	    return(0);
	}
	/* save copy of name string */
	strcpy(buf, name);
	sc->name = buf;

	/* save copy of serial string */
	sc->serial = buf + strlen(buf) + 1;
	strncpy(sc->serial, value, valuelen);
	sc->serial[valuelen] = '\0';

	return(0);
    }
    return(-1);
}

/* int getsnkent(struct snkent *snk, char *name)
 *	Get an entry from the snkkeys file that corresponds to
 *	card id "name".  Return 0 on success, -1 on failure.
 */

int getsnkent(snk, name)

struct snkent *snk;
char *name;

{
    FILE *snkfile;
    static char buf[128];
    int line = 0;

    /* open keyfile */
    if ((snkfile = fopen(SNKFILE, "r")) != NULL)
    {
	/* look up requested name in database */
	while (fgets(buf, sizeof(buf), snkfile) != NULL)
	{
	    line++;
	    if (buf[0] == '#')
	        continue;       /* comment */
	    snk->id = strtok(buf, ":");
	    snk->key = strtok((char *) 0, ":");
	    snk->cksum = strtok((char *) 0, ":\n");
	    if (snk->id == 0 || snk->key == 0 || snk->cksum == 0) {
		syslog(LOG_ERR, "%s, line %d: malformed entry", SNKFILE, line);
		continue;
	    }
	    if (strcmp(snk->id, name) == 0)

	    {
		fclose(snkfile);
		return(0);
	    }
	}
	fclose(snkfile);
    }
    return(-1);
}

