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