#include "signal.h"
#include "substdio.h"
#include "stralloc.h"
#include "subfd.h"
#include "sgetopt.h"
#include "getline.h"
#include "alloc.h"
#include "str.h"
#include "hfield.h"
#include "newfield.h"
#include "token.h"
#include "control.h"
#include "conf-home.h"
#include "env.h"
#include "gen_alloc.h"
#include "gen_allocdefs.h"
#include "error.h"
#include "qqtalk.h"
#include "now.h"
#include "exit.h"
#include "headerbody.h"

datetime_sec starttime;

char *mailhost;
char *mailuser;
int mailusertokentype;

stralloc control_idhost = {0};
stralloc control_defaultdomain = {0};
stralloc control_defaulthost = {0};
stralloc control_plusdomain = {0};

stralloc sender = {0};
stralloc envsbuf = {0};
token_alloc envs = {0};
int flagrh;

int flagqueue;
struct qqtalk qqt;

void put(s,len) char *s; int len;
{ if (flagqueue) qqtalk_put(&qqt,s,len); else substdio_put(subfdout,s,len); }
void puts(s) char *s; { put(s,str_len(s)); }

void die() { _exit(1); }
void die_nomem() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: out of memory\n"); die(); }
void die_invalid(sa) stralloc *sa; {
 substdio_putsflush(subfderr,"qmail-inject: fatal: invalid header field: ");
 substdio_putflush(subfderr,sa->s,sa->len); die(); }
void die_exec() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: unable to exec qmail-queue\n"); die(); }
void die_qqt() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: unable to run qmail-queue\n"); die(); }
void die_chdir() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: internal bug\n"); die(); }
void die_bug() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: internal bug\n"); die(); }
void die_read() {
 if (errno == error_nomem) die_nomem();
 substdio_putsflush(subfderr,"qmail-inject: fatal: read error\n"); die(); }
void doordie(sa,r) stralloc *sa; int r; {
 if (r == 1) return; if (r == -1) die_nomem();
 substdio_putsflush(subfderr,"qmail-inject: fatal: unable to parse this: ");
 substdio_putflush(subfderr,sa->s,sa->len); die(); }

void die_comm() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: qmail-queue lost communications link\n"); die(); }
void die_qq() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: qmail-queue died\n"); die(); }
void die_qqwrite() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: qmail-queue unable to write message to disk\n"); die(); }
void die_qqsig() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: qmail-queue was killed\n"); die(); }
void die_qqtimeout() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: qmail-queue timed out\n"); die(); }
void die_qqtoolong() {
 substdio_putsflush(subfderr,"qmail-inject: fatal: qmail-queue unhappy with long addresses\n"); die(); }

GEN_ALLOC_typedef(saa,stralloc,sa,len,a)
GEN_ALLOC_readyplus(saa,stralloc,sa,len,a,i,n,x,10,saa_readyplus)

static stralloc sauninit = {0};

saa savedh = {0};
saa hrlist = {0};
saa hrrlist = {0};
saa reciplist = {0};
int flagresent;

void exitnicely()
{
 if (!flagqueue) substdio_flush(subfdout);

 if (flagqueue)
  {
   int i;

   if (!stralloc_0(&sender)) die_nomem();
   qqtalk_from(&qqt,sender.s);

   for (i = 0;i < reciplist.len;++i)
    {
     if (!stralloc_0(&reciplist.sa[i])) die_nomem();
     qqtalk_to(&qqt,reciplist.sa[i].s);
    }
   if (flagrh)
     if (flagresent)
       for (i = 0;i < hrrlist.len;++i)
	{
         if (!stralloc_0(&hrrlist.sa[i])) die_nomem();
	 qqtalk_to(&qqt,hrrlist.sa[i].s);
	}
     else
       for (i = 0;i < hrlist.len;++i)
	{
         if (!stralloc_0(&hrlist.sa[i])) die_nomem();
	 qqtalk_to(&qqt,hrlist.sa[i].s);
	}

   switch(qqtalk_close(&qqt))
    {
     case 0: break;
     case QQT_CRASHED: die_qqsig();
     case QQT_USAGE: case QQT_BUG: die_bug();
     case QQT_EXECSOFT: case QQT_EXECHARD: die_exec();
     case QQT_NOMEM: die_nomem();
     case QQT_READ: die_comm();
     case QQT_WRITE: die_qqwrite();
     case QQT_TOOLONG: die_qqtoolong();
     case QQT_TIMEOUT: die_qqtimeout();
     default: die_qq();
    }
  }

 _exit(0);
}

void savedh_append(h)
stralloc *h;
{
 if (!saa_readyplus(&savedh,1)) die_nomem();
 savedh.sa[savedh.len] = sauninit;
 if (!stralloc_copy(savedh.sa + savedh.len,h)) die_nomem();
 ++savedh.len;
}

void savedh_print()
{
 int i;

 for (i = 0;i < savedh.len;++i)
   put(savedh.sa[i].s,savedh.sa[i].len);
}

stralloc defaultdomainbuf = {0};
token_alloc defaultdomain = {0};
stralloc defaulthostbuf = {0};
token_alloc defaulthost = {0};
stralloc plusdomainbuf = {0};
token_alloc plusdomain = {0};

void rwroute(addr)
token_alloc *addr;
{
 if (addr->t[addr->len - 1].type == TOKEN_AT)
   while (addr->len)
     if (addr->t[--addr->len].type == TOKEN_COLON)
       return;
}

void rwextraat(addr)
token_alloc *addr;
{
 int i;
 if (addr->t[0].type == TOKEN_AT)
  {
   --addr->len;
   for (i = 0;i < addr->len;++i)
     addr->t[i] = addr->t[i + 1];
  }
}

void rwextradot(addr)
token_alloc *addr;
{
 int i;
 if (addr->t[0].type == TOKEN_DOT)
  {
   --addr->len;
   for (i = 0;i < addr->len;++i)
     addr->t[i] = addr->t[i + 1];
  }
}

void rwnoat(addr)
token_alloc *addr;
{
 int i;
 int shift;

 for (i = 0;i < addr->len;++i)
   if (addr->t[i].type == TOKEN_AT)
     return;
 shift = defaulthost.len;
 if (!token_readyplus(addr,shift)) die_nomem();
 for (i = addr->len - 1;i >= 0;--i)
   addr->t[i + shift] = addr->t[i];
 addr->len += shift;
 for (i = 0;i < shift;++i)
   addr->t[i] = defaulthost.t[shift - 1 - i];
}

void rwnodot(addr)
token_alloc *addr;
{
 int i;
 int shift;
 for (i = 0;i < addr->len;++i)
   if (addr->t[i].type == TOKEN_DOT)
     return;
 for (i = 0;i < addr->len;++i)
   if (addr->t[i].type == TOKEN_LITERAL)
     return;
 shift = defaultdomain.len;
 if (!token_readyplus(addr,shift)) die_nomem();
 for (i = addr->len - 1;i >= 0;--i)
   addr->t[i + shift] = addr->t[i];
 addr->len += shift;
 for (i = 0;i < shift;++i)
   addr->t[i] = defaultdomain.t[shift - 1 - i];
}

void rwplus(addr)
token_alloc *addr;
{
 int i;
 int shift;

 if (addr->t[0].type != TOKEN_ATOM) return;
 if (!addr->t[0].slen) return;
 if (addr->t[0].s[addr->t[0].slen - 1] != '+') return;

 --addr->t[0].slen; /* remove + */

 shift = plusdomain.len;
 if (!token_readyplus(addr,shift)) die_nomem();
 for (i = addr->len - 1;i >= 0;--i)
   addr->t[i + shift] = addr->t[i];
 addr->len += shift;
 for (i = 0;i < shift;++i)
   addr->t[i] = plusdomain.t[shift - 1 - i];
}

void rwgeneric(addr)
token_alloc *addr;
{
 if (!addr->len) return; /* don't rewrite <> */
 if (addr->len >= 2)
   if (addr->t[1].type == TOKEN_AT)
     if (addr->t[0].type == TOKEN_LITERAL)
       if (!addr->t[0].slen) /* don't rewrite <foo@[]> */
	 return;
 rwroute(addr);
 if (!addr->len) return; /* <@foo:> -> <> */
 rwextradot(addr);
 if (!addr->len) return; /* <.> -> <> */
 rwextraat(addr);
 if (!addr->len) return; /* <@> -> <> */
 rwnoat(addr);
 rwplus(addr);
 rwnodot(addr);
}

int rwreturn(addr)
token_alloc *addr;
{
 rwgeneric(addr);
 if (!sender.s)
  {
   token_reverse(addr);
   if (token_unquote(&sender,addr) != 1) die_nomem();
   token_reverse(addr);
  }
 return 1;
}

int rwsender(addr)
token_alloc *addr;
{
 rwgeneric(addr);
 return 1;
}

void rwrecip(addr,xl)
token_alloc *addr;
saa *xl;
{
 rwgeneric(addr);
 token_reverse(addr);
 if (!saa_readyplus(xl,1)) die_nomem();
 xl->sa[xl->len] = sauninit;
 if (token_unquote(&xl->sa[xl->len],addr) != 1) die_nomem();
 ++xl->len;
 token_reverse(addr);
}

int rwhrr(addr) token_alloc *addr;
{ rwrecip(addr,&hrrlist); return 1; }
int rwhr(addr) token_alloc *addr;
{ rwrecip(addr,&hrlist); return 1; }

int htypeseen[H_NUM];
stralloc hfbuf = {0};
token_alloc hfin = {0};
token_alloc hfrewrite = {0};
token_alloc hfaddr = {0};

void doheaderfield(h)
stralloc *h;
{
 int htype;
 int flagrewrite;
 int flagrecip;
 int flagrr;

 htype = hfield_known(h->s,h->len);
 if (htype)
   htypeseen[htype] = 1;
 else
   if (!hfield_valid(h->s,h->len))
     die_invalid(h);

 flagrewrite = 0;
 flagrecip = 0;
 flagrr = 0;
 switch(htype)
  {
   case H_R_TO: case H_R_CC: case H_R_BCC:
     flagrr = 1;
   case H_TO: case H_CC: case H_BCC: case H_APPARENTLYTO:
     flagrecip = 1;
   case H_SENDER: case H_FROM: case H_REPLYTO:
   case H_RETURNRECEIPTTO: case H_ERRORSTO: case H_RETURNPATH:
   case H_R_SENDER: case H_R_FROM: case H_R_REPLYTO:
     flagrewrite = 1;
     break;
  }

 if (flagrewrite)
  {
   doordie(h,token_parse(&hfin,h,&hfbuf));
   doordie(h,token_addrlist(&hfrewrite,&hfaddr,&hfin,(htype == H_RETURNPATH) ? rwreturn : (flagrecip ? (flagrr ? rwhrr : rwhr) : rwsender)));
   if (token_unparse(h,&hfrewrite) != 1)
     die_nomem();
  }

 if (htype == H_BCC) return;
 if (htype == H_R_BCC) return;
 if (htype == H_RETURNPATH) return;
 if (htype == H_CONTENTLENGTH) return; /* some things are just too stupid */
 savedh_append(h);
}

void dobody(h)
stralloc *h;
{
 put(h->s,h->len);
}

stralloc torecip = {0};
token_alloc tr = {0};

void dorecip(s)
char *s;
{
 if (!stralloc_copys(&torecip,s)) die_nomem();
 switch(token_parse(&tr,&torecip,&hfbuf))
  {
   case -1: die_nomem();
   case 0:
     substdio_puts(subfderr,"qmail-inject: fatal: unable to parse address: ");
     substdio_puts(subfderr,s);
     substdio_putsflush(subfderr,"\n");
     die();
  }
 token_reverse(&tr);
 rwrecip(&tr,&reciplist);
}

stralloc defaultfrom = {0};
token_alloc df = {0};

void defaultfrommake()
{
 char *fullname;
 fullname = env_get("MAILNAME");
 if (!fullname) fullname = env_get("NAME");
 if (!token_ready(&df,10)) die_nomem();
 df.len = 0;
 df.t[df.len].type = TOKEN_ATOM;
 df.t[df.len].s = "From";
 df.t[df.len].slen = 4;
 ++df.len;
 df.t[df.len].type = TOKEN_COLON;
 ++df.len;
 df.t[df.len].type = mailusertokentype;
 df.t[df.len].s = mailuser;
 df.t[df.len].slen = str_len(mailuser);
 ++df.len;
 if (mailhost)
  {
   df.t[df.len].type = TOKEN_AT;
   ++df.len;
   df.t[df.len].type = TOKEN_ATOM;
   df.t[df.len].s = mailhost;
   df.t[df.len].slen = str_len(mailhost);
   ++df.len;
  }
 if (fullname)
  {
   df.t[df.len].type = TOKEN_COMMENT;
   df.t[df.len].s = fullname;
   df.t[df.len].slen = str_len(fullname);
   ++df.len;
  }
 if (token_unparse(&defaultfrom,&df) != 1) die_nomem();
 doordie(&defaultfrom,token_parse(&df,&defaultfrom,&hfbuf));
 doordie(&defaultfrom,token_addrlist(&hfrewrite,&hfaddr,&df,rwsender));
 if (token_unparse(&defaultfrom,&hfrewrite) != 1) die_nomem();
}

stralloc defaultreturnpath = {0};
token_alloc drp = {0};

void dodefaultreturnpath()
{
 if (!token_ready(&drp,10)) die_nomem();
 drp.len = 0;
 drp.t[drp.len].type = TOKEN_ATOM;
 drp.t[drp.len].s = "Return-Path";
 drp.t[drp.len].slen = 11;
 ++drp.len;
 drp.t[drp.len].type = TOKEN_COLON;
 ++drp.len;
 drp.t[drp.len].type = mailusertokentype;
 drp.t[drp.len].s = mailuser;
 drp.t[drp.len].slen = str_len(mailuser);
 ++drp.len;
 if (mailhost)
  {
   drp.t[drp.len].type = TOKEN_AT;
   ++drp.len;
   drp.t[drp.len].type = TOKEN_ATOM;
   drp.t[drp.len].s = mailhost;
   drp.t[drp.len].slen = str_len(mailhost);
   ++drp.len;
  }
 if (token_unparse(&defaultreturnpath,&drp) != 1) die_nomem();
 doordie(&defaultreturnpath,token_parse(&drp,&defaultreturnpath,&hfbuf));
 doordie(&defaultreturnpath,token_addrlist(&hfrewrite,&hfaddr,&drp,rwreturn));
 if (token_unparse(&defaultreturnpath,&hfrewrite) != 1) die_nomem();
}

void finishheader()
{
 flagresent =
   htypeseen[H_R_SENDER] || htypeseen[H_R_FROM] || htypeseen[H_R_REPLYTO]
   || htypeseen[H_R_TO] || htypeseen[H_R_CC] || htypeseen[H_R_BCC]
   || htypeseen[H_R_DATE] || htypeseen[H_R_MESSAGEID];

 if (!sender.s)
   dodefaultreturnpath();

 /* could check at this point whether there are any recipients */
 if (flagqueue)
   if (qqtalk_open(&qqt,0) == -1) die_qqt();

 if (flagresent)
  {
   if (!htypeseen[H_R_DATE])
    {
     if (!newfield_datemake(starttime)) die_nomem();
     puts("Resent-");
     puts(newfield_date);
    }
   if (!htypeseen[H_R_MESSAGEID])
    {
     if (!newfield_msgidmake(control_idhost.s,control_idhost.len,starttime)) die_nomem();
     puts("Resent-");
     puts(newfield_msgid);
    }
   if (!htypeseen[H_R_FROM])
    {
     defaultfrommake();
     puts("Resent-");
     put(defaultfrom.s,defaultfrom.len);
    }
   if (!htypeseen[H_R_TO] && !htypeseen[H_R_CC])
    {
     if (!newfield_ccmake()) die_nomem();
     puts("Resent-");
     puts(newfield_cc);
    }
  }
 else
  {
   if (!htypeseen[H_DATE])
    {
     if (!newfield_datemake(starttime)) die_nomem();
     puts(newfield_date);
    }
   if (!htypeseen[H_MESSAGEID])
    {
     if (!newfield_msgidmake(control_idhost.s,control_idhost.len,starttime)) die_nomem();
     puts(newfield_msgid);
    }
   if (!htypeseen[H_FROM])
    {
     defaultfrommake();
     put(defaultfrom.s,defaultfrom.len);
    }
   if (!htypeseen[H_TO] && !htypeseen[H_CC])
    {
     if (!newfield_ccmake()) die_nomem();
     puts(newfield_cc);
    }
  }

 savedh_print();
}

void getcontrols()
{
 static stralloc sa = {0};

 if (control_init() == -1) die_read();

 if (control_rldef(&control_defaultdomain,"control/defaultdomain",1,"defaultdomain") != 1)
   die_read();
 if (!stralloc_copys(&sa,".")) die_nomem();
 if (!stralloc_cat(&sa,&control_defaultdomain)) die_nomem();
 doordie(&sa,token_parse(&defaultdomain,&sa,&defaultdomainbuf));

 if (control_rldef(&control_defaulthost,"control/defaulthost",1,"defaulthost") != 1)
   die_read();
 if (!stralloc_copys(&sa,"@")) die_nomem();
 if (!stralloc_cat(&sa,&control_defaulthost)) die_nomem();
 doordie(&sa,token_parse(&defaulthost,&sa,&defaulthostbuf));

 if (control_rldef(&control_plusdomain,"control/plusdomain",1,"plusdomain") != 1)
   die_read();
 if (!stralloc_copys(&sa,".")) die_nomem();
 if (!stralloc_cat(&sa,&control_plusdomain)) die_nomem();
 doordie(&sa,token_parse(&plusdomain,&sa,&plusdomainbuf));

 if (control_rldef(&control_idhost,"control/idhost",1,"idhost") != 1)
   die_read();
}

#define RECIP_DEFAULT 1
#define RECIP_ARGS 2
#define RECIP_HEADER 3
#define RECIP_AH 4

void main(argc,argv)
int argc;
char **argv;
{
 int i;
 int opt;
 int recipstrategy;

 signal_init();

 starttime = now();

 mailhost = env_get("MAILHOST");
 mailuser = env_get("MAILUSER");
 if (!mailuser) mailuser = env_get("USER");
 if (!mailuser) mailuser = env_get("LOGNAME");
 if (!mailuser) mailuser = "anonymous";

 mailusertokentype = TOKEN_ATOM;
 if (quote_need(mailuser,str_len(mailuser))) mailusertokentype = TOKEN_QUOTE;

 for (i = 0;i < H_NUM;++i) htypeseen[i] = 0;

 recipstrategy = RECIP_DEFAULT;
 flagqueue = 1;

 if (chdir(CONF_HOME) == -1)
   die_chdir();
 getcontrols();

 if (!saa_readyplus(&hrlist,1)) die_nomem();
 if (!saa_readyplus(&hrrlist,1)) die_nomem();
 if (!saa_readyplus(&reciplist,1)) die_nomem();

 while ((opt = getopt(argc,argv,"aAhHnNf:")) != opteof)
   switch(opt)
    {
     case 'a': recipstrategy = RECIP_ARGS; break;
     case 'A': recipstrategy = RECIP_DEFAULT; break;
     case 'h': recipstrategy = RECIP_HEADER; break;
     case 'H': recipstrategy = RECIP_AH; break;
     case 'n': flagqueue = 0; break;
     case 'N': flagqueue = 1; break;
     case 'f':
       if (!stralloc_copys(&sender,optarg)) die_nomem();
       doordie(&sender,token_parse(&envs,&sender,&envsbuf));
       token_reverse(&envs);
       rwgeneric(&envs);
       token_reverse(&envs);
       if (token_unquote(&sender,&envs) != 1) die_nomem();
       break;
     case '?':
     default:
       die();
    }
 argc -= optind;
 argv += optind;

 if (recipstrategy == RECIP_DEFAULT)
   recipstrategy = (*argv ? RECIP_ARGS : RECIP_HEADER);

 if (recipstrategy != RECIP_HEADER)
   while (*argv)
     dorecip(*argv++);

 flagrh = (recipstrategy != RECIP_ARGS);

 if (headerbody(subfdin,doheaderfield,finishheader,dobody) == -1)
   die_read();
 exitnicely();
}
