libev migration - add shutdown handlers
[citadel.git] / citadel / modules / smtp / serv_smtpeventclient.c
1 /*
2  * This module is an SMTP and ESMTP implementation for the Citadel system.
3  * It is compliant with all of the following:
4  *
5  * RFC  821 - Simple Mail Transfer Protocol
6  * RFC  876 - Survey of SMTP Implementations
7  * RFC 1047 - Duplicate messages and SMTP
8  * RFC 1652 - 8 bit MIME
9  * RFC 1869 - Extended Simple Mail Transfer Protocol
10  * RFC 1870 - SMTP Service Extension for Message Size Declaration
11  * RFC 2033 - Local Mail Transfer Protocol
12  * RFC 2197 - SMTP Service Extension for Command Pipelining
13  * RFC 2476 - Message Submission
14  * RFC 2487 - SMTP Service Extension for Secure SMTP over TLS
15  * RFC 2554 - SMTP Service Extension for Authentication
16  * RFC 2821 - Simple Mail Transfer Protocol
17  * RFC 2822 - Internet Message Format
18  * RFC 2920 - SMTP Service Extension for Command Pipelining
19  *  
20  * The VRFY and EXPN commands have been removed from this implementation
21  * because nobody uses these commands anymore, except for spammers.
22  *
23  * Copyright (c) 1998-2009 by the citadel.org team
24  *
25  *  This program is free software; you can redistribute it and/or modify
26  *  it under the terms of the GNU General Public License as published by
27  *  the Free Software Foundation; either version 3 of the License, or
28  *  (at your option) any later version.
29  *
30  *  This program is distributed in the hope that it will be useful,
31  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
32  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  *  GNU General Public License for more details.
34  *
35  *  You should have received a copy of the GNU General Public License
36  *  along with this program; if not, write to the Free Software
37  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
38  */
39
40 #include "sysdep.h"
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <stdio.h>
44 #include <termios.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <sys/types.h>
50 #include <syslog.h>
51
52 #if TIME_WITH_SYS_TIME
53 # include <sys/time.h>
54 # include <time.h>
55 #else
56 # if HAVE_SYS_TIME_H
57 #  include <sys/time.h>
58 # else
59 #  include <time.h>
60 # endif
61 #endif
62 #include <sys/wait.h>
63 #include <ctype.h>
64 #include <string.h>
65 #include <limits.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "control.h"
76 #include "user_ops.h"
77 #include "database.h"
78 #include "msgbase.h"
79 #include "internet_addressing.h"
80 #include "genstamp.h"
81 #include "domain.h"
82 #include "clientsocket.h"
83 #include "locate_host.h"
84 #include "citadel_dirs.h"
85
86 #include "ctdl_module.h"
87
88 #include "smtp_util.h"
89 #include "event_client.h"
90 #include "smtpqueue.h"
91
92 #ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
93 /*****************************************************************************/
94 /*               SMTP CLIENT (OUTBOUND PROCESSING) STUFF                     */
95 /*****************************************************************************/
96
97 typedef enum _eSMTP_C_States {
98         eConnect, 
99         eEHLO,
100         eHELO,
101         eSMTPAuth,
102         eFROM,
103         eRCPT,
104         eDATA,
105         eDATABody,
106         eDATATerminateBody,
107         eQUIT,
108         eMaxSMTPC
109 } eSMTP_C_States;
110
111 const double SMTP_C_ConnTimeout = 300.; /* wail 1 minute for connections... */
112 const double SMTP_C_ReadTimeouts[eMaxSMTPC] = {
113         300., /* Greeting... */
114         30., /* EHLO */
115         30., /* HELO */
116         30., /* Auth */
117         30., /* From */
118         90., /* RCPT */
119         30., /* DATA */
120         90., /* DATABody */
121         90., /* end of body... */
122         30.  /* QUIT */
123 };
124 const double SMTP_C_SendTimeouts[eMaxSMTPC] = {
125         90., /* Greeting... */
126         30., /* EHLO */
127         30., /* HELO */
128         30., /* Auth */
129         30., /* From */
130         30., /* RCPT */
131         30., /* DATA */
132         90., /* DATABody */
133         900., /* end of body... */
134         30.  /* QUIT */
135 };
136
137 static const ConstStr ReadErrors[eMaxSMTPC] = {
138         {HKEY("Connection broken during SMTP conversation")},
139         {HKEY("Connection broken during SMTP EHLO")},
140         {HKEY("Connection broken during SMTP HELO")},
141         {HKEY("Connection broken during SMTP AUTH")},
142         {HKEY("Connection broken during SMTP MAIL FROM")},
143         {HKEY("Connection broken during SMTP RCPT")},
144         {HKEY("Connection broken during SMTP DATA")},
145         {HKEY("Connection broken during SMTP message transmit")},
146         {HKEY("")}/* quit reply, don't care. */
147 };
148
149
150 typedef struct _stmp_out_msg {
151         MailQEntry *MyQEntry;
152         OneQueItem *MyQItem;
153         long n;
154         AsyncIO IO;
155
156         eSMTP_C_States State;
157
158         struct ares_mx_reply *AllMX;
159         struct ares_mx_reply *CurrMX;
160         const char *mx_port;
161         const char *mx_host;
162
163         struct hostent *OneMX;
164
165         ParsedURL *Relay;
166         ParsedURL *pCurrRelay;
167         StrBuf *msgtext;
168         char *envelope_from;
169         char user[1024];
170         char node[1024];
171         char name[1024];
172         char mailfrom[1024];
173 } SmtpOutMsg;
174
175 void DeleteSmtpOutMsg(void *v)
176 {
177         SmtpOutMsg *Msg = v;
178
179         ares_free_data(Msg->AllMX);
180         
181         FreeStrBuf(&Msg->msgtext);
182         FreeAsyncIOContents(&Msg->IO);
183         free(Msg);
184 }
185
186 eNextState SMTP_C_Shutdown(AsyncIO *IO);
187 eNextState SMTP_C_Timeout(AsyncIO *IO);
188 eNextState SMTP_C_ConnFail(AsyncIO *IO);
189 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
190 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
191 eNextState SMTP_C_Terminate(AsyncIO *IO);
192 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
193
194 typedef eNextState (*SMTPReadHandler)(SmtpOutMsg *Msg);
195 typedef eNextState (*SMTPSendHandler)(SmtpOutMsg *Msg);
196
197
198 #define SMTP_ERROR(WHICH_ERR, ERRSTR) do {\
199                 SendMsg->MyQEntry->Status = WHICH_ERR; \
200                 StrBufAppendBufPlain(SendMsg->MyQEntry->StatusMessage, HKEY(ERRSTR), 0); \
201                 return eAbort; } \
202         while (0)
203
204 #define SMTP_VERROR(WHICH_ERR) do {\
205                 SendMsg->MyQEntry->Status = WHICH_ERR; \
206                 StrBufPlain(SendMsg->MyQEntry->StatusMessage, \
207                             ChrPtr(SendMsg->IO.IOBuf) + 4, \
208                             StrLength(SendMsg->IO.IOBuf) - 4); \
209                 return eAbort; } \
210         while (0)
211
212 #define SMTP_IS_STATE(WHICH_STATE) (ChrPtr(SendMsg->IO.IOBuf)[0] == WHICH_STATE)
213
214 #define SMTP_DBG_SEND() CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: > %s\n", SendMsg->n, ChrPtr(SendMsg->IO.SendBuf.Buf))
215 #define SMTP_DBG_READ() CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: < %s\n", SendMsg->n, ChrPtr(SendMsg->IO.IOBuf))
216
217
218 void FinalizeMessageSend(SmtpOutMsg *Msg)
219 {
220         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
221         
222         if (DecreaseQReference(Msg->MyQItem)) 
223         {
224                 int nRemain;
225                 StrBuf *MsgData;
226
227                 nRemain = CountActiveQueueEntries(Msg->MyQItem);
228
229                 MsgData = SerializeQueueItem(Msg->MyQItem);
230                 /*
231                  * Uncompleted delivery instructions remain, so delete the old
232                  * instructions and replace with the updated ones.
233                  */
234                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
235                 smtpq_do_bounce(Msg->MyQItem,
236                                Msg->msgtext); 
237                 if (nRemain > 0) {
238                         struct CtdlMessage *msg;
239                         msg = malloc(sizeof(struct CtdlMessage));
240                         memset(msg, 0, sizeof(struct CtdlMessage));
241                         msg->cm_magic = CTDLMESSAGE_MAGIC;
242                         msg->cm_anon_type = MES_NORMAL;
243                         msg->cm_format_type = FMT_RFC822;
244                         msg->cm_fields['M'] = SmashStrBuf(&MsgData);
245                         CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
246                         CtdlFreeMessage(msg);
247                 }
248                 else {
249                         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->MessageID, 1, "");
250                         FreeStrBuf(&MsgData);
251                 }
252
253                 RemoveQItem(Msg->MyQItem);
254         }
255         DeleteSmtpOutMsg(Msg);
256 }
257
258
259 void SetConnectStatus(AsyncIO *IO)
260 {
261         
262         SmtpOutMsg *SendMsg = IO->Data;
263         char buf[256];
264         void *src;
265
266         buf[0] = '\0';
267
268         if (IO->IP6) {
269                 src = &IO->Addr.sin6_addr;
270         }
271         else {
272                 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->Addr;
273
274                 src = &addr->sin_addr.s_addr;
275         }
276
277         inet_ntop((IO->IP6)?AF_INET6:AF_INET,
278                   src,
279                   buf, sizeof(buf));
280         if (SendMsg->mx_host == NULL)
281                 SendMsg->mx_host = "<no name>";
282
283         CtdlLogPrintf(CTDL_DEBUG, 
284                       "SMTP client[%ld]: connecting to %s [%s]:%d ...\n", 
285                       SendMsg->n, 
286                       SendMsg->mx_host, 
287                       buf,
288                       SendMsg->IO.dport);
289
290         SendMsg->MyQEntry->Status = 5; 
291         StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
292                      "Timeout while connecting %s [%s]:%d ", 
293                      SendMsg->mx_host,
294                      buf,
295                      SendMsg->IO.dport);
296 }
297
298 eNextState mx_connect_relay_ip(AsyncIO *IO)
299 {
300         
301         SmtpOutMsg *SendMsg = IO->Data;
302
303         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
304
305         IO->IP6 = SendMsg->pCurrRelay->af == AF_INET6;
306         
307         if (SendMsg->pCurrRelay->Port != 0)
308                 IO->dport = SendMsg->pCurrRelay->Port;
309
310         memset(&IO->Addr, 0, sizeof(struct sockaddr_in6));
311         if (IO->IP6) {
312                 memcpy(&IO->Addr.sin6_addr.s6_addr, 
313                        &SendMsg->pCurrRelay->Addr,
314                        sizeof(struct in6_addr));
315
316                 IO->Addr.sin6_family = AF_INET6;
317                 IO->Addr.sin6_port = htons(IO->dport);
318         }
319         else {
320                 struct sockaddr_in *addr = (struct sockaddr_in*) &IO->Addr;
321                 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
322                 memcpy(&addr->sin_addr,///.s_addr, 
323                        &SendMsg->pCurrRelay->Addr,
324                        sizeof(struct in_addr));
325                 
326                 addr->sin_family = AF_INET;
327                 addr->sin_port = htons(IO->dport);
328         }
329
330         SetConnectStatus(IO);
331
332         return InitEventIO(IO, SendMsg, 
333                            SMTP_C_ConnTimeout, 
334                            SMTP_C_ReadTimeouts[0],
335                             1);
336 }
337
338 void get_one_mx_host_ip_done(void *Ctx, 
339                              int status,
340                              int timeouts,
341                              struct hostent *hostent)
342 {
343         AsyncIO *IO = (AsyncIO *) Ctx;
344         SmtpOutMsg *SendMsg = IO->Data;
345         eNextState State = eAbort;
346
347         if ((status == ARES_SUCCESS) && (hostent != NULL) ) {
348                 
349                 IO->IP6  = hostent->h_addrtype == AF_INET6;
350                 IO->HEnt = hostent;
351
352                 memset(&IO->Addr, 0, sizeof(struct in6_addr));
353                 if (IO->IP6) {
354                         memcpy(&IO->Addr.sin6_addr.s6_addr, 
355                                &hostent->h_addr_list[0],
356                                sizeof(struct in6_addr));
357                         
358                         IO->Addr.sin6_family = hostent->h_addrtype;
359                         IO->Addr.sin6_port = htons(IO->dport);
360                 }
361                 else {
362                         struct sockaddr_in *addr = (struct sockaddr_in*) &IO->Addr;
363                         /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
364 //                      addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
365                         memcpy(&addr->sin_addr.s_addr, hostent->h_addr_list[0], sizeof(uint32_t));
366                         
367                         addr->sin_family = hostent->h_addrtype;
368                         addr->sin_port = htons(IO->dport);
369                         
370                 }
371                 SendMsg->IO.HEnt = hostent;
372                 SetConnectStatus(IO);
373                 State = InitEventIO(IO, SendMsg, 
374                                    SMTP_C_ConnTimeout, 
375                                    SMTP_C_ReadTimeouts[0],
376                                    1);
377         }
378         if ((State == eAbort) && (IO->sock != -1))
379                 SMTP_C_Terminate(IO);
380 }
381
382 const unsigned short DefaultMXPort = 25;
383 eNextState get_one_mx_host_ip(AsyncIO *IO)
384 {
385         SmtpOutMsg * SendMsg = IO->Data;
386         const char *Hostname;
387         //char *endpart;
388         //char buf[SIZ];
389         InitC_ares_dns(IO);
390
391         if (SendMsg->CurrMX) {
392                 SendMsg->mx_host = SendMsg->CurrMX->host;
393                 SendMsg->CurrMX = SendMsg->CurrMX->next;
394         }
395
396         if (SendMsg->pCurrRelay != NULL) {
397                 SendMsg->mx_host = Hostname = SendMsg->pCurrRelay->Host;
398                 if (SendMsg->pCurrRelay->Port != 0)
399                         SendMsg->IO.dport = SendMsg->pCurrRelay->Port;
400         }
401         else if (SendMsg->mx_host != NULL) Hostname = SendMsg->mx_host;
402         else Hostname = SendMsg->node;
403
404         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
405
406         CtdlLogPrintf(CTDL_DEBUG, 
407                       "SMTP client[%ld]: looking up %s : %d ...\n", 
408                       SendMsg->n, 
409                       Hostname, 
410                       SendMsg->IO.dport);
411
412         ares_gethostbyname(SendMsg->IO.DNSChannel,
413                            Hostname,   
414                            AF_INET6, /* it falls back to ipv4 in doubt... */
415                            get_one_mx_host_ip_done,
416                            &SendMsg->IO);
417         return IO->NextState;
418 }
419
420
421 eNextState smtp_resolve_mx_done(AsyncIO *IO)
422 {
423         SmtpOutMsg * SendMsg = IO->Data;
424
425         QueryCbDone(IO);
426
427         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
428
429         SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
430
431         SendMsg->CurrMX = SendMsg->AllMX = IO->VParsedDNSReply;
432         //// TODO: should we remove the current ares context???
433         get_one_mx_host_ip(IO);
434         return IO->NextState;
435 }
436
437
438 eNextState resolve_mx_records(AsyncIO *IO)
439 {
440         SmtpOutMsg * SendMsg = IO->Data;
441
442         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
443
444         if (!QueueQuery(ns_t_mx, 
445                         SendMsg->node, 
446                         &SendMsg->IO, 
447                         smtp_resolve_mx_done))
448         {
449                 SendMsg->MyQEntry->Status = 5;
450                 StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
451                              "No MX hosts found for <%s>", SendMsg->node);
452                 return IO->NextState;
453         }
454         return eAbort;
455 }
456
457
458 int smtp_resolve_recipients(SmtpOutMsg *SendMsg)
459 {
460         const char *ptr;
461         char buf[1024];
462         int scan_done;
463         int lp, rp;
464         int i;
465
466         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
467
468         if ((SendMsg==NULL) || 
469             (SendMsg->MyQEntry == NULL) || 
470             (StrLength(SendMsg->MyQEntry->Recipient) == 0)) {
471                 return 0;
472         }
473
474         /* Parse out the host portion of the recipient address */
475         process_rfc822_addr(ChrPtr(SendMsg->MyQEntry->Recipient), 
476                             SendMsg->user, 
477                             SendMsg->node, 
478                             SendMsg->name);
479
480         CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: Attempting delivery to <%s> @ <%s> (%s)\n",
481                       SendMsg->n, SendMsg->user, SendMsg->node, SendMsg->name);
482         /* If no envelope_from is supplied, extract one from the message */
483         if ( (SendMsg->envelope_from == NULL) || 
484              (IsEmptyStr(SendMsg->envelope_from)) ) {
485                 SendMsg->mailfrom[0] = '\0';
486                 scan_done = 0;
487                 ptr = ChrPtr(SendMsg->msgtext);
488                 do {
489                         if (ptr = cmemreadline(ptr, buf, sizeof buf), *ptr == 0) {
490                                 scan_done = 1;
491                         }
492                         if (!strncasecmp(buf, "From:", 5)) {
493                                 safestrncpy(SendMsg->mailfrom, &buf[5], sizeof SendMsg->mailfrom);
494                                 striplt(SendMsg->mailfrom);
495                                 for (i=0; SendMsg->mailfrom[i]; ++i) {
496                                         if (!isprint(SendMsg->mailfrom[i])) {
497                                                 strcpy(&SendMsg->mailfrom[i], &SendMsg->mailfrom[i+1]);
498                                                 i=0;
499                                         }
500                                 }
501         
502                                 /* Strip out parenthesized names */
503                                 lp = (-1);
504                                 rp = (-1);
505                                 for (i=0; !IsEmptyStr(SendMsg->mailfrom + i); ++i) {
506                                         if (SendMsg->mailfrom[i] == '(') lp = i;
507                                         if (SendMsg->mailfrom[i] == ')') rp = i;
508                                 }
509                                 if ((lp>0)&&(rp>lp)) {
510                                         strcpy(&SendMsg->mailfrom[lp-1], &SendMsg->mailfrom[rp+1]);
511                                 }
512         
513                                 /* Prefer brokketized names */
514                                 lp = (-1);
515                                 rp = (-1);
516                                 for (i=0; !IsEmptyStr(SendMsg->mailfrom + i); ++i) {
517                                         if (SendMsg->mailfrom[i] == '<') lp = i;
518                                         if (SendMsg->mailfrom[i] == '>') rp = i;
519                                 }
520                                 if ( (lp>=0) && (rp>lp) ) {
521                                         SendMsg->mailfrom[rp] = 0;
522                                         memmove(SendMsg->mailfrom, 
523                                                 &SendMsg->mailfrom[lp + 1], 
524                                                 rp - lp);
525                                 }
526         
527                                 scan_done = 1;
528                         }
529                 } while (scan_done == 0);
530                 if (IsEmptyStr(SendMsg->mailfrom)) strcpy(SendMsg->mailfrom, "someone@somewhere.org");
531                 stripallbut(SendMsg->mailfrom, '<', '>');
532                 SendMsg->envelope_from = SendMsg->mailfrom;
533         }
534
535         return 1;
536 }
537
538
539
540 void smtp_try(OneQueItem *MyQItem, 
541               MailQEntry *MyQEntry, 
542               StrBuf *MsgText, 
543               int KeepMsgText,  /* KeepMsgText allows us to use MsgText as ours. */
544               int MsgCount)
545 {
546         SmtpOutMsg * SendMsg;
547
548         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
549
550         SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
551         memset(SendMsg, 0, sizeof(SmtpOutMsg));
552         SendMsg->IO.sock      = (-1);
553         SendMsg->IO.NextState = eReadMessage;
554         SendMsg->n            = MsgCount++;
555         SendMsg->MyQEntry     = MyQEntry;
556         SendMsg->MyQItem      = MyQItem;
557         SendMsg->pCurrRelay   = MyQItem->URL;
558
559         SendMsg->IO.dport         = DefaultMXPort;
560         SendMsg->IO.Data          = SendMsg;
561         SendMsg->IO.SendDone      = SMTP_C_DispatchWriteDone;
562         SendMsg->IO.ReadDone      = SMTP_C_DispatchReadDone;
563         SendMsg->IO.Terminate     = SMTP_C_Terminate;
564         SendMsg->IO.LineReader    = SMTP_C_ReadServerStatus;
565         SendMsg->IO.ConnFail      = SMTP_C_ConnFail;
566         SendMsg->IO.Timeout       = SMTP_C_Timeout;
567         SendMsg->IO.ShutdownAbort = SMTP_C_Shutdown;
568         SendMsg->IO.SendBuf.Buf   = NewStrBufPlain(NULL, 1024);
569         SendMsg->IO.RecvBuf.Buf   = NewStrBufPlain(NULL, 1024);
570         SendMsg->IO.IOBuf         = NewStrBuf();
571                         
572
573         if (KeepMsgText) {
574                 SendMsg->msgtext    = MsgText;
575         }
576         else {
577                 SendMsg->msgtext = NewStrBufDup(MsgText);
578         }
579
580         if (smtp_resolve_recipients(SendMsg)) {
581                 if (SendMsg->pCurrRelay == NULL)
582                         QueueEventContext(&SendMsg->IO,
583                                           resolve_mx_records);
584                 else {
585                         if (SendMsg->pCurrRelay->IsIP) {
586                                 QueueEventContext(&SendMsg->IO,
587                                                   mx_connect_relay_ip);
588                         }
589                         else {
590                                 QueueEventContext(&SendMsg->IO,
591                                                   get_one_mx_host_ip);
592                         }
593                 }
594         }
595         else {
596                 if ((SendMsg==NULL) || 
597                     (SendMsg->MyQEntry == NULL)) {
598                         SendMsg->MyQEntry->Status = 5;
599                         StrBufPlain(SendMsg->MyQEntry->StatusMessage, 
600                                     HKEY("Invalid Recipient!"));
601                 }
602                 FinalizeMessageSend(SendMsg);
603         }
604 }
605
606
607
608
609
610 /*****************************************************************************/
611 /*                     SMTP CLIENT STATE CALLBACKS                           */
612 /*****************************************************************************/
613 eNextState SMTPC_read_greeting(SmtpOutMsg *SendMsg)
614 {
615         /* Process the SMTP greeting from the server */
616         SMTP_DBG_READ();
617
618         if (!SMTP_IS_STATE('2')) {
619                 if (SMTP_IS_STATE('4')) 
620                         SMTP_VERROR(4);
621                 else 
622                         SMTP_VERROR(5);
623         }
624         return eSendReply;
625 }
626
627 eNextState SMTPC_send_EHLO(SmtpOutMsg *SendMsg)
628 {
629         /* At this point we know we are talking to a real SMTP server */
630
631         /* Do a EHLO command.  If it fails, try the HELO command. */
632         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
633                      "EHLO %s\r\n", config.c_fqdn);
634
635         SMTP_DBG_SEND();
636         return eReadMessage;
637 }
638
639 eNextState SMTPC_read_EHLO_reply(SmtpOutMsg *SendMsg)
640 {
641         SMTP_DBG_READ();
642
643         if (SMTP_IS_STATE('2')) {
644                 SendMsg->State ++;
645
646                 if ((SendMsg->pCurrRelay == NULL) || 
647                     (SendMsg->pCurrRelay->User == NULL))
648                         SendMsg->State ++; /* Skip auth... */
649         }
650         /* else we fall back to 'helo' */
651         return eSendReply;
652 }
653
654 eNextState STMPC_send_HELO(SmtpOutMsg *SendMsg)
655 {
656         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
657                      "HELO %s\r\n", config.c_fqdn);
658
659         SMTP_DBG_SEND();
660         return eReadMessage;
661 }
662
663 eNextState SMTPC_read_HELO_reply(SmtpOutMsg *SendMsg)
664 {
665         SMTP_DBG_READ();
666
667         if (!SMTP_IS_STATE('2')) {
668                 if (SMTP_IS_STATE('4'))
669                         SMTP_VERROR(4);
670                 else 
671                         SMTP_VERROR(5);
672         }
673                 if ((SendMsg->pCurrRelay == NULL) || 
674                     (SendMsg->pCurrRelay->User == NULL))
675                 SendMsg->State ++; /* Skip auth... */
676         return eSendReply;
677 }
678
679 eNextState SMTPC_send_auth(SmtpOutMsg *SendMsg)
680 {
681         char buf[SIZ];
682         char encoded[1024];
683
684         if ((SendMsg->pCurrRelay == NULL) || 
685             (SendMsg->pCurrRelay->User == NULL))
686                 SendMsg->State ++; /* Skip auth, shouldn't even come here!... */
687         else {
688         /* Do an AUTH command if necessary */
689         sprintf(buf, "%s%c%s%c%s", 
690                 SendMsg->pCurrRelay->User, '\0', 
691                 SendMsg->pCurrRelay->User, '\0', 
692                 SendMsg->pCurrRelay->Pass);
693         CtdlEncodeBase64(encoded, buf, 
694                          strlen(SendMsg->pCurrRelay->User) * 2 +
695                          strlen(SendMsg->pCurrRelay->Pass) + 2, 0);
696         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
697                      "AUTH PLAIN %s\r\n", encoded);
698         }
699         SMTP_DBG_SEND();
700         return eReadMessage;
701 }
702
703 eNextState SMTPC_read_auth_reply(SmtpOutMsg *SendMsg)
704 {
705         /* Do an AUTH command if necessary */
706         
707         SMTP_DBG_READ();
708         
709         if (!SMTP_IS_STATE('2')) {
710                 if (SMTP_IS_STATE('4'))
711                         SMTP_VERROR(4);
712                 else 
713                         SMTP_VERROR(5);
714         }
715         return eSendReply;
716 }
717
718 eNextState SMTPC_send_FROM(SmtpOutMsg *SendMsg)
719 {
720         /* previous command succeeded, now try the MAIL FROM: command */
721         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
722                      "MAIL FROM:<%s>\r\n", 
723                      SendMsg->envelope_from);
724
725         SMTP_DBG_SEND();
726         return eReadMessage;
727 }
728
729 eNextState SMTPC_read_FROM_reply(SmtpOutMsg *SendMsg)
730 {
731         SMTP_DBG_READ();
732
733         if (!SMTP_IS_STATE('2')) {
734                 if (SMTP_IS_STATE('4'))
735                         SMTP_VERROR(4);
736                 else 
737                         SMTP_VERROR(5);
738         }
739         return eSendReply;
740 }
741
742
743 eNextState SMTPC_send_RCPT(SmtpOutMsg *SendMsg)
744 {
745         /* MAIL succeeded, now try the RCPT To: command */
746         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
747                      "RCPT TO:<%s@%s>\r\n", 
748                      SendMsg->user, 
749                      SendMsg->node);
750
751         SMTP_DBG_SEND();
752         return eReadMessage;
753 }
754
755 eNextState SMTPC_read_RCPT_reply(SmtpOutMsg *SendMsg)
756 {
757         SMTP_DBG_READ();
758
759         if (!SMTP_IS_STATE('2')) {
760                 if (SMTP_IS_STATE('4')) 
761                         SMTP_VERROR(4);
762                 else 
763                         SMTP_VERROR(5);
764         }
765         return eSendReply;
766 }
767
768 eNextState SMTPC_send_DATAcmd(SmtpOutMsg *SendMsg)
769 {
770         /* RCPT succeeded, now try the DATA command */
771         StrBufPlain(SendMsg->IO.SendBuf.Buf,
772                     HKEY("DATA\r\n"));
773
774         SMTP_DBG_SEND();
775         return eReadMessage;
776 }
777
778 eNextState SMTPC_read_DATAcmd_reply(SmtpOutMsg *SendMsg)
779 {
780         SMTP_DBG_READ();
781
782         if (!SMTP_IS_STATE('3')) {
783                 if (SMTP_IS_STATE('4')) 
784                         SMTP_VERROR(3);
785                 else 
786                         SMTP_VERROR(5);
787         }
788         return eSendReply;
789 }
790
791 eNextState SMTPC_send_data_body(SmtpOutMsg *SendMsg)
792 {
793         StrBuf *Buf;
794         /* If we reach this point, the server is expecting data.*/
795
796         Buf = SendMsg->IO.SendBuf.Buf;
797         SendMsg->IO.SendBuf.Buf = SendMsg->msgtext;
798         SendMsg->msgtext = Buf;
799         SendMsg->State ++;
800
801         return eSendMore;
802 }
803
804 eNextState SMTPC_send_terminate_data_body(SmtpOutMsg *SendMsg)
805 {
806         StrBuf *Buf;
807
808         Buf = SendMsg->IO.SendBuf.Buf;
809         SendMsg->IO.SendBuf.Buf = SendMsg->msgtext;
810         SendMsg->msgtext = Buf;
811
812         StrBufPlain(SendMsg->IO.SendBuf.Buf,
813                     HKEY(".\r\n"));
814
815         return eReadMessage;
816
817 }
818
819 eNextState SMTPC_read_data_body_reply(SmtpOutMsg *SendMsg)
820 {
821         SMTP_DBG_READ();
822
823         if (!SMTP_IS_STATE('2')) {
824                 if (SMTP_IS_STATE('4'))
825                         SMTP_VERROR(4);
826                 else 
827                         SMTP_VERROR(5);
828         }
829
830         /* We did it! */
831         StrBufPlain(SendMsg->MyQEntry->StatusMessage, 
832                     &ChrPtr(SendMsg->IO.RecvBuf.Buf)[4],
833                     StrLength(SendMsg->IO.RecvBuf.Buf) - 4);
834         SendMsg->MyQEntry->Status = 2;
835         return eSendReply;
836 }
837
838 eNextState SMTPC_send_QUIT(SmtpOutMsg *SendMsg)
839 {
840         StrBufPlain(SendMsg->IO.SendBuf.Buf,
841                     HKEY("QUIT\r\n"));
842
843         SMTP_DBG_SEND();
844         return eReadMessage;
845 }
846
847 eNextState SMTPC_read_QUIT_reply(SmtpOutMsg *SendMsg)
848 {
849         SMTP_DBG_READ();
850
851         CtdlLogPrintf(CTDL_INFO, "SMTP client[%ld]: delivery to <%s> @ <%s> (%s) succeeded\n",
852                       SendMsg->n, SendMsg->user, SendMsg->node, SendMsg->name);
853         return eTerminateConnection;
854 }
855
856 eNextState SMTPC_read_dummy(SmtpOutMsg *SendMsg)
857 {
858         return eSendReply;
859 }
860
861 eNextState SMTPC_send_dummy(SmtpOutMsg *SendMsg)
862 {
863         return eReadMessage;
864 }
865
866
867 /*****************************************************************************/
868 /*                     SMTP CLIENT DISPATCHER                                */
869 /*****************************************************************************/
870 SMTPReadHandler ReadHandlers[eMaxSMTPC] = {
871         SMTPC_read_greeting,
872         SMTPC_read_EHLO_reply,
873         SMTPC_read_HELO_reply,
874         SMTPC_read_auth_reply,
875         SMTPC_read_FROM_reply,
876         SMTPC_read_RCPT_reply,
877         SMTPC_read_DATAcmd_reply,
878         SMTPC_read_dummy,
879         SMTPC_read_data_body_reply,
880         SMTPC_read_QUIT_reply
881 };
882 SMTPSendHandler SendHandlers[eMaxSMTPC] = {
883         SMTPC_send_dummy, /* we don't send a greeting, the server does... */
884         SMTPC_send_EHLO,
885         STMPC_send_HELO,
886         SMTPC_send_auth,
887         SMTPC_send_FROM,
888         SMTPC_send_RCPT,
889         SMTPC_send_DATAcmd,
890         SMTPC_send_data_body,
891         SMTPC_send_terminate_data_body,
892         SMTPC_send_QUIT
893 };
894
895 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
896 {
897         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
898         double Timeout;
899         switch (NextTCPState) {
900         case eSendReply:
901         case eSendMore:
902                 Timeout = SMTP_C_SendTimeouts[pMsg->State];
903                 if (pMsg->State == eDATABody) {
904                         /* if we're sending a huge message, we need more time. */
905                         Timeout += StrLength(pMsg->msgtext) / 1024;
906                 }
907                 break;
908         case eReadMessage:
909                 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
910                 if (pMsg->State == eDATATerminateBody) {
911                         /* 
912                          * some mailservers take a nap before accepting the message
913                          * content inspection and such.
914                          */
915                         Timeout += StrLength(pMsg->msgtext) / 1024;
916                 }
917                 break;
918         case eTerminateConnection:
919         case eAbort:
920                 return;
921         }
922         SetNextTimeout(&pMsg->IO, Timeout);
923 }
924 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
925 {
926         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
927         SmtpOutMsg *pMsg = IO->Data;
928         eNextState rc;
929
930         rc = ReadHandlers[pMsg->State](pMsg);
931         pMsg->State++;
932         SMTPSetTimeout(rc, pMsg);
933         return rc;
934 }
935 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
936 {
937         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
938         SmtpOutMsg *pMsg = IO->Data;
939         eNextState rc;
940
941         rc = SendHandlers[pMsg->State](pMsg);
942         SMTPSetTimeout(rc, pMsg);
943         return rc;
944 }
945
946
947 /*****************************************************************************/
948 /*                     SMTP CLIENT ERROR CATCHERS                            */
949 /*****************************************************************************/
950 eNextState SMTP_C_Terminate(AsyncIO *IO)
951 {
952         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
953         SmtpOutMsg *pMsg = IO->Data;
954         FinalizeMessageSend(pMsg);
955         return eAbort;
956 }
957 eNextState SMTP_C_Timeout(AsyncIO *IO)
958 {
959         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
960         SmtpOutMsg *pMsg = IO->Data;
961         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
962         FinalizeMessageSend(pMsg);
963         return eAbort;
964 }
965 eNextState SMTP_C_ConnFail(AsyncIO *IO)
966 {
967         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
968         SmtpOutMsg *pMsg = IO->Data;
969         FinalizeMessageSend(pMsg);
970         return eAbort;
971 }
972 eNextState SMTP_C_Shutdown(AsyncIO *IO)
973 {
974         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
975         SmtpOutMsg *pMsg = IO->Data;
976
977         pMsg->MyQEntry->Status = 3;
978         StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
979         FinalizeMessageSend(pMsg);
980         return eAbort;
981 }
982
983
984 /**
985  * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
986  */
987 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
988 {
989         eReadState Finished = eBufferNotEmpty; 
990
991         while (Finished == eBufferNotEmpty) {
992                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
993                 
994                 switch (Finished) {
995                 case eMustReadMore: /// read new from socket... 
996                         return Finished;
997                         break;
998                 case eBufferNotEmpty: /* shouldn't happen... */
999                 case eReadSuccess: /// done for now...
1000                         if (StrLength(IO->IOBuf) < 4)
1001                                 continue;
1002                         if (ChrPtr(IO->IOBuf)[3] == '-')
1003                                 Finished = eBufferNotEmpty;
1004                         else 
1005                                 return Finished;
1006                         break;
1007                 case eReadFail: /// WHUT?
1008                         ///todo: shut down! 
1009                         break;
1010                 }
1011         }
1012         return Finished;
1013 }
1014
1015 #endif
1016 CTDL_MODULE_INIT(smtp_eventclient)
1017 {
1018         return "smtpeventclient";
1019 }