SMTP-Client: make shure everything is finished before we terminate one client.
[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 n;
235         SmtpOutMsg *Msg = IO->Data;
236
237         n = GetShutdownDeliveries(Msg->MyQItem);
238         if (n > 0) 
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                 return mx_connect_ip(IO);
392         }
393         else
394                 return FailOneAttempt(IO);
395 }
396
397 eNextState get_one_mx_host_ip(AsyncIO *IO)
398 {
399         SmtpOutMsg * Msg = IO->Data;
400         /*
401          * here we start with the lookup of one host. it might be...
402          * - the relay host *sigh*
403          * - the direct hostname if there was no mx record
404          * - one of the mx'es
405          */
406
407         InitC_ares_dns(IO);
408
409         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
410
411         EVS_syslog(LOG_DEBUG,
412                   "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
413                   Msg->n,
414                   (Msg->pCurrRelay->IPv6)? "aaaa": "a",
415                   Msg->pCurrRelay->Host,
416                   Msg->pCurrRelay->Port);
417
418         if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
419                         Msg->pCurrRelay->Host,
420                         &Msg->IO,
421                         &Msg->HostLookup,
422                         get_one_mx_host_ip_done))
423         {
424                 Msg->MyQEntry->Status = 5;
425                 StrBufPrintf(Msg->MyQEntry->StatusMessage,
426                              "No MX hosts found for <%s>", Msg->node);
427                 Msg->IO.NextState = eTerminateConnection;
428                 return IO->NextState;
429         }
430         IO->NextState = eReadDNSReply;
431         return IO->NextState;
432 }
433
434
435 /*****************************************************************************
436  * here we try to find out about the MX records for our recipients.          *
437  *****************************************************************************/
438 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
439 {
440         SmtpOutMsg * Msg = IO->Data;
441         ParsedURL **pp;
442
443         QueryCbDone(IO);
444
445         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
446
447         pp = &Msg->Relay;
448         while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
449                 pp = &(*pp)->Next;
450
451         if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
452             (IO->DNS.Query->VParsedDNSReply != NULL))
453         { /* ok, we found mx records. */
454
455                 Msg->CurrMX
456                         = Msg->AllMX
457                         = IO->DNS.Query->VParsedDNSReply;
458                 while (Msg->CurrMX) {
459                         int i;
460                         for (i = 0; i < 2; i++) {
461                                 ParsedURL *p;
462
463                                 p = (ParsedURL*) malloc(sizeof(ParsedURL));
464                                 memset(p, 0, sizeof(ParsedURL));
465                                 p->Priority = Msg->CurrMX->priority;
466                                 p->IsIP = 0;
467                                 p->Port = DefaultMXPort;
468                                 p->IPv6 = i == 1;
469                                 p->Host = Msg->CurrMX->host;
470                                 if (*pp == NULL)
471                                         *pp = p;
472                                 else {
473                                         ParsedURL *ppp = *pp;
474
475                                         while ((ppp->Next != NULL) &&
476                                                (ppp->Next->Priority <= p->Priority))
477                                                ppp = ppp->Next;
478                                         if ((ppp == *pp) &&
479                                             (ppp->Priority > p->Priority)) {
480                                                 p->Next = *pp;
481                                                 *pp = p;
482                                         }
483                                         else {
484                                                 p->Next = ppp->Next;
485                                                 ppp->Next = p;
486                                         }
487                                 }
488                         }
489                         Msg->CurrMX    = Msg->CurrMX->next;
490                 }
491                 Msg->CXFlags   = Msg->CXFlags & F_HAVE_MX;
492         }
493         else { /* else fall back to the plain hostname */
494                 int i;
495                 for (i = 0; i < 2; i++) {
496                         ParsedURL *p;
497
498                         p = (ParsedURL*) malloc(sizeof(ParsedURL));
499                         memset(p, 0, sizeof(ParsedURL));
500                         p->IsIP = 0;
501                         p->Port = DefaultMXPort;
502                         p->IPv6 = i == 1;
503                         p->Host = Msg->node;
504
505                         *pp = p;
506                         pp = &p->Next;
507                 }
508                 Msg->CXFlags   = Msg->CXFlags & F_DIRECT;
509         }
510         if (Msg->MyQItem->FallBackHost != NULL)
511         {
512                 Msg->MyQItem->FallBackHost->Next = *pp;
513                 *pp = Msg->MyQItem->FallBackHost;
514         }
515         Msg->pCurrRelay = Msg->Relay;
516         return get_one_mx_host_ip(IO);
517 }
518
519 eNextState resolve_mx_records(AsyncIO *IO)
520 {
521         SmtpOutMsg * Msg = IO->Data;
522
523         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
524         /* start resolving MX records here. */
525         if (!QueueQuery(ns_t_mx,
526                         Msg->node,
527                         &Msg->IO,
528                         &Msg->MxLookup,
529                         smtp_resolve_mx_record_done))
530         {
531                 Msg->MyQEntry->Status = 5;
532                 StrBufPrintf(Msg->MyQEntry->StatusMessage,
533                              "No MX hosts found for <%s>", Msg->node);
534                 return IO->NextState;
535         }
536         Msg->IO.NextState = eReadDNSReply;
537         return IO->NextState;
538 }
539
540
541
542 /******************************************************************************
543  *  so, we're going to start a SMTP delivery.  lets get it on.                *
544  ******************************************************************************/
545
546 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
547                             MailQEntry *MyQEntry,
548                             int MsgCount)
549 {
550         SmtpOutMsg * Msg;
551
552         Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
553         memset(Msg, 0, sizeof(SmtpOutMsg));
554
555         Msg->n                = MsgCount;
556         Msg->MyQEntry         = MyQEntry;
557         Msg->MyQItem          = MyQItem;
558         Msg->pCurrRelay       = MyQItem->URL;
559
560         InitIOStruct(&Msg->IO,
561                      Msg,
562                      eReadMessage,
563                      SMTP_C_ReadServerStatus,
564                      SMTP_C_DNSFail,
565                      SMTP_C_DispatchWriteDone,
566                      SMTP_C_DispatchReadDone,
567                      SMTP_C_Terminate,
568                      SMTP_C_TerminateDB,
569                      SMTP_C_ConnFail,
570                      SMTP_C_Timeout,
571                      SMTP_C_Shutdown);
572
573         Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
574
575         return Msg;
576 }
577
578 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
579                               MailQEntry *MyQEntry,
580                               StrBuf *MsgText,
581                         /*KeepMsgText allows us to use MsgText as ours.*/
582                               int KeepMsgText,
583                               int MsgCount)
584 {
585         SmtpOutMsg *Msg;
586
587         syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
588
589         Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
590         if (KeepMsgText) Msg->msgtext = MsgText;
591         else             Msg->msgtext = NewStrBufDup(MsgText);
592
593         if (smtp_resolve_recipients(Msg)) {
594
595                 safestrncpy(
596                         ((CitContext *)Msg->IO.CitContext)->cs_host,
597                         Msg->node,
598                         sizeof(((CitContext *)
599                                 Msg->IO.CitContext)->cs_host));
600
601                 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
602                        Msg->MyQItem->MessageID,
603                        ChrPtr(Msg->MyQEntry->Recipient),
604                        ((CitContext*)Msg->IO.CitContext)->cs_pid);
605                 if (Msg->pCurrRelay == NULL)
606                         QueueEventContext(&Msg->IO,
607                                           resolve_mx_records);
608                 else { /* oh... via relay host */
609                         if (Msg->pCurrRelay->IsIP) {
610                                 QueueEventContext(&Msg->IO,
611                                                   mx_connect_ip);
612                         }
613                         else {
614                                 /* uneducated admin has chosen to
615                                    add DNS to the equation... */
616                                 QueueEventContext(&Msg->IO,
617                                                   get_one_mx_host_ip);
618                         }
619                 }
620         }
621         else {
622                 /* No recipients? well fail then. */
623                 if ((Msg==NULL) ||
624                     (Msg->MyQEntry == NULL)) {
625                         Msg->MyQEntry->Status = 5;
626                         StrBufPlain(Msg->MyQEntry->StatusMessage,
627                                     HKEY("Invalid Recipient!"));
628                 }
629                 FinalizeMessageSend_1(&Msg->IO);
630                 FinalizeMessageSend_DB_1(&Msg->IO);
631                 FinalizeMessageSend_DB_2(&Msg->IO);
632                 FinalizeMessageSend_DB_3(&Msg->IO);
633                 FinalizeMessageSend_DB(&Msg->IO);
634         }
635 }
636
637
638
639
640
641
642 /*****************************************************************************/
643 /*                     SMTP CLIENT DISPATCHER                                */
644 /*****************************************************************************/
645
646 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
647 {
648         double Timeout = 0.0;
649         AsyncIO *IO = &Msg->IO;
650
651         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
652
653         switch (NextTCPState) {
654         case eSendFile:
655         case eSendReply:
656         case eSendMore:
657                 Timeout = SMTP_C_SendTimeouts[Msg->State];
658                 if (Msg->State == eDATABody) {
659                         /* if we're sending a huge message,
660                          * we need more time.
661                          */
662                         Timeout += StrLength(Msg->msgtext) / 512;
663                 }
664                 break;
665         case eReadMessage:
666                 Timeout = SMTP_C_ReadTimeouts[Msg->State];
667                 if (Msg->State == eDATATerminateBody) {
668                         /*
669                          * some mailservers take a nap before accepting
670                          * the message content inspection and such.
671                          */
672                         Timeout += StrLength(Msg->msgtext) / 512;
673                 }
674                 break;
675         case eSendDNSQuery:
676         case eReadDNSReply:
677         case eDBQuery:
678         case eReadFile:
679         case eReadMore:
680         case eReadPayload:
681         case eConnect:
682         case eTerminateConnection:
683         case eAbort:
684                 return;
685         }
686         SetNextTimeout(&Msg->IO, Timeout);
687 }
688 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
689 {
690         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
691         SmtpOutMsg *Msg = IO->Data;
692         eNextState rc;
693
694         rc = ReadHandlers[Msg->State](Msg);
695         if (rc != eAbort)
696         {
697                 Msg->State++;
698                 SMTPSetTimeout(rc, Msg);
699         }
700         return rc;
701 }
702 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
703 {
704         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
705         SmtpOutMsg *Msg = IO->Data;
706         eNextState rc;
707
708         rc = SendHandlers[Msg->State](Msg);
709         SMTPSetTimeout(rc, Msg);
710         return rc;
711 }
712
713
714 /*****************************************************************************/
715 /*                     SMTP CLIENT ERROR CATCHERS                            */
716 /*****************************************************************************/
717 eNextState SMTP_C_Terminate(AsyncIO *IO)
718 {
719         SmtpOutMsg *Msg = IO->Data;
720
721         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
722         return FinalizeMessageSend(Msg);
723 }
724 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
725 {
726         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
727         return FinalizeMessageSend_DB(IO);
728 }
729 eNextState SMTP_C_Timeout(AsyncIO *IO)
730 {
731         SmtpOutMsg *Msg = IO->Data;
732
733         Msg->MyQEntry->Status = 4;
734         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
735         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
736         if (Msg->State > eRCPT)
737                 return eAbort;
738         else
739                 return FailOneAttempt(IO);
740 }
741 eNextState SMTP_C_ConnFail(AsyncIO *IO)
742 {
743         SmtpOutMsg *Msg = IO->Data;
744
745         Msg->MyQEntry->Status = 4;
746         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
747         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
748         return FailOneAttempt(IO);
749 }
750 eNextState SMTP_C_DNSFail(AsyncIO *IO)
751 {
752         SmtpOutMsg *Msg = IO->Data;
753         Msg->MyQEntry->Status = 4;
754         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
755         return FailOneAttempt(IO);
756 }
757 eNextState SMTP_C_Shutdown(AsyncIO *IO)
758 {
759         EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
760         SmtpOutMsg *Msg = IO->Data;
761
762         Msg->MyQEntry->Status = 3;
763         StrBufPlain(Msg->MyQEntry->StatusMessage,
764                     HKEY("server shutdown during message submit."));
765         return FinalizeMessageSend(Msg);
766 }
767
768
769 /**
770  * @brief lineread Handler;
771  * understands when to read more SMTP lines, and when this is a one-lined reply.
772  */
773 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
774 {
775         eReadState Finished = eBufferNotEmpty;
776
777         while (Finished == eBufferNotEmpty) {
778                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
779
780                 switch (Finished) {
781                 case eMustReadMore: /// read new from socket...
782                         return Finished;
783                         break;
784                 case eBufferNotEmpty: /* shouldn't happen... */
785                 case eReadSuccess: /// done for now...
786                         if (StrLength(IO->IOBuf) < 4)
787                                 continue;
788                         if (ChrPtr(IO->IOBuf)[3] == '-')
789                                 Finished = eBufferNotEmpty;
790                         else
791                                 return Finished;
792                         break;
793                 case eReadFail: /// WHUT?
794                         ///todo: shut down!
795                         break;
796                 }
797         }
798         return Finished;
799 }
800
801 CTDL_MODULE_INIT(smtp_eventclient)
802 {
803         return "smtpeventclient";
804 }