/*
	Internet Finger server
   Copyright 1991 Phil Karn, KA9Q
*/

/****************************************************************************
*	$Id: fingerd.c 1.2 94/02/02 14:37:43 ROOT_DOS Exp $
*
*	01 Feb 93	1.2	GT	New sendfile () prototype.						
****************************************************************************/

#include <stdio.h>
#include <string.h>
#include "global.h"
#include "files.h"
#include "mbuf.h"
#include "socket.h"
#include "session.h"
#include "proc.h"
#include "dirutil.h"
#include "commands.h"
#include "mailbox.h"

static int Sfinger = -1;	/* Prototype socket for service */

static void __stdargs fingerd __ARGS((int s,void *unused,void *p));

/* Start up finger service */
int
finstart(argc,argv,p)
int argc;
char *argv[];
void *p;
{
	struct sockaddr_in lsocket;
	int s;

	if(Sfinger != -1){
		return 0;
	}
	psignal(Curproc,0);	/* Don't keep the parser waiting */
	chname(Curproc,"Finger listener");

	lsocket.sin_family = AF_INET;
	lsocket.sin_addr.s_addr = INADDR_ANY;
	if(argc < 2)
		lsocket.sin_port = IPPORT_FINGER;
	else
		lsocket.sin_port = atoi(argv[1]);

	Sfinger = socket(AF_INET,SOCK_STREAM,0);
	bind(Sfinger,(char *)&lsocket,sizeof(lsocket));
	listen(Sfinger,1);
	for(;;){
		if((s = accept(Sfinger,NULLCHAR,(int *)NULL)) == -1)
			break;	/* Service is shutting down */

		/* Spawn a server */
		newproc("fingerd",512,fingerd,s,NULL,NULL,0);
	}
	return 0;
}
static void __stdargs fingerd(int s,void *unused, void *p)
{
	char user[80];
	FILE *fp;
	char *file,*cp;

	sockmode(s,SOCK_ASCII);
	sockowner(s,Curproc);
	log(s,"open Finger");
	recvline(s,user,80);
	rip(user);
	
	if (strlen(user) == 0) {
		fp = dir(Fdir, 0);
		if (fp == NULLFILE)
			usprintf(s,"No finger information available\n");
		else
			usprintf(s,"Known users on this system:\n");
	} else {
		file = pathname(Fdir, user);
		cp   = pathname(Fdir, "");

		/* Check for attempted security violation (e.g., somebody
		 * might be trying to finger "../ftpusers"!)
		 */
		 
		if (strncmp(file, cp, strlen(cp)) != 0){
			fp = NULLFILE;
			usprintf(s, "Invalid user name %s\n", user);
		} else if((fp = fopen(file, READ_TEXT)) == NULLFILE)
			usprintf(s, "User %s not known\n", user);
		free(cp);
		free(file);
	}
	if (fp != NULLFILE) {
		sendfile(fp, s, ASCII_TYPE, 0, 0);
		fclose(fp);
	}
	if (strlen(user) == 0 && Listusers != NULL) {
		(*Listusers)(s);
	}
	close_s(s);
	log(s, "close Finger");
}

int fin0(int argc, char *argv[], void *p)
{
	close_s(Sfinger);
	Sfinger = -1;
	return 0;
}
