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