c7de74fac3e9da7fffd65b10251b42c36a9411af
[citadel.git] / citadel / modules / smtp / serv_smtpeventclient.c
1 /*
2  * This module is an SMTP and ESMTP implementation for the Citadel system.
3  * It is compliant with all of the following:
4  *
5  * RFC  821 - Simple Mail Transfer Protocol
6  * RFC  876 - Survey of SMTP Implementations
7  * RFC 1047 - Duplicate messages and SMTP
8  * RFC 1652 - 8 bit MIME
9  * RFC 1869 - Extended Simple Mail Transfer Protocol
10  * RFC 1870 - SMTP Service Extension for Message Size Declaration
11  * RFC 2033 - Local Mail Transfer Protocol
12  * RFC 2197 - SMTP Service Extension for Command Pipelining
13  * RFC 2476 - Message Submission
14  * RFC 2487 - SMTP Service Extension for Secure SMTP over TLS
15  * RFC 2554 - SMTP Service Extension for Authentication
16  * RFC 2821 - Simple Mail Transfer Protocol
17  * RFC 2822 - Internet Message Format
18  * RFC 2920 - SMTP Service Extension for Command Pipelining
19  *
20  * The VRFY and EXPN commands have been removed from this implementation
21  * because nobody uses these commands anymore, except for spammers.
22  *
23  * Copyright (c) 1998-2012 by the citadel.org team
24  *
25  *  This program is open source software; you can redistribute it and/or modify
26  *  it under the terms of the GNU General Public License version 3.
27  *  
28  *  
29  *
30  *  This program is distributed in the hope that it will be useful,
31  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
32  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  *  GNU General Public License for more details.
34  *
35  *  
36  *  
37  *  
38  */
39
40 #include "sysdep.h"
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <stdio.h>
44 #include <termios.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <sys/types.h>
50 #include <syslog.h>
51
52 #if TIME_WITH_SYS_TIME
53 # include <sys/time.h>
54 # include <time.h>
55 #else
56 # if HAVE_SYS_TIME_H
57 #  include <sys/time.h>
58 # else
59 #  include <time.h>
60 # endif
61 #endif
62 #include <sys/wait.h>
63 #include <ctype.h>
64 #include <string.h>
65 #include <limits.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "control.h"
76 #include "user_ops.h"
77 #include "database.h"
78 #include "msgbase.h"
79 #include "internet_addressing.h"
80 #include "genstamp.h"
81 #include "domain.h"
82 #include "clientsocket.h"
83 #include "locate_host.h"
84 #include "citadel_dirs.h"
85
86 #include "ctdl_module.h"
87
88 #include "smtp_util.h"
89 #include "event_client.h"
90 #include "smtpqueue.h"
91 #include "smtp_clienthandlers.h"
92
93 int SMTPClientDebugEnabled = 0;
94 void DeleteSmtpOutMsg(void *v)
95 {
96         SmtpOutMsg *Msg = v;
97         AsyncIO *IO = &Msg->IO;
98         EV_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
99
100         /* these are kept in our own space and free'd below */
101         Msg->IO.ConnectMe = NULL;
102
103         ares_free_data(Msg->AllMX);
104         if (Msg->HostLookup.VParsedDNSReply != NULL)
105                 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
106         FreeURL(&Msg->Relay);
107         FreeStrBuf(&Msg->msgtext);
108         FreeAsyncIOContents(&Msg->IO);
109         memset (Msg, 0, sizeof(SmtpOutMsg)); /* just to be shure... */
110         free(Msg);
111 }
112
113 eNextState SMTP_C_Shutdown(AsyncIO *IO);
114 eNextState SMTP_C_Timeout(AsyncIO *IO);
115 eNextState SMTP_C_ConnFail(AsyncIO *IO);
116 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
117 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
118 eNextState SMTP_C_DNSFail(AsyncIO *IO);
119 eNextState SMTP_C_Terminate(AsyncIO *IO);
120 eNextState SMTP_C_TerminateDB(AsyncIO *IO);
121 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
122
123 eNextState mx_connect_ip(AsyncIO *IO);
124 eNextState get_one_mx_host_ip(AsyncIO *IO);
125
126 /******************************************************************************
127  * So, we're finished with sending (regardless of success or failure)         *
128  * This Message might be referenced by several Queue-Items, if we're the last,*
129  * we need to free the memory and send bounce messages (on terminal failure)  *
130  * else we just free our SMTP-Message struct.                                 *
131  ******************************************************************************/
132 eNextState FinalizeMessageSend_DB(AsyncIO *IO)
133 {
134         const char *Status;
135         SmtpOutMsg *Msg = IO->Data;
136         
137         if (Msg->MyQEntry->Status == 2) 
138                 Status = "Delivery successful.";
139         else if (Msg->MyQEntry->Status == 5) 
140                 Status = "Delivery failed permanently; giving up.";
141         else
142                 Status = "Delivery failed temporarily; will retry later.";
143                         
144         EVS_syslog(LOG_INFO,
145                    "%s Time[%fs] Recipient <%s> @ <%s> (%s) Status message: %s\n",
146                    Status,
147                    Msg->IO.Now - Msg->IO.StartIO,
148                    Msg->user,
149                    Msg->node,
150                    Msg->name,
151                    ChrPtr(Msg->MyQEntry->StatusMessage));
152
153
154         Msg->IDestructQueItem = DecreaseQReference(Msg->MyQItem);
155
156         Msg->nRemain = CountActiveQueueEntries(Msg->MyQItem);
157
158         if (Msg->MyQEntry->Active && 
159             CheckQEntryIsBounce(Msg->MyQEntry))
160         {
161                 /* are we casue for a bounce mail? */
162                 Msg->MyQItem->SendBounceMail |= (1<<Msg->MyQEntry->Status);
163         }
164
165         if ((Msg->nRemain > 0) || Msg->IDestructQueItem)
166                 Msg->QMsgData = SerializeQueueItem(Msg->MyQItem);
167         else
168                 Msg->QMsgData = NULL;
169
170         /*
171          * Uncompleted delivery instructions remain, so delete the old
172          * instructions and replace with the updated ones.
173          */
174         EVS_syslog(LOG_DEBUG, "%ld", Msg->MyQItem->QueMsgID);
175         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
176         Msg->MyQItem->QueMsgID = -1;
177
178         if (Msg->IDestructQueItem)
179                 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
180
181         if (Msg->nRemain > 0)
182         {
183                 struct CtdlMessage *msg;
184                 msg = malloc(sizeof(struct CtdlMessage));
185                 memset(msg, 0, sizeof(struct CtdlMessage));
186                 msg->cm_magic = CTDLMESSAGE_MAGIC;
187                 msg->cm_anon_type = MES_NORMAL;
188                 msg->cm_format_type = FMT_RFC822;
189                 msg->cm_fields['M'] = SmashStrBuf(&Msg->QMsgData);
190                 msg->cm_fields['U'] = strdup("QMSG");
191                 Msg->MyQItem->QueMsgID =
192                         CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
193                 EVS_syslog(LOG_DEBUG, "%ld", Msg->MyQItem->QueMsgID);
194                 CtdlFreeMessage(msg);
195         }
196         else {
197                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
198                                    &Msg->MyQItem->MessageID,
199                                    1,
200                                    "");
201                 FreeStrBuf(&Msg->QMsgData);
202         }
203
204         RemoveContext(Msg->IO.CitContext);
205         return eAbort;
206 }
207
208 eNextState Terminate(AsyncIO *IO)
209 {
210         SmtpOutMsg *Msg = IO->Data;
211
212         if (Msg->IDestructQueItem)
213                 RemoveQItem(Msg->MyQItem);
214
215         DeleteSmtpOutMsg(Msg);
216         return eAbort;
217 }
218 eNextState FinalizeMessageSend(SmtpOutMsg *Msg)
219 {
220         /* hand over to DB Queue */
221         return QueueDBOperation(&Msg->IO, FinalizeMessageSend_DB);
222 }
223
224 eNextState FailOneAttempt(AsyncIO *IO)
225 {
226         SmtpOutMsg *Msg = IO->Data;
227
228         if (Msg->MyQEntry->Status == 2)
229                 return eAbort;
230
231         /*
232          * possible ways here:
233          * - connection timeout
234          * - dns lookup failed
235          */
236         StopClientWatchers(IO);
237
238         if (Msg->pCurrRelay != NULL)
239                 Msg->pCurrRelay = Msg->pCurrRelay->Next;
240
241         if (Msg->pCurrRelay == NULL) {
242                 EVS_syslog(LOG_DEBUG, "%s Aborting\n", __FUNCTION__);
243                 return eAbort;
244         }
245         if (Msg->pCurrRelay->IsIP) {
246                 EVS_syslog(LOG_DEBUG, "%s connecting IP\n", __FUNCTION__);
247                 return mx_connect_ip(IO);
248         }
249         else {
250                 EVS_syslog(LOG_DEBUG,
251                            "%s resolving next MX Record\n",
252                            __FUNCTION__);
253                 return get_one_mx_host_ip(IO);
254         }
255 }
256
257
258 void SetConnectStatus(AsyncIO *IO)
259 {
260         SmtpOutMsg *Msg = IO->Data;
261         char buf[256];
262         void *src;
263
264         buf[0] = '\0';
265
266         if (IO->ConnectMe->IPv6) {
267                 src = &IO->ConnectMe->Addr.sin6_addr;
268         }
269         else {
270                 struct sockaddr_in *addr;
271
272                 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
273                 src = &addr->sin_addr.s_addr;
274         }
275
276         inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
277                   src,
278                   buf,
279                   sizeof(buf));
280
281         if (Msg->mx_host == NULL)
282                 Msg->mx_host = "<no MX-Record>";
283
284         EVS_syslog(LOG_INFO,
285                   "connecting to %s [%s]:%d ...\n",
286                   Msg->mx_host,
287                   buf,
288                   Msg->IO.ConnectMe->Port);
289
290         Msg->MyQEntry->Status = 4;
291         StrBufPrintf(Msg->MyQEntry->StatusMessage,
292                      "Timeout while connecting %s [%s]:%d ",
293                      Msg->mx_host,
294                      buf,
295                      Msg->IO.ConnectMe->Port);
296         Msg->IO.NextState = eConnect;
297 }
298
299 /*****************************************************************************
300  * So we connect our Relay IP here.                                          *
301  *****************************************************************************/
302 eNextState mx_connect_ip(AsyncIO *IO)
303 {
304         SmtpOutMsg *Msg = IO->Data;
305
306         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
307
308         IO->ConnectMe = Msg->pCurrRelay;
309         Msg->State = eConnectMX;
310
311         SetConnectStatus(IO);
312
313         return EvConnectSock(IO,
314                              SMTP_C_ConnTimeout,
315                              SMTP_C_ReadTimeouts[0],
316                              1);
317 }
318
319 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
320 {
321         SmtpOutMsg *Msg = IO->Data;
322         struct hostent *hostent;
323
324         IO->ConnectMe = Msg->pCurrRelay;
325
326         QueryCbDone(IO);
327         EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
328                    __FUNCTION__,
329                    IO->Now - IO->DNS.Start);
330
331         hostent = Msg->HostLookup.VParsedDNSReply;
332         if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
333             (hostent != NULL) ) {
334                 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
335                 if (Msg->pCurrRelay->IPv6) {
336                         memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
337                                &hostent->h_addr_list[0],
338                                sizeof(struct in6_addr));
339
340                         Msg->pCurrRelay->Addr.sin6_family =
341                                 hostent->h_addrtype;
342                         Msg->pCurrRelay->Addr.sin6_port =
343                                 htons(Msg->IO.ConnectMe->Port);
344                 }
345                 else {
346                         struct sockaddr_in *addr;
347                         /*
348                          * Bypass the ns lookup result like this:
349                          * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
350                          * addr->sin_addr.s_addr =
351                          *   htonl((uint32_t)&hostent->h_addr_list[0]);
352                          */
353
354                         addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
355
356                         memcpy(&addr->sin_addr.s_addr,
357                                hostent->h_addr_list[0],
358                                sizeof(uint32_t));
359
360                         addr->sin_family = hostent->h_addrtype;
361                         addr->sin_port   = htons(Msg->IO.ConnectMe->Port);
362                 }
363                 Msg->mx_host = Msg->pCurrRelay->Host;
364                 if (Msg->HostLookup.VParsedDNSReply != NULL) {
365                         Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
366                         Msg->HostLookup.VParsedDNSReply = NULL;
367                 }
368                 return mx_connect_ip(IO);
369         }
370         else {
371                 if (Msg->HostLookup.VParsedDNSReply != NULL) {
372                         Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
373                         Msg->HostLookup.VParsedDNSReply = NULL;
374                 }
375                 return FailOneAttempt(IO);
376         }
377 }
378
379 eNextState get_one_mx_host_ip(AsyncIO *IO)
380 {
381         SmtpOutMsg * Msg = IO->Data;
382         /*
383          * here we start with the lookup of one host. it might be...
384          * - the relay host *sigh*
385          * - the direct hostname if there was no mx record
386          * - one of the mx'es
387          */
388
389         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
390
391         EVS_syslog(LOG_DEBUG,
392                   "looking up %s-Record %s : %d ...\n",
393                   (Msg->pCurrRelay->IPv6)? "aaaa": "a",
394                   Msg->pCurrRelay->Host,
395                   Msg->pCurrRelay->Port);
396
397         if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
398                         Msg->pCurrRelay->Host,
399                         &Msg->IO,
400                         &Msg->HostLookup,
401                         get_one_mx_host_ip_done))
402         {
403                 Msg->MyQEntry->Status = 5;
404                 StrBufPrintf(Msg->MyQEntry->StatusMessage,
405                              "No MX hosts found for <%s>", Msg->node);
406                 Msg->IO.NextState = eTerminateConnection;
407                 return IO->NextState;
408         }
409         IO->NextState = eReadDNSReply;
410         return IO->NextState;
411 }
412
413
414 /*****************************************************************************
415  * here we try to find out about the MX records for our recipients.          *
416  *****************************************************************************/
417 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
418 {
419         SmtpOutMsg * Msg = IO->Data;
420         ParsedURL **pp;
421
422         QueryCbDone(IO);
423
424         EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
425                    __FUNCTION__,
426                    IO->Now - IO->DNS.Start);
427
428         pp = &Msg->Relay;
429         while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
430                 pp = &(*pp)->Next;
431
432         if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
433             (IO->DNS.Query->VParsedDNSReply != NULL))
434         { /* ok, we found mx records. */
435
436                 Msg->CurrMX
437                         = Msg->AllMX
438                         = IO->DNS.Query->VParsedDNSReply;
439                 while (Msg->CurrMX) {
440                         int i;
441                         for (i = 0; i < 2; i++) {
442                                 ParsedURL *p;
443
444                                 p = (ParsedURL*) malloc(sizeof(ParsedURL));
445                                 memset(p, 0, sizeof(ParsedURL));
446                                 p->Priority = Msg->CurrMX->priority;
447                                 p->IsIP = 0;
448                                 p->Port = DefaultMXPort;
449                                 p->IPv6 = i == 1;
450                                 p->Host = Msg->CurrMX->host;
451                                 if (*pp == NULL)
452                                         *pp = p;
453                                 else {
454                                         ParsedURL *ppp = *pp;
455
456                                         while ((ppp->Next != NULL) &&
457                                                (ppp->Next->Priority <= p->Priority))
458                                                ppp = ppp->Next;
459                                         if ((ppp == *pp) &&
460                                             (ppp->Priority > p->Priority)) {
461                                                 p->Next = *pp;
462                                                 *pp = p;
463                                         }
464                                         else {
465                                                 p->Next = ppp->Next;
466                                                 ppp->Next = p;
467                                         }
468                                 }
469                         }
470                         Msg->CurrMX    = Msg->CurrMX->next;
471                 }
472                 Msg->CXFlags   = Msg->CXFlags & F_HAVE_MX;
473         }
474         else { /* else fall back to the plain hostname */
475                 int i;
476                 for (i = 0; i < 2; i++) {
477                         ParsedURL *p;
478
479                         p = (ParsedURL*) malloc(sizeof(ParsedURL));
480                         memset(p, 0, sizeof(ParsedURL));
481                         p->IsIP = 0;
482                         p->Port = DefaultMXPort;
483                         p->IPv6 = i == 1;
484                         p->Host = Msg->node;
485
486                         *pp = p;
487                         pp = &p->Next;
488                 }
489                 Msg->CXFlags   = Msg->CXFlags & F_DIRECT;
490         }
491         if (Msg->MyQItem->FallBackHost != NULL)
492         {
493                 Msg->MyQItem->FallBackHost->Next = *pp;
494                 *pp = Msg->MyQItem->FallBackHost;
495         }
496         Msg->pCurrRelay = Msg->Relay;
497         return get_one_mx_host_ip(IO);
498 }
499
500 eNextState resolve_mx_records(AsyncIO *IO)
501 {
502         SmtpOutMsg * Msg = IO->Data;
503
504         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
505         /* start resolving MX records here. */
506         if (!QueueQuery(ns_t_mx,
507                         Msg->node,
508                         &Msg->IO,
509                         &Msg->MxLookup,
510                         smtp_resolve_mx_record_done))
511         {
512                 Msg->MyQEntry->Status = 5;
513                 StrBufPrintf(Msg->MyQEntry->StatusMessage,
514                              "No MX hosts found for <%s>", Msg->node);
515                 return IO->NextState;
516         }
517         Msg->IO.NextState = eReadDNSReply;
518         return IO->NextState;
519 }
520
521
522
523 /******************************************************************************
524  *  so, we're going to start a SMTP delivery.  lets get it on.                *
525  ******************************************************************************/
526
527 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
528                             MailQEntry *MyQEntry,
529                             int MsgCount)
530 {
531         SmtpOutMsg * Msg;
532
533         Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
534         if (Msg == NULL)
535                 return NULL;
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         SMTPC_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
571
572         Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
573         if (Msg == NULL) {
574                 SMTPC_syslog(LOG_DEBUG, "%s Failed to alocate message context.\n", __FUNCTION__);
575                 if (KeepMsgText) 
576                         FreeStrBuf (&MsgText);
577                 return;
578         }
579         if (KeepMsgText) Msg->msgtext = MsgText;
580         else             Msg->msgtext = NewStrBufDup(MsgText);
581
582         if (smtp_resolve_recipients(Msg)) {
583
584                 safestrncpy(
585                         ((CitContext *)Msg->IO.CitContext)->cs_host,
586                         Msg->node,
587                         sizeof(((CitContext *)
588                                 Msg->IO.CitContext)->cs_host));
589
590                 SMTPC_syslog(LOG_DEBUG, "Starting: [%ld] <%s> CC <%d> \n",
591                              Msg->MyQItem->MessageID,
592                              ChrPtr(Msg->MyQEntry->Recipient),
593                              ((CitContext*)Msg->IO.CitContext)->cs_pid);
594                 if (Msg->pCurrRelay == NULL)
595                         QueueEventContext(&Msg->IO,
596                                           resolve_mx_records);
597                 else { /* oh... via relay host */
598                         if (Msg->pCurrRelay->IsIP) {
599                                 QueueEventContext(&Msg->IO,
600                                                   mx_connect_ip);
601                         }
602                         else {
603                                 /* uneducated admin has chosen to
604                                    add DNS to the equation... */
605                                 QueueEventContext(&Msg->IO,
606                                                   get_one_mx_host_ip);
607                         }
608                 }
609         }
610         else {
611                 /* No recipients? well fail then. */
612                 if (Msg->MyQEntry != NULL) {
613                         Msg->MyQEntry->Status = 5;
614                         StrBufPlain(Msg->MyQEntry->StatusMessage,
615                                     HKEY("Invalid Recipient!"));
616                 }
617                 FinalizeMessageSend_DB(&Msg->IO);
618                 DeleteSmtpOutMsg(&Msg->IO);
619         }
620 }
621
622
623
624
625
626
627 /*****************************************************************************/
628 /*                     SMTP CLIENT DISPATCHER                                */
629 /*****************************************************************************/
630
631 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
632 {
633         double Timeout = 0.0;
634         AsyncIO *IO = &Msg->IO;
635
636         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
637
638         switch (NextTCPState) {
639         case eSendFile:
640         case eSendReply:
641         case eSendMore:
642                 Timeout = SMTP_C_SendTimeouts[Msg->State];
643                 if (Msg->State == eDATABody) {
644                         /* if we're sending a huge message,
645                          * we need more time.
646                          */
647                         Timeout += StrLength(Msg->msgtext) / 512;
648                 }
649                 break;
650         case eReadMessage:
651                 Timeout = SMTP_C_ReadTimeouts[Msg->State];
652                 if (Msg->State == eDATATerminateBody) {
653                         /*
654                          * some mailservers take a nap before accepting
655                          * the message content inspection and such.
656                          */
657                         Timeout += StrLength(Msg->msgtext) / 512;
658                 }
659                 break;
660         case eSendDNSQuery:
661         case eReadDNSReply:
662         case eDBQuery:
663         case eReadFile:
664         case eReadMore:
665         case eReadPayload:
666         case eConnect:
667         case eTerminateConnection:
668         case eAbort:
669                 return;
670         }
671         SetNextTimeout(&Msg->IO, Timeout);
672 }
673 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
674 {
675         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
676         SmtpOutMsg *Msg = IO->Data;
677         eNextState rc;
678
679         rc = ReadHandlers[Msg->State](Msg);
680         if (rc != eAbort)
681         {
682                 Msg->State++;
683                 SMTPSetTimeout(rc, Msg);
684         }
685         return rc;
686 }
687 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
688 {
689         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
690         SmtpOutMsg *Msg = IO->Data;
691         eNextState rc;
692
693         rc = SendHandlers[Msg->State](Msg);
694         SMTPSetTimeout(rc, Msg);
695         return rc;
696 }
697
698
699 /*****************************************************************************/
700 /*                     SMTP CLIENT ERROR CATCHERS                            */
701 /*****************************************************************************/
702 eNextState SMTP_C_Terminate(AsyncIO *IO)
703 {
704         SmtpOutMsg *Msg = IO->Data;
705
706         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
707         return FinalizeMessageSend(Msg);
708 }
709 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
710 {
711         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
712         return Terminate(IO);
713 }
714 eNextState SMTP_C_Timeout(AsyncIO *IO)
715 {
716         SmtpOutMsg *Msg = IO->Data;
717
718         Msg->MyQEntry->Status = 4;
719         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
720         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
721         if (Msg->State > eRCPT)
722                 return eAbort;
723         else
724                 return FailOneAttempt(IO);
725 }
726 eNextState SMTP_C_ConnFail(AsyncIO *IO)
727 {
728         SmtpOutMsg *Msg = IO->Data;
729
730         Msg->MyQEntry->Status = 4;
731         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
732         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
733         return FailOneAttempt(IO);
734 }
735 eNextState SMTP_C_DNSFail(AsyncIO *IO)
736 {
737         SmtpOutMsg *Msg = IO->Data;
738         Msg->MyQEntry->Status = 4;
739         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
740         return FailOneAttempt(IO);
741 }
742 eNextState SMTP_C_Shutdown(AsyncIO *IO)
743 {
744         EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
745         SmtpOutMsg *Msg = IO->Data;
746
747         Msg->MyQEntry->Status = 3;
748         StrBufPlain(Msg->MyQEntry->StatusMessage,
749                     HKEY("server shutdown during message submit."));
750         return FinalizeMessageSend(Msg);
751 }
752
753
754 /**
755  * @brief lineread Handler;
756  * understands when to read more SMTP lines, and when this is a one-lined reply.
757  */
758 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
759 {
760         eReadState Finished = eBufferNotEmpty;
761
762         while (Finished == eBufferNotEmpty) {
763                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
764
765                 switch (Finished) {
766                 case eMustReadMore: /// read new from socket...
767                         return Finished;
768                         break;
769                 case eBufferNotEmpty: /* shouldn't happen... */
770                 case eReadSuccess: /// done for now...
771                         if (StrLength(IO->IOBuf) < 4)
772                                 continue;
773                         if (ChrPtr(IO->IOBuf)[3] == '-')
774                                 Finished = eBufferNotEmpty;
775                         else
776                                 return Finished;
777                         break;
778                 case eReadFail: /// WHUT?
779                         ///todo: shut down!
780                         break;
781                 }
782         }
783         return Finished;
784 }
785
786 void LogDebugEnableSMTPClient(const int n)
787 {
788         SMTPClientDebugEnabled = n;
789 }
790
791 CTDL_MODULE_INIT(smtp_eventclient)
792 {
793         if (!threading)
794                 CtdlRegisterDebugFlagHook(HKEY("smtpeventclient"), LogDebugEnableSMTPClient, &SMTPClientDebugEnabled);
795         return "smtpeventclient";
796 }