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