f08efde76e61ce1419281bf33267167ccaddf67c
[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         if (Msg == NULL)
534                 return NULL;
535         memset(Msg, 0, sizeof(SmtpOutMsg));
536
537         Msg->n                = MsgCount;
538         Msg->MyQEntry         = MyQEntry;
539         Msg->MyQItem          = MyQItem;
540         Msg->pCurrRelay       = MyQItem->URL;
541
542         InitIOStruct(&Msg->IO,
543                      Msg,
544                      eReadMessage,
545                      SMTP_C_ReadServerStatus,
546                      SMTP_C_DNSFail,
547                      SMTP_C_DispatchWriteDone,
548                      SMTP_C_DispatchReadDone,
549                      SMTP_C_Terminate,
550                      SMTP_C_TerminateDB,
551                      SMTP_C_ConnFail,
552                      SMTP_C_Timeout,
553                      SMTP_C_Shutdown);
554
555         Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
556
557         return Msg;
558 }
559
560 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
561                               MailQEntry *MyQEntry,
562                               StrBuf *MsgText,
563                         /*KeepMsgText allows us to use MsgText as ours.*/
564                               int KeepMsgText,
565                               int MsgCount)
566 {
567         SmtpOutMsg *Msg;
568
569         SMTPC_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
570
571         Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
572         if (Msg == NULL) {
573                 SMTPC_syslog(LOG_DEBUG, "%s Failed to alocate message context.\n", __FUNCTION__);
574                 if (KeepMsgText) 
575                         FreeStrBuf (&MsgText);
576                 return;
577         }
578         if (KeepMsgText) Msg->msgtext = MsgText;
579         else             Msg->msgtext = NewStrBufDup(MsgText);
580
581         if (smtp_resolve_recipients(Msg)) {
582
583                 safestrncpy(
584                         ((CitContext *)Msg->IO.CitContext)->cs_host,
585                         Msg->node,
586                         sizeof(((CitContext *)
587                                 Msg->IO.CitContext)->cs_host));
588
589                 SMTPC_syslog(LOG_DEBUG, "Starting: [%ld] <%s> CC <%d> \n",
590                              Msg->MyQItem->MessageID,
591                              ChrPtr(Msg->MyQEntry->Recipient),
592                              ((CitContext*)Msg->IO.CitContext)->cs_pid);
593                 if (Msg->pCurrRelay == NULL)
594                         QueueEventContext(&Msg->IO,
595                                           resolve_mx_records);
596                 else { /* oh... via relay host */
597                         if (Msg->pCurrRelay->IsIP) {
598                                 QueueEventContext(&Msg->IO,
599                                                   mx_connect_ip);
600                         }
601                         else {
602                                 /* uneducated admin has chosen to
603                                    add DNS to the equation... */
604                                 QueueEventContext(&Msg->IO,
605                                                   get_one_mx_host_ip);
606                         }
607                 }
608         }
609         else {
610                 /* No recipients? well fail then. */
611                 if (Msg->MyQEntry == NULL) {
612                         Msg->MyQEntry->Status = 5;
613                         StrBufPlain(Msg->MyQEntry->StatusMessage,
614                                     HKEY("Invalid Recipient!"));
615                 }
616                 FinalizeMessageSend_DB(&Msg->IO);
617                 DeleteSmtpOutMsg(&Msg->IO);
618         }
619 }
620
621
622
623
624
625
626 /*****************************************************************************/
627 /*                     SMTP CLIENT DISPATCHER                                */
628 /*****************************************************************************/
629
630 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
631 {
632         double Timeout = 0.0;
633         AsyncIO *IO = &Msg->IO;
634
635         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
636
637         switch (NextTCPState) {
638         case eSendFile:
639         case eSendReply:
640         case eSendMore:
641                 Timeout = SMTP_C_SendTimeouts[Msg->State];
642                 if (Msg->State == eDATABody) {
643                         /* if we're sending a huge message,
644                          * we need more time.
645                          */
646                         Timeout += StrLength(Msg->msgtext) / 512;
647                 }
648                 break;
649         case eReadMessage:
650                 Timeout = SMTP_C_ReadTimeouts[Msg->State];
651                 if (Msg->State == eDATATerminateBody) {
652                         /*
653                          * some mailservers take a nap before accepting
654                          * the message content inspection and such.
655                          */
656                         Timeout += StrLength(Msg->msgtext) / 512;
657                 }
658                 break;
659         case eSendDNSQuery:
660         case eReadDNSReply:
661         case eDBQuery:
662         case eReadFile:
663         case eReadMore:
664         case eReadPayload:
665         case eConnect:
666         case eTerminateConnection:
667         case eAbort:
668                 return;
669         }
670         SetNextTimeout(&Msg->IO, Timeout);
671 }
672 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
673 {
674         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
675         SmtpOutMsg *Msg = IO->Data;
676         eNextState rc;
677
678         rc = ReadHandlers[Msg->State](Msg);
679         if (rc != eAbort)
680         {
681                 Msg->State++;
682                 SMTPSetTimeout(rc, Msg);
683         }
684         return rc;
685 }
686 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
687 {
688         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
689         SmtpOutMsg *Msg = IO->Data;
690         eNextState rc;
691
692         rc = SendHandlers[Msg->State](Msg);
693         SMTPSetTimeout(rc, Msg);
694         return rc;
695 }
696
697
698 /*****************************************************************************/
699 /*                     SMTP CLIENT ERROR CATCHERS                            */
700 /*****************************************************************************/
701 eNextState SMTP_C_Terminate(AsyncIO *IO)
702 {
703         SmtpOutMsg *Msg = IO->Data;
704
705         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
706         return FinalizeMessageSend(Msg);
707 }
708 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
709 {
710         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
711         return Terminate(IO);
712 }
713 eNextState SMTP_C_Timeout(AsyncIO *IO)
714 {
715         SmtpOutMsg *Msg = IO->Data;
716
717         Msg->MyQEntry->Status = 4;
718         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
719         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
720         if (Msg->State > eRCPT)
721                 return eAbort;
722         else
723                 return FailOneAttempt(IO);
724 }
725 eNextState SMTP_C_ConnFail(AsyncIO *IO)
726 {
727         SmtpOutMsg *Msg = IO->Data;
728
729         Msg->MyQEntry->Status = 4;
730         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
731         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
732         return FailOneAttempt(IO);
733 }
734 eNextState SMTP_C_DNSFail(AsyncIO *IO)
735 {
736         SmtpOutMsg *Msg = IO->Data;
737         Msg->MyQEntry->Status = 4;
738         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
739         return FailOneAttempt(IO);
740 }
741 eNextState SMTP_C_Shutdown(AsyncIO *IO)
742 {
743         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
744         SmtpOutMsg *Msg = IO->Data;
745
746         Msg->MyQEntry->Status = 3;
747         StrBufPlain(Msg->MyQEntry->StatusMessage,
748                     HKEY("server shutdown during message submit."));
749         return FinalizeMessageSend(Msg);
750 }
751
752
753 /**
754  * @brief lineread Handler;
755  * understands when to read more SMTP lines, and when this is a one-lined reply.
756  */
757 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
758 {
759         eReadState Finished = eBufferNotEmpty;
760
761         while (Finished == eBufferNotEmpty) {
762                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
763
764                 switch (Finished) {
765                 case eMustReadMore: /// read new from socket...
766                         return Finished;
767                         break;
768                 case eBufferNotEmpty: /* shouldn't happen... */
769                 case eReadSuccess: /// done for now...
770                         if (StrLength(IO->IOBuf) < 4)
771                                 continue;
772                         if (ChrPtr(IO->IOBuf)[3] == '-')
773                                 Finished = eBufferNotEmpty;
774                         else
775                                 return Finished;
776                         break;
777                 case eReadFail: /// WHUT?
778                         ///todo: shut down!
779                         break;
780                 }
781         }
782         return Finished;
783 }
784
785 void LogDebugEnableSMTPClient(const int n)
786 {
787         SMTPClientDebugEnabled = n;
788 }
789
790 CTDL_MODULE_INIT(smtp_eventclient)
791 {
792         if (!threading)
793                 CtdlRegisterDebugFlagHook(HKEY("smtpeventclient"), LogDebugEnableSMTPClient, &SMTPClientDebugEnabled);
794         return "smtpeventclient";
795 }