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