/****************************************************************************
*                                                                           *
*	mailutil.c - A few functions from bmutil.c and mailbox.c                 *
*                                                                           *
*  29.08.94 DFN -	Initial version														 *
*                                                                           *
****************************************************************************/

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "global.h"
#include "ftpserv.h"
#include "smtp.h"
#include "proc.h"
#include "usock.h"
#include "socket.h"
#include "telnet.h"
#include "timer.h"
#include "session.h"
#include "files.h"
#include "bm.h"
#include "mailbox.h"

char *rewrite_address(char *addr);

static void string_tidy(char *str);
   
/*---------------------------------------------------------------------------
	Hdrs - Array of valid mail headers, used by the htype function.
---------------------------------------------------------------------------*/

char *Hdrs[] = {
	"Approved: ",
	"From: ",
	"To: ",
	"Date: ",
	"Message-Id: ",
	"Subject: ",
	"Received: ",
	"Sender: ",
	"Reply-To: ",
	"Status: ",
	"X-BBS-Msg-Type: ",
	"X-Forwarded-To: ",
	"Cc: ",
	"Return-Receipt-To: ",
	"Apparently-To: ",
	"Errors-To: ",
	"Organization: ",
	NULLCHAR
};


/*---------------------------------------------------------------------------
	htype - Return the header type
---------------------------------------------------------------------------*/
	
int htype(char *s)
{
	int	i;
	char  *p;

	p = s;

	/* check to see if there is a ':' before and white space 					*/

	while (*p != '\0' && *p != ' ' && *p != ':')
		p++;
		
	if (*p != ':')
		return NOHEADER;

	for (i = 0; Hdrs[i] != NULLCHAR; i++) {
		if (strnicmp(Hdrs[i], s, strlen(Hdrs[i])) == 0)
			return i;
	}
	return UNKNOWN;
}

/*---------------------------------------------------------------------------
	getaddress - Parse a string to extract an address of the form 'user@host'
	             Vaild input formats:-  Text: <user@host>
	                                    Text: user@host (Text)
---------------------------------------------------------------------------*/

char *getaddress(char *string, int cont)
{
	int par = 0;
	char *cp, *ap = NULLCHAR;

	if ((cp = getname(string)) != NULLCHAR) 	/* Look for <> style address 	*/
	     return cp;
	     
	cp = string;
	
	if (!cont)
		if ((cp = strchr(string, ':')) == NULLCHAR)	/* Skip the token 		*/
			return NULLCHAR;
		else
			++cp;
			
	for ( ; *cp != '\0'; ++cp) {
		if (par && *cp == ')') {
			--par;
			continue;
	   }
	   
	   if (*cp == '(')								/* Ignore text within () 		*/
			++par;
			if (par)
		  		continue;
	     	if (*cp == ' ' || *cp == '\t' || *cp == '\n' || *cp == ',') {
		  		if (ap != NULLCHAR)
		       	break;
		  		continue;
		  	}
		  	
	     if (ap == NULLCHAR)
		  	ap = cp;
	}
	
	*cp = '\0';
	return ap;
}


/*---------------------------------------------------------------------------
	rewrite_address - Read the rewrite file for lines where the first word is
						   a regular expression and the second word are rewriting
                     rules.  The special character '$' followed by a digit
                     denotes the string that matched a '*' character. The '*'
                     characters are numbered from 1 to 9.  Example: the line
                     "*@*.* $2@$1.ampr.org" would rewrite the address
                     "foo@bar.xxx" to "bar@foo.ampr.org".
                     $H is replaced by our hostname, and $$ is an escaped $
                     character.  If the third word on the line has an 'r'
                     character in it, the function will recurse with the new
                     address.
---------------------------------------------------------------------------*/

char *rewrite_address(char *addr)
{
	int cnt;
	char *argv[10], *cp, *cp2, *retstr;
	char buf[MBXLINE];  
	FILE *fp;
	
	if ((fp = fopen(Rewritefile, READ_TEXT)) == NULLFILE)
		return NULLCHAR;
		
	memset((char *)argv, 0, 10*sizeof(char *));
	
	while (fgets(buf, MBXLINE, fp) != NULLCHAR) {
		if (*buf == '#')								/* skip commented lines 		*/
			continue;

		string_tidy(buf);   							/* clean up the buffer 			*/

		if ((cp = strchr(buf, ' ')) == NULLCHAR) /* get the first word 		*/
			if ((cp = strchr(buf, '\t')) == NULLCHAR)
				continue;

		*cp = '\0';
		
		if ((cp2 = strchr(buf, '\t')) != NULLCHAR) {
			*cp = ' ';
			cp  = cp2;
			*cp = '\0';
		}
		
		if (!wildmat(addr, buf, argv))
			continue;									/* no match 						*/
		rip(++cp);
		cp2 = retstr = (char *)callocw(1, MBXLINE);

		while (*cp != '\0' && *cp != ' ' && *cp != '\t')
			if (*cp == '$') {
				if (isdigit(*(++cp)))
					if (argv[*cp - '0'-1] != '\0')
						strcat(cp2, argv[*cp - '0'-1]);

				if (*cp == 'h' || *cp == 'H') 	/* Our hostname 					*/
					strcat(cp2, Hostname);

				if (*cp == '$')						/* Escaped $ character 			*/
					strcat(cp2, "$");
				cp2 = retstr + strlen(retstr);
				cp++;
			}
			else
				*cp2++ = *cp++;
				
		for (cnt=0; argv[cnt] != NULLCHAR; ++cnt)
			free(argv[cnt]);
			
		fclose(fp);
		
		/*
			If there remains an 'r' character on the line, repeat everything
			by recursing.
		*/
		
		if (strchr(cp, 'r') != NULLCHAR || strchr(cp, 'R') != NULLCHAR) {
			if ((cp2 = rewrite_address(retstr)) != NULLCHAR) {
				free(retstr);
				return cp2;
			}
		}
		return retstr;
	}
	
	fclose(fp);
	return NULLCHAR;
}


/*---------------------------------------------------------------------------
	stribg_tidy - Reduce runs of whitespace to 1 space
---------------------------------------------------------------------------*/
	
static void string_tidy(char *str)   
{
	int c;
	char *ip=str;
	char *op=str;

	while (c = *ip++) {
		if (c != ' ' && c != '\t') {
      	*op++ = c;
      	continue;
    	}

		*op++ = ' ';

		while (*ip && (*ip == ' ' || *ip =='\t'))
			ip++;
   }
   
	*op='\0';  
}

/****************************************************************************
*	T H E   E N D																				 *
****************************************************************************/ 
	
