/*
	return code
		1 : TRUE
		0 : FALSE
		
*/

#include "trust.h"

int	login(int socket)
{
	FILE	*pass_file;

	char	call[16];
	char	pass[64];
	char	line[256];
	int	numrcv;
	int	n;
	int	k;


	// パケットの送信
	send(socket, "Repeater Call: ", 16, 0);

	//パケットの受信
	memset (RepeaterCall, 0x20, 8);
	numrcv = recv(socket, call, sizeof(call), 0);
	call[numrcv] = 0x00;
	for (n = 0 ; n < numrcv ; n++)
	{
		call[n] = toupper (call[n]);
		if (call[n] == 0x0a) call[n] = 0x00;
		if (call[n] == 0x0d) call[n] = 0x00;
	}
	numrcv = strlen(call);
	if (numrcv > 8) numrcv = 8;
	memcpy (RepeaterCall, call, numrcv);

	if (RepeaterCall[7] == 0x20) return 0;		/* no module name */

	call[7] = 0x00;
	for (n = 0 ; n < 7 ; n++)
	{
		if (call[n] == 0x20) call[n] = 0x00;  
	}

	logfile = fopen (LOGFILE, "a");
	now = time (NULL);	
 	fprintf(logfile, "%24.24s Repeater Call: %8.8s\n", ctime(&now), RepeaterCall);
	fclose (logfile);

        // パケットの送信
        send(socket, "Password: ", 11, 0);

        //パケットの受信
        numrcv = recv(socket, pass, sizeof(pass), 0);
	pass[numrcv] = 0x00;
	for (n = 0 ; n < numrcv ; n++)
	{
		if (pass[n] == 0x0a) pass[n] = 0x00;
		else if (pass[n] == 0x0d) pass[n] = 0x00;
	}
	logfile = fopen (LOGFILE, "a");
	now = time(NULL);
        fprintf(logfile, "%24.24s Password: %s\n", ctime(&now),pass);
	fclose(logfile);

        if ((pass_file = fopen("/etc/ds_passwd", "r")) == NULL) return 0;

        while (fgets (line, sizeof line , pass_file))
        {
                if (!memcmp (&call, &line, strlen(call)))
		{
			k = strlen(call) + 1;
			for (n = k ; n < 256 ; n++)
			{
				if (line[n] == ':')
				{
					line[n] = 0x00;
					break;
				}
			}
			if (strcmp (crypt (pass, &line[k]), &line[k]))
			{
				printf ("Invalid Password\n");
				return 0;
			}
			else return 1;
		}
        }
	return 0;

}

