/* Post Office Protocol (POP3) Client -- RFC1225
 * Copyright 1992 William Allen Simpson
 *	partly based on a NNTP client design by Anders Klemets, SM0RGV
 *      and POP2 Client by Mike Stockett, WA7DYX, et alia.
 */
#include <stdio.h>
#include <time.h>
#include "global.h"
#include "timer.h"
#include "proc.h"
#include "netuser.h"
#include "socket.h"
#include "cmdparse.h"
#include "files.h"
#include "mailcli.h"
#include "mailutil.h"
#include "smtp.h"


void
pop3_job(unused,v1,p2)
int unused;
void *v1;
void *p2;
{
	struct mailservers *np = v1;
	struct sockaddr_in fsocket;
	char buf[TLINELEN];
	char *cp;
	FILE *wfp = NULLFILE;
	time_t t;
	int s = -1;
	int bytes;
	int messages;
	int i;

	if ( mailbusy( np ) )
		return;

	if ( (fsocket.sin_addr.s_addr = resolve(np->hostname)) == 0L ) {
		/* No IP address found */
		if (Mailtrace >= 1)
			log(-1,"POP3 can't resolve host '%s'", np->hostname);
		start_timer(&np->timer);
		return;
	}

	fsocket.sin_family = AF_INET;
	fsocket.sin_port = IPPORT_POP3;

	s = socket(AF_INET,SOCK_STREAM,0);
	sockmode(s,SOCK_ASCII);

	if (connect(s,(char *)&fsocket,SOCKSIZE) == -1) {
		cp = sockerr(s);
		if (Mailtrace >= 2)
			log(s,"POP3 Connect failed: %s",
				cp != NULLCHAR ? cp : "" );
		goto quit;
	}

	log(s,"POP3 Connected to mailhost %s", np->hostname);

	/* Eat the banner */
	if ( mailresponse( s, buf, "banner" ) == -1
	  || buf[0] == '-' ) {
		goto quit;
	}

	usprintf(s,"USER %s\n", np->username);
	if ( mailresponse( s, buf, "USER" ) == -1
	  || buf[0] == '-' ) {
		goto quit;
	}

	usprintf(s,"PASS %s\n", np->password);
	if ( mailresponse( s, buf, "PASS" ) == -1
	  || buf[0] == '-' ) {
		goto quit;
	}

	usprintf(s,"STAT\n" );
	if ( mailresponse( s, buf, "STAT" ) == -1
	  || buf[0] == '-' ) {
		goto quit;
	}

	rip(buf);
	if ( Mailtrace >= 1 )
		log(s,"POP3 status %s",buf);
	sscanf(buf,"+OK %d %d",&messages,&bytes);

	for ( i = 0; i++ < messages; ) {
		if ((wfp = tmpfile()) == NULLFILE) {
			if ( Mailtrace >= 1 )
				log(s,"POP3 Cannot create tmp file" );
			goto quit;
		}

		usprintf(s,"RETR %d\n", i);
		if ( mailresponse( s, buf, "RETR" ) == -1 )
			goto quit;
		if ( buf[0] == '-' ) {
			continue;
		}

		time(&t);
		fprintf( wfp, "From POP3@%s %s",
			np->hostname,
			ctime(&t));

		if ( recvmail(s, buf, TLINELEN, wfp, Mailtrace) == -1 ) {
			goto quit;
		}

		if ( copymail(buf, TLINELEN, wfp ) == -1 )
			goto quit;
		fclose (wfp);

		usprintf(s,"DELE %d\n", i);
		if ( mailresponse( s, buf, "DELE" ) == -1
		  || buf[0] == '-' ) {
			goto quit;
		}
	}

	usprintf(s,"QUIT\n" );
	mailresponse( s, buf, "QUIT" );

	if ( messages ) {
		tprintf("New mail arrived for %s from mailhost %s%c\n",
				np->mailbox,
				np->hostname,
				Mailquiet ? ' ' : '\007');
		smtptick(NULL);     /* wake SMTP to send that mail */
	}

quit:
	log(s,"POP3 daemon exiting" );
	close_s(s);

	if (wfp != NULLFILE)
		fclose(wfp);
	start_timer(&np->timer);
}


