
/*
    LinuxWare passwords support functions

    Copyright (C) 1994, 1995  Ales Dryak <e-mail: A.Dryak@sh.cvut.cz>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/
#include <ctype.h>
#include <string.h>
#include "lwpwd.h"

static unsigned int xtoi(char c)
{
	if (c>='0' && c<='9') return c-'0';
	if (c>='A' && c<='F') return c-'A'+10;
	if (c>='a' && c<='f') return c-'a'+10;
	return -1;
}

int getlwpwent(FILE* file,lwpwent* pe)
{
	char buf[sizeof(pe->name)+sizeof(pe->passwd)*2+10];
	char* pass;
	char* dst;
	byte* dstb;

	pe->expired=1;	
	if (fgets(buf,sizeof(buf),file)==NULL) return 0;
	for(pass=buf,dst=pe->name.name;;pass++,dst++)
	{
		if (*pass==0) return 0;
		if (dst>=pe->name.name+sizeof(pe->name)) return 0;
		if (*pass==':') break;
		*dst=toupper(*pass);
	}
	*dst=0;
	*pass++=0;
	if (*pass=='\n')
	{
		memset(pe->passwd.passwd,0,sizeof(pe->passwd.passwd));
		return 1;
	}
	for(dstb=pe->passwd.passwd;;dstb++)
	{
		if (dstb>=pe->passwd.passwd+sizeof(pe->passwd.passwd)) break;
		if (!isxdigit(*pass)) return 0;
		*dstb=xtoi(*pass++)*16;
		if (!isxdigit(*pass)) return 0;
		*dstb+=xtoi(*pass++);
	}
	if (*pass!='\n') return 0;
	pe->expired=0;
	return 1;
}

int getlwpwnam(FILE* file,lwpwent* pe,char* name)
{
	rewind(file);
	while(getlwpwent(file,pe))
	{
		if (strcmp(name,pe->name.name)==0) return 1;
	}
	return 0;
}

int putlwpwent(FILE* file,lwpwent* pe)
{
	int i;
	char* p;
	for(p=pe->name.name;*p;p++)
	{
		fprintf(file,"%c",tolower(*p));
	}
	fprintf(file,":");
	if (!pe->expired)
	{
		for(i=0;i<sizeof(pe->passwd.passwd);i++) 
		{
			fprintf(file,"%02X",pe->passwd.passwd[i]);
		}
	}
	fprintf(file,"\n");
	return 1;
}
