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