Logging: add timestamps for eventdriven IO
[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-2012 by the citadel.org team
24  *
25  *  This program is open source software; you can redistribute it and/or modify
26  *  it under the terms of the GNU General Public License version 3.
27  *  
28  *  
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  *  
36  *  
37  *  
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 #include "smtp_clienthandlers.h"
92
93 const unsigned short DefaultMXPort = 25;
94 void DeleteSmtpOutMsg(void *v)
95 {
96         SmtpOutMsg *Msg = v;
97         AsyncIO *IO = &Msg->IO;
98         EV_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
99
100         /* these are kept in our own space and free'd below */
101         Msg->IO.ConnectMe = NULL;
102
103         ares_free_data(Msg->AllMX);
104         if (Msg->HostLookup.VParsedDNSReply != NULL)
105                 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
106         FreeURL(&Msg->Relay);
107         FreeStrBuf(&Msg->msgtext);
108         FreeAsyncIOContents(&Msg->IO);
109         memset (Msg, 0, sizeof(SmtpOutMsg)); /* just to be shure... */
110         free(Msg);
111 }
112
113 eNextState SMTP_C_Shutdown(AsyncIO *IO);
114 eNextState SMTP_C_Timeout(AsyncIO *IO);
115 eNextState SMTP_C_ConnFail(AsyncIO *IO);
116 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
117 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
118 eNextState SMTP_C_DNSFail(AsyncIO *IO);
119 eNextState SMTP_C_Terminate(AsyncIO *IO);
120 eNextState SMTP_C_TerminateDB(AsyncIO *IO);
121 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
122
123 eNextState mx_connect_ip(AsyncIO *IO);
124 eNextState get_one_mx_host_ip(AsyncIO *IO);
125 eNextState FinalizeMessageSendDB(AsyncIO *IO);
126 eNextState FinalizeMessageSend_DB1(AsyncIO *IO);
127 eNextState FinalizeMessageSend_DB2(AsyncIO *IO);
128 eNextState FinalizeMessageSend_DB3(AsyncIO *IO);
129 eNextState FinalizeMessageSend_DB4(AsyncIO *IO);
130
131 /******************************************************************************
132  * So, we're finished with sending (regardless of success or failure)         *
133  * This Message might be referenced by several Queue-Items, if we're the last,*
134  * we need to free the memory and send bounce messages (on terminal failure)  *
135  * else we just free our SMTP-Message struct.                                 *
136  ******************************************************************************/
137 inline void FinalizeMessageSend_1(AsyncIO *IO)
138 {
139         const char *Status;
140         SmtpOutMsg *Msg = IO->Data;
141         
142         if (Msg->MyQEntry->Status == 2) 
143                 Status = "Delivery Successfull.";
144         else if (Msg->MyQEntry->Status == 5) 
145                 Status = "Delivery failed permanently; giving up.";
146         else
147                 Status = "Delivery failed temporarily; will retry later.";
148                         
149         EVS_syslog(LOG_INFO,
150                    "SMTP: %s Time[%fs] Recipient <%s> @ <%s> (%s) Statusmessage: %s\n",
151                    Status,
152                    Msg->IO.Now - Msg->IO.StartIO,
153                    Msg->user,
154                    Msg->node,
155                    Msg->name,
156                    ChrPtr(Msg->MyQEntry->StatusMessage));
157
158
159         Msg->IDestructQueItem = DecreaseQReference(Msg->MyQItem);
160
161         Msg->nRemain = CountActiveQueueEntries(Msg->MyQItem);
162
163         if (Msg->MyQEntry->Active && 
164             CheckQEntryIsBounce(Msg->MyQEntry))
165         {
166                 /* are we casue for a bounce mail? */
167                 Msg->MyQItem->SendBounceMail |= (1<<Msg->MyQEntry->Status);
168         }
169
170         if ((Msg->nRemain > 0) || Msg->IDestructQueItem)
171                 Msg->QMsgData = SerializeQueueItem(Msg->MyQItem);
172         else
173                 Msg->QMsgData = NULL;
174 }
175 eNextState FinalizeMessageSend(SmtpOutMsg *Msg)
176 {
177         return QueueDBOperation(&Msg->IO, FinalizeMessageSend_DB1);
178 }
179
180 inline void FinalizeMessageSend_DB_1(AsyncIO *IO)
181 {
182         SmtpOutMsg *Msg = IO->Data;
183
184         /*
185          * Uncompleted delivery instructions remain, so delete the old
186          * instructions and replace with the updated ones.
187          */
188         EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
189         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
190 }
191 eNextState FinalizeMessageSend_DB1(AsyncIO *IO)
192 {
193         FinalizeMessageSend_1(IO);
194         FinalizeMessageSend_DB_1(IO);
195         return NextDBOperation(IO, FinalizeMessageSend_DB2);
196 }
197
198
199 inline void FinalizeMessageSend_DB_2(AsyncIO *IO)
200 {
201         SmtpOutMsg *Msg = IO->Data;
202
203         if (Msg->IDestructQueItem)
204                 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
205 }
206 eNextState FinalizeMessageSend_DB2(AsyncIO *IO)
207 {
208         FinalizeMessageSend_DB_2(IO);
209
210         return NextDBOperation(IO, FinalizeMessageSend_DB3);
211 }
212
213
214 inline void FinalizeMessageSend_DB_3(AsyncIO *IO)
215 {
216         SmtpOutMsg *Msg = IO->Data;
217
218         if (Msg->nRemain > 0)
219         {
220                 struct CtdlMessage *msg;
221                 msg = malloc(sizeof(struct CtdlMessage));
222                 memset(msg, 0, sizeof(struct CtdlMessage));
223                 msg->cm_magic = CTDLMESSAGE_MAGIC;
224                 msg->cm_anon_type = MES_NORMAL;
225                 msg->cm_format_type = FMT_RFC822;
226                 msg->cm_fields['M'] = SmashStrBuf(&Msg->QMsgData);
227                 msg->cm_fields['U'] = strdup("QMSG");
228                 Msg->MyQItem->QueMsgID =
229                         CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
230                 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
231                 CtdlFreeMessage(msg);
232         }
233         else {
234                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
235                                    &Msg->MyQItem->MessageID,
236                                    1,
237                                    "");
238                 FreeStrBuf(&Msg->QMsgData);
239         }
240         DecreaseShutdownDeliveries(Msg->MyQItem);
241 }
242 eNextState FinalizeMessageSend_DB3(AsyncIO *IO)
243 {
244         SmtpOutMsg *Msg = IO->Data;
245         FinalizeMessageSend_DB_3(IO);
246         if (!Msg->IDestructQueItem)
247                 return eAbort;
248         return NextDBOperation(IO, FinalizeMessageSend_DB4);
249 }
250
251 eNextState FinalizeMessageSend_DB4(AsyncIO *IO)
252 {
253         int Done;
254         SmtpOutMsg *Msg = IO->Data;
255
256         Done = GetShutdownDeliveries(Msg->MyQItem);
257         if (!Done) 
258                 return NextDBOperation(IO, FinalizeMessageSend_DB4);
259         else
260                 return eAbort;
261 }
262
263 eNextState FinalizeMessageSend_DB(AsyncIO *IO)
264 {
265         SmtpOutMsg *Msg = IO->Data;
266
267         RemoveContext(Msg->IO.CitContext);
268         if (Msg->IDestructQueItem)
269                 RemoveQItem(Msg->MyQItem);
270         DeleteSmtpOutMsg(Msg);
271         return eAbort;
272 }
273
274 eNextState FailOneAttempt(AsyncIO *IO)
275 {
276         SmtpOutMsg *Msg = IO->Data;
277
278         if (Msg->MyQEntry->Status == 2)
279                 return eAbort;
280
281         /*
282          * possible ways here:
283          * - connection timeout
284          * - dns lookup failed
285          */
286         StopClientWatchers(IO);
287
288         if (Msg->pCurrRelay != NULL)
289                 Msg->pCurrRelay = Msg->pCurrRelay->Next;
290
291         if (Msg->pCurrRelay == NULL) {
292                 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
293                 return eAbort;
294         }
295         if (Msg->pCurrRelay->IsIP) {
296                 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
297                 return mx_connect_ip(IO);
298         }
299         else {
300                 EVS_syslog(LOG_DEBUG,
301                            "SMTP: %s resolving next MX Record\n",
302                            __FUNCTION__);
303                 return get_one_mx_host_ip(IO);
304         }
305 }
306
307
308 void SetConnectStatus(AsyncIO *IO)
309 {
310         SmtpOutMsg *Msg = IO->Data;
311         char buf[256];
312         void *src;
313
314         buf[0] = '\0';
315
316         if (IO->ConnectMe->IPv6) {
317                 src = &IO->ConnectMe->Addr.sin6_addr;
318         }
319         else {
320                 struct sockaddr_in *addr;
321
322                 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
323                 src = &addr->sin_addr.s_addr;
324         }
325
326         inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
327                   src,
328                   buf,
329                   sizeof(buf));
330
331         if (Msg->mx_host == NULL)
332                 Msg->mx_host = "<no MX-Record>";
333
334         EVS_syslog(LOG_DEBUG,
335                   "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
336                   Msg->n,
337                   Msg->mx_host,
338                   buf,
339                   Msg->IO.ConnectMe->Port);
340
341         Msg->MyQEntry->Status = 5;
342         StrBufPrintf(Msg->MyQEntry->StatusMessage,
343                      "Timeout while connecting %s [%s]:%d ",
344                      Msg->mx_host,
345                      buf,
346                      Msg->IO.ConnectMe->Port);
347         Msg->IO.NextState = eConnect;
348 }
349
350 /*****************************************************************************
351  * So we connect our Relay IP here.                                          *
352  *****************************************************************************/
353 eNextState mx_connect_ip(AsyncIO *IO)
354 {
355         SmtpOutMsg *Msg = IO->Data;
356
357         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
358
359         IO->ConnectMe = Msg->pCurrRelay;
360         Msg->State = eConnectMX;
361
362         SetConnectStatus(IO);
363
364         return EvConnectSock(IO,
365                              SMTP_C_ConnTimeout,
366                              SMTP_C_ReadTimeouts[0],
367                              1);
368 }
369
370 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
371 {
372         SmtpOutMsg *Msg = IO->Data;
373         struct hostent *hostent;
374
375         QueryCbDone(IO);
376         EVS_syslog(LOG_DEBUG, "SMTP: %s Time[%fs]\n",
377                    __FUNCTION__,
378                    IO->Now - IO->DNS.Start);
379
380         hostent = Msg->HostLookup.VParsedDNSReply;
381         if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
382             (hostent != NULL) ) {
383                 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
384                 if (Msg->pCurrRelay->IPv6) {
385                         memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
386                                &hostent->h_addr_list[0],
387                                sizeof(struct in6_addr));
388
389                         Msg->pCurrRelay->Addr.sin6_family =
390                                 hostent->h_addrtype;
391                         Msg->pCurrRelay->Addr.sin6_port =
392                                 htons(DefaultMXPort);
393                 }
394                 else {
395                         struct sockaddr_in *addr;
396                         /*
397                          * Bypass the ns lookup result like this:
398                          * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
399                          * addr->sin_addr.s_addr =
400                          *   htonl((uint32_t)&hostent->h_addr_list[0]);
401                          */
402
403                         addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
404
405                         memcpy(&addr->sin_addr.s_addr,
406                                hostent->h_addr_list[0],
407                                sizeof(uint32_t));
408
409                         addr->sin_family = hostent->h_addrtype;
410                         addr->sin_port   = htons(DefaultMXPort);
411                 }
412                 Msg->mx_host = Msg->pCurrRelay->Host;
413                 if (Msg->HostLookup.VParsedDNSReply != NULL) {
414                         Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
415                         Msg->HostLookup.VParsedDNSReply = NULL;
416                 }
417                 return mx_connect_ip(IO);
418         }
419         else {
420                 if (Msg->HostLookup.VParsedDNSReply != NULL) {
421                         Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
422                         Msg->HostLookup.VParsedDNSReply = NULL;
423                 }
424                 return FailOneAttempt(IO);
425         }
426 }
427
428 eNextState get_one_mx_host_ip(AsyncIO *IO)
429 {
430         SmtpOutMsg * Msg = IO->Data;
431         /*
432          * here we start with the lookup of one host. it might be...
433          * - the relay host *sigh*
434          * - the direct hostname if there was no mx record
435          * - one of the mx'es
436          */
437
438         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
439
440         EVS_syslog(LOG_DEBUG,
441                   "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
442                   Msg->n,
443                   (Msg->pCurrRelay->IPv6)? "aaaa": "a",
444                   Msg->pCurrRelay->Host,
445                   Msg->pCurrRelay->Port);
446
447         if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
448                         Msg->pCurrRelay->Host,
449                         &Msg->IO,
450                         &Msg->HostLookup,
451                         get_one_mx_host_ip_done))
452         {
453                 Msg->MyQEntry->Status = 5;
454                 StrBufPrintf(Msg->MyQEntry->StatusMessage,
455                              "No MX hosts found for <%s>", Msg->node);
456                 Msg->IO.NextState = eTerminateConnection;
457                 return IO->NextState;
458         }
459         IO->NextState = eReadDNSReply;
460         return IO->NextState;
461 }
462
463
464 /*****************************************************************************
465  * here we try to find out about the MX records for our recipients.          *
466  *****************************************************************************/
467 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
468 {
469         SmtpOutMsg * Msg = IO->Data;
470         ParsedURL **pp;
471
472         QueryCbDone(IO);
473
474         EVS_syslog(LOG_DEBUG, "SMTP: %s Time[%fs]\n",
475                    __FUNCTION__,
476                 IO->Now - IO->DNS.Start);
477
478         pp = &Msg->Relay;
479         while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
480                 pp = &(*pp)->Next;
481
482         if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
483             (IO->DNS.Query->VParsedDNSReply != NULL))
484         { /* ok, we found mx records. */
485
486                 Msg->CurrMX
487                         = Msg->AllMX
488                         = IO->DNS.Query->VParsedDNSReply;
489                 while (Msg->CurrMX) {
490                         int i;
491                         for (i = 0; i < 2; i++) {
492                                 ParsedURL *p;
493
494                                 p = (ParsedURL*) malloc(sizeof(ParsedURL));
495                                 memset(p, 0, sizeof(ParsedURL));
496                                 p->Priority = Msg->CurrMX->priority;
497                                 p->IsIP = 0;
498                                 p->Port = DefaultMXPort;
499                                 p->IPv6 = i == 1;
500                                 p->Host = Msg->CurrMX->host;
501                                 if (*pp == NULL)
502                                         *pp = p;
503                                 else {
504                                         ParsedURL *ppp = *pp;
505
506                                         while ((ppp->Next != NULL) &&
507                                                (ppp->Next->Priority <= p->Priority))
508                                                ppp = ppp->Next;
509                                         if ((ppp == *pp) &&
510                                             (ppp->Priority > p->Priority)) {
511                                                 p->Next = *pp;
512                                                 *pp = p;
513                                         }
514                                         else {
515                                                 p->Next = ppp->Next;
516                                                 ppp->Next = p;
517                                         }
518                                 }
519                         }
520                         Msg->CurrMX    = Msg->CurrMX->next;
521                 }
522                 Msg->CXFlags   = Msg->CXFlags & F_HAVE_MX;
523         }
524         else { /* else fall back to the plain hostname */
525                 int i;
526                 for (i = 0; i < 2; i++) {
527                         ParsedURL *p;
528
529                         p = (ParsedURL*) malloc(sizeof(ParsedURL));
530                         memset(p, 0, sizeof(ParsedURL));
531                         p->IsIP = 0;
532                         p->Port = DefaultMXPort;
533                         p->IPv6 = i == 1;
534                         p->Host = Msg->node;
535
536                         *pp = p;
537                         pp = &p->Next;
538                 }
539                 Msg->CXFlags   = Msg->CXFlags & F_DIRECT;
540         }
541         if (Msg->MyQItem->FallBackHost != NULL)
542         {
543                 Msg->MyQItem->FallBackHost->Next = *pp;
544                 *pp = Msg->MyQItem->FallBackHost;
545         }
546         Msg->pCurrRelay = Msg->Relay;
547         return get_one_mx_host_ip(IO);
548 }
549
550 eNextState resolve_mx_records(AsyncIO *IO)
551 {
552         SmtpOutMsg * Msg = IO->Data;
553
554         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
555         /* start resolving MX records here. */
556         if (!QueueQuery(ns_t_mx,
557                         Msg->node,
558                         &Msg->IO,
559                         &Msg->MxLookup,
560                         smtp_resolve_mx_record_done))
561         {
562                 Msg->MyQEntry->Status = 5;
563                 StrBufPrintf(Msg->MyQEntry->StatusMessage,
564                              "No MX hosts found for <%s>", Msg->node);
565                 return IO->NextState;
566         }
567         Msg->IO.NextState = eReadDNSReply;
568         return IO->NextState;
569 }
570
571
572
573 /******************************************************************************
574  *  so, we're going to start a SMTP delivery.  lets get it on.                *
575  ******************************************************************************/
576
577 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
578                             MailQEntry *MyQEntry,
579                             int MsgCount)
580 {
581         SmtpOutMsg * Msg;
582
583         Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
584         memset(Msg, 0, sizeof(SmtpOutMsg));
585
586         Msg->n                = MsgCount;
587         Msg->MyQEntry         = MyQEntry;
588         Msg->MyQItem          = MyQItem;
589         Msg->pCurrRelay       = MyQItem->URL;
590
591         InitIOStruct(&Msg->IO,
592                      Msg,
593                      eReadMessage,
594                      SMTP_C_ReadServerStatus,
595                      SMTP_C_DNSFail,
596                      SMTP_C_DispatchWriteDone,
597                      SMTP_C_DispatchReadDone,
598                      SMTP_C_Terminate,
599                      SMTP_C_TerminateDB,
600                      SMTP_C_ConnFail,
601                      SMTP_C_Timeout,
602                      SMTP_C_Shutdown);
603
604         Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
605
606         return Msg;
607 }
608
609 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
610                               MailQEntry *MyQEntry,
611                               StrBuf *MsgText,
612                         /*KeepMsgText allows us to use MsgText as ours.*/
613                               int KeepMsgText,
614                               int MsgCount)
615 {
616         SmtpOutMsg *Msg;
617
618         syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
619
620         Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
621         if (KeepMsgText) Msg->msgtext = MsgText;
622         else             Msg->msgtext = NewStrBufDup(MsgText);
623
624         if (smtp_resolve_recipients(Msg)) {
625
626                 safestrncpy(
627                         ((CitContext *)Msg->IO.CitContext)->cs_host,
628                         Msg->node,
629                         sizeof(((CitContext *)
630                                 Msg->IO.CitContext)->cs_host));
631
632                 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
633                        Msg->MyQItem->MessageID,
634                        ChrPtr(Msg->MyQEntry->Recipient),
635                        ((CitContext*)Msg->IO.CitContext)->cs_pid);
636                 if (Msg->pCurrRelay == NULL)
637                         QueueEventContext(&Msg->IO,
638                                           resolve_mx_records);
639                 else { /* oh... via relay host */
640                         if (Msg->pCurrRelay->IsIP) {
641                                 QueueEventContext(&Msg->IO,
642                                                   mx_connect_ip);
643                         }
644                         else {
645                                 /* uneducated admin has chosen to
646                                    add DNS to the equation... */
647                                 QueueEventContext(&Msg->IO,
648                                                   get_one_mx_host_ip);
649                         }
650                 }
651         }
652         else {
653                 /* No recipients? well fail then. */
654                 if ((Msg==NULL) ||
655                     (Msg->MyQEntry == NULL)) {
656                         Msg->MyQEntry->Status = 5;
657                         StrBufPlain(Msg->MyQEntry->StatusMessage,
658                                     HKEY("Invalid Recipient!"));
659                 }
660                 FinalizeMessageSend_1(&Msg->IO);
661                 FinalizeMessageSend_DB_1(&Msg->IO);
662                 FinalizeMessageSend_DB_2(&Msg->IO);
663                 FinalizeMessageSend_DB_3(&Msg->IO);
664                 FinalizeMessageSend_DB(&Msg->IO);
665         }
666 }
667
668
669
670
671
672
673 /*****************************************************************************/
674 /*                     SMTP CLIENT DISPATCHER                                */
675 /*****************************************************************************/
676
677 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
678 {
679         double Timeout = 0.0;
680         AsyncIO *IO = &Msg->IO;
681
682         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
683
684         switch (NextTCPState) {
685         case eSendFile:
686         case eSendReply:
687         case eSendMore:
688                 Timeout = SMTP_C_SendTimeouts[Msg->State];
689                 if (Msg->State == eDATABody) {
690                         /* if we're sending a huge message,
691                          * we need more time.
692                          */
693                         Timeout += StrLength(Msg->msgtext) / 512;
694                 }
695                 break;
696         case eReadMessage:
697                 Timeout = SMTP_C_ReadTimeouts[Msg->State];
698                 if (Msg->State == eDATATerminateBody) {
699                         /*
700                          * some mailservers take a nap before accepting
701                          * the message content inspection and such.
702                          */
703                         Timeout += StrLength(Msg->msgtext) / 512;
704                 }
705                 break;
706         case eSendDNSQuery:
707         case eReadDNSReply:
708         case eDBQuery:
709         case eReadFile:
710         case eReadMore:
711         case eReadPayload:
712         case eConnect:
713         case eTerminateConnection:
714         case eAbort:
715                 return;
716         }
717         SetNextTimeout(&Msg->IO, Timeout);
718 }
719 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
720 {
721         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
722         SmtpOutMsg *Msg = IO->Data;
723         eNextState rc;
724
725         rc = ReadHandlers[Msg->State](Msg);
726         if (rc != eAbort)
727         {
728                 Msg->State++;
729                 SMTPSetTimeout(rc, Msg);
730         }
731         return rc;
732 }
733 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
734 {
735         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
736         SmtpOutMsg *Msg = IO->Data;
737         eNextState rc;
738
739         rc = SendHandlers[Msg->State](Msg);
740         SMTPSetTimeout(rc, Msg);
741         return rc;
742 }
743
744
745 /*****************************************************************************/
746 /*                     SMTP CLIENT ERROR CATCHERS                            */
747 /*****************************************************************************/
748 eNextState SMTP_C_Terminate(AsyncIO *IO)
749 {
750         SmtpOutMsg *Msg = IO->Data;
751
752         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
753         return FinalizeMessageSend(Msg);
754 }
755 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
756 {
757         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
758         return FinalizeMessageSend_DB(IO);
759 }
760 eNextState SMTP_C_Timeout(AsyncIO *IO)
761 {
762         SmtpOutMsg *Msg = IO->Data;
763
764         Msg->MyQEntry->Status = 4;
765         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
766         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
767         if (Msg->State > eRCPT)
768                 return eAbort;
769         else
770                 return FailOneAttempt(IO);
771 }
772 eNextState SMTP_C_ConnFail(AsyncIO *IO)
773 {
774         SmtpOutMsg *Msg = IO->Data;
775
776         Msg->MyQEntry->Status = 4;
777         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
778         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
779         return FailOneAttempt(IO);
780 }
781 eNextState SMTP_C_DNSFail(AsyncIO *IO)
782 {
783         SmtpOutMsg *Msg = IO->Data;
784         Msg->MyQEntry->Status = 4;
785         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
786         return FailOneAttempt(IO);
787 }
788 eNextState SMTP_C_Shutdown(AsyncIO *IO)
789 {
790         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
791         SmtpOutMsg *Msg = IO->Data;
792
793         Msg->MyQEntry->Status = 3;
794         StrBufPlain(Msg->MyQEntry->StatusMessage,
795                     HKEY("server shutdown during message submit."));
796         return FinalizeMessageSend(Msg);
797 }
798
799
800 /**
801  * @brief lineread Handler;
802  * understands when to read more SMTP lines, and when this is a one-lined reply.
803  */
804 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
805 {
806         eReadState Finished = eBufferNotEmpty;
807
808         while (Finished == eBufferNotEmpty) {
809                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
810
811                 switch (Finished) {
812                 case eMustReadMore: /// read new from socket...
813                         return Finished;
814                         break;
815                 case eBufferNotEmpty: /* shouldn't happen... */
816                 case eReadSuccess: /// done for now...
817                         if (StrLength(IO->IOBuf) < 4)
818                                 continue;
819                         if (ChrPtr(IO->IOBuf)[3] == '-')
820                                 Finished = eBufferNotEmpty;
821                         else
822                                 return Finished;
823                         break;
824                 case eReadFail: /// WHUT?
825                         ///todo: shut down!
826                         break;
827                 }
828         }
829         return Finished;
830 }
831
832 CTDL_MODULE_INIT(smtp_eventclient)
833 {
834         return "smtpeventclient";
835 }