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