/*
 *
 * EnderUnix Software Development Team @ Turkey
 * (c) 2002 Istanbul, Turkiye
 * 
 * See COPYING for copyright and copying restrictions
 *
 */

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>

#include <sys/stat.h>
#include <sys/types.h>

#include "wildmat.h"
#include "functions.h"
#include "loadconfig.h"
#include "parser.h"

extern char logtype[VALSIZE];

void readLogFile(char *fn) 
{	
	FILE *fp;
	char buf[1024];
	struct stat st;
	hist_stat old;
	hist_stat new;

	get_saved_pos(&old);
	if ((fp = fopen(fn, "r")) == NULL) {
		fprintf(stderr, "fopen: %s: %s\n", fn, strerror(errno));
		exit(-1);
	}
	/* Get the current values of last read log file's inode number
	 *          * and byte offset  */
        if ((stat(fn, &st)) == -1) {
                fprintf(stderr, "Couldnt' stat %s: %s\n", fn, strerror(errno));
                exit(-1);
        }
        /* If both inode numbers are the same, we assume that log file
	 *          * has not been changed (i.e rotated, removed), so we can
	 *                   * go past offset bytes and continue to read new logs */
        if (st.st_ino == old.inode)
                fseek(fp, old.saved_pos, SEEK_SET);


	if (strcmp(logtype, "qmail") == 0) {
		while ((fgets(buf, 1024, fp)) != NULL) 
			qmail_parseline(buf);
	}
	else if ((strcmp(logtype, "sendmail") == 0) ||  (strcmp(logtype, "postfix") == 0)) {
		while ((fgets(buf, 1024, fp)) != NULL) 
			sendmail_parseline(buf);
	}
        new.inode = st.st_ino;
        new.saved_pos = ftell(fp);
        save_pos(&new);
	fclose(fp);
}

void qmail_parseline(char *str)
{
	char *p;
	char *email;
	char *save;

	if ((strstr(str, " from ")) == NULL)
		return ;
    	p = str;
    	while (strncmp (p," from ",6))
        	p++;
    	p = p + 7;
	email = (char *)calloc(strlen(p) + 1, sizeof(char));
	save = email;
	while ((*email++ = *p++) != '>')
		;
	*(--email) = '\0';
	if (strlen(save) == 0 || save[0] =='#') 
		return;
	check_addr(save);
}

void sendmail_parseline(char *str)
{
	char *p;
	char *email;
	char *save;
	

	if ((strstr(str, " from=")) == NULL)
		return ;

    	p = str;

    	while (strncmp (p," from=", 6))
        	p++;
    	p = p + 6;

	email = (char *)calloc(strlen(p) + 1, (sizeof(char)));
	save = email;

	while ((*email++ = *p++) != ',')
		;
	*(--email) = '\0';

	if (strlen(save) == 0) 
		return ;
	check_addr(save);
}


syntax highlighted by Code2HTML, v. 0.9.1