/* Internet finger client
 * Copyright 1991 Phil Karn, KA9Q
 */

/****************************************************************************
*	$Id: finger.c 1.2 92/09/14 18:02:08 ROOT_DOS Exp Locker: ROOT_DOS $
*	13 Sep 92	1.2		CMS		Make "finger @siteX@siteY" work.			*
*
*	ATARI Version by David Nash - dnash@chaos.demon.co.uk
*
*  Add __stdargs for dofinger
*
****************************************************************************/


#include <stdio.h>
#include <string.h>
#include "global.h"
#include "mbuf.h"
#include "socket.h"
#include "session.h"
#include "proc.h"
#include "netuser.h"
#include "commands.h"
#include "tty.h"

int __stdargs dofinger(argc,argv,p)
int argc;
char *argv[];
void *p;
{
	struct sockaddr_in sock;
	char *cp;
	int s,i;
	struct mbuf *bp;
	struct session *sp;

	/* Allocate a session descriptor */
	if((sp = newsession(argv[1],FINGER)) == NULLSESSION){
		tprintf("Too many sessions\n");
		keywait(NULLCHAR,1);
		return 1;
	}
	sp->ttystate.echo = sp->ttystate.edit = 0;
	sp->flowmode = 1;
	sock.sin_family = AF_INET;
	sock.sin_port = IPPORT_FINGER;
	for(i=1;i<argc;i++){
		cp = strrchr(argv[i],'@');
		if(cp == NULLCHAR){
			tprintf("%s: local names not supported\n",argv[i]);
			continue;
		}
		*cp++ = '\0';
		tprintf("%s@%s -- ",argv[i],cp);
		tprintf("Resolving %s... ",cp);
		if((sock.sin_addr.s_addr = resolve(cp)) == 0){
			tprintf("Host %s unknown\n",cp);
			continue;
		}
		tprintf("trying %s",psocket((struct sockaddr *)&sock));
		if((sp->s = s = socket(AF_INET,SOCK_STREAM,0)) == -1){
			tprintf("Can't create socket\n");
			break;
		}
		sockmode(s,SOCK_ASCII);
		if(connect(s,(char *)&sock,sizeof(sock)) == -1){
			cp = sockerr(s);
			tprintf(" -- Connect failed: %s\n",cp != NULLCHAR ? cp : "");
			close_s(s);
			sp->s = -1;
			continue;
		}
		tprintf("\n");
		usprintf(s,"%s\n",argv[i]);
		usflush(Curproc->output);
		while(recv_mbuf(s,&bp,0,NULLCHAR,(int *)0) > 0){
			send_mbuf(Curproc->output,bp,0,NULLCHAR,0);
		}
		close_s(s);
		sp->s = -1;
	}
	keywait(NULLCHAR,1);
	freesession(sp);
	return 0;
}
