/* This file is part of the Project Athena Zephyr Notification System.
 * It contains code for the "zpopnotify" command.
 *
 *	Created by:	Robert French
 *
 *	$Source: /afs/stacken.kth.se/src/SourceRepository/stacken-zephyr/clients/zcomsat/zcomsat2.c,v $
 *	$Author: lha $
 *
 *	Copyright (c) 1987,1988 by the Massachusetts Institute of Technology.
 *	For copying and distribution information, see the file
 *	"mit-copyright.h". 
 */


#include <sysdep.h>
#include <zephyr/mit-copyright.h>
#include <zephyr/zephyr.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <sys/param.h>			/* for MAXHOSTNAMELEN */
#include <com_err.h>
#include <errno.h>
#include <sys/socket.h>

#ifndef lint
static char rcsid_zcomsat_c[] = "$Header: /afs/stacken.kth.se/src/SourceRepository/stacken-zephyr/clients/zcomsat/zcomsat2.c,v 1.1.1.1 1998/01/27 11:07:07 lha Exp $";
#endif /* lint */

#define MAIL_CLASS "MAIL"
#define MAIL_INSTANCE "POP"

main(argc,argv)
	int argc;
	char *argv[];
{
	ZNotice_t notice;
	struct hostent *hent;
	int retval;
	register int i;
	char *whoami,myhost[MAXHOSTNAMELEN],mysender[BUFSIZ];
	char *lines[2];
	char from[BUFSIZ] ;
	char *tmp ;
	struct sockaddr_in peer ;
	int peersize = sizeof(peer) ;
	
	openlog("zcomsat", LOG_PID, LOG_DAEMON);

	whoami = argv[0];

	if ((retval = ZInitialize()) != ZERR_NONE) {
		com_err(whoami,retval,"while initializing");
		exit(1);
	} 

	if (gethostname(myhost,MAXHOSTNAMELEN) == -1) {
		com_err(whoami,errno,"Can't get hostname");
		exit(1);
	}
	myhost[MAXHOSTNAMELEN-1] = '\0';

	if (!(hent = gethostbyname(myhost))) {
		com_err(whoami,errno,"Can't get canonical hostname");
		exit(1);
	}

	(void) strncpy(myhost,hent->h_name,MAXHOSTNAMELEN);
	myhost[MAXHOSTNAMELEN-1] = '\0';


	/* get the message, its on format user@offset */

	i = recvfrom(0, from, BUFSIZ, 0, (struct sockaddr*) &peer, &peersize) ;
	if (i <= 0) {
	  syslog(LOG_INFO, "error reading comsat msg") ;
	  closelog() ;
	  exit (0) ;
	}

	/* procmail contacts via localhost */
	if (peer.sin_addr.s_addr != inet_addr("127.0.0.1")) {
	  syslog(LOG_AUTH, "Someone tries to fake a comsat msg from %s", inet_ntoa(peer.sin_addr.s_addr)) ;
	  exit(0) ;
	}

	
	from[BUFSIZ-1] = '\0' ;

	tmp = strchr(from, '@') ;
	/* Punch a hole in @ */
	if (tmp != NULL)
	  *tmp = '\0' ;

	lines[0] = myhost;
	lines[1] = "You have new mail.";
	
	(void) strcpy(mysender,"pop@");
	(void) strcat(mysender,ZGetRealm());

	(void) memset((char *)&notice, 0, sizeof(notice));
	notice.z_kind = UNSAFE;
	notice.z_class = MAIL_CLASS;
	notice.z_class_inst = MAIL_INSTANCE;
	notice.z_opcode = "";
	notice.z_sender = mysender;
	notice.z_default_format = "From Post Office $1:\n$2";
	
	notice.z_recipient = from ;
	
	if ((retval = ZSendList(&notice,lines,2,ZNOAUTH)) != ZERR_NONE) {
	  com_err(whoami,retval,"while sending notice");
	  closelog() ;
	  exit(1);
	} 

	closelog() ;
	return 0 ;
}
