/*
** publickey.c                      /etc/publickey access functions
**
** Copyright (C) 1993 Signum Support AB
**
** This file is part of the NYS Library.
**
** The NYS Library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Library General Public License as
** published by the Free Software Foundation; either version 2 of the
** License, or (at your option) any later version.
**
** The NYS Library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Library General Public License for more details.
** 
** You should have received a copy of the GNU Library General Public
** License along with the NYS Library; see the file COPYING.LIB.  If
** not, write to the Free Software Foundation, Inc., 675 Mass Ave,
** Cambridge, MA 02139, USA.
**
*/

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

#include <rpc/rpc.h>
#include <rpc/key_prot.h>

extern int xdecrypt(char *secret, char *passwd);

static FILE *pkeyf;
static char line[BUFSIZ+1];
static const char *PKFILE = "/etc/publickey";

int _getpublickey (const char *netname, char *publickey)
{
	char *p;
	register char *savekey;
	register char *saveval;

	pkeyf = fopen(PKFILE, "r");
	if (pkeyf == NULL) {
		/* TODO print warning */
		return (0);
	}

again:
	p = fgets(line, BUFSIZ, pkeyf);
	if (p == NULL) {
		fclose(pkeyf);
		return (0);
	}
	if ((*p == '#') || (*p == '\n'))
		goto again;
	savekey = strtok(line, " \t");
	if (savekey == NULL) {
		/* TODO print warning */
		goto again;
	}
	saveval = strtok(NULL, " \t#\n");
	if (saveval == NULL) {
		/* TODO print warning */
		goto again;
	}
	if (strcasecmp(savekey, netname))
		goto again;
	p = strchr(saveval, ':');
	if (p == NULL) {
		/* TODO print warning */
		goto again;
	}
	*p = 0;
	(void)strcpy(publickey, saveval);
	fclose(pkeyf);
	return(1);
}

int _getsecretkey (const char *netname, char *secretkey, char *passwd)
{
	char *p;
	register char *savekey;
	register char *saveval;

	pkeyf = fopen(PKFILE, "r");
	if (pkeyf == NULL) {
		/* TODO print warning */
		return (0);
	}

again:
	p = fgets(line, BUFSIZ, pkeyf);
	if (p == NULL) {
		fclose(pkeyf);
		return (0);
	}
	if ((*p == '#') || (*p == '\n'))
		goto again;
	savekey = strtok(line, " \t");
	if (savekey == NULL) {
		/* TODO print warning */
		goto again;
	}
	saveval = strtok(NULL, " \t#\n");
	if (saveval == NULL) {
		/* TODO print warning */
		goto again;
	}
	if (strcasecmp(savekey, netname))
		goto again;
	p = strchr(saveval, ':');
	if (p == NULL) {
		/* TODO print warning */
		goto again;
	}	
	p++;
	if (!xdecrypt(p, passwd)) {
		fclose(pkeyf);
		return (0);
	}
	if (bcmp(p, p + HEXKEYBYTES, KEYCHECKSUMSIZE) != 0) {
		secretkey = NULL;
		fclose(pkeyf);
		return(0);
	}
	p[HEXKEYBYTES] = 0;
	(void) strcpy(secretkey, p);
	fclose(pkeyf);
	return (1);
}
