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