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