libev/c-ares migration: unstack out ouf c-ares before querying new requests
[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-2009 by the citadel.org team
24  *
25  *  This program is free software; you can redistribute it and/or modify
26  *  it under the terms of the GNU General Public License as published by
27  *  the Free Software Foundation; either version 3 of the License, or
28  *  (at your option) any later version.
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  *  You should have received a copy of the GNU General Public License
36  *  along with this program; if not, write to the Free Software
37  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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
92 #ifdef EXPERIMENTAL_SMTP_EVENT_CLIENT
93 /*****************************************************************************/
94 /*               SMTP CLIENT (OUTBOUND PROCESSING) STUFF                     */
95 /*****************************************************************************/
96
97 typedef enum _eSMTP_C_States {
98         eConnect, 
99         eEHLO,
100         eHELO,
101         eSMTPAuth,
102         eFROM,
103         eRCPT,
104         eDATA,
105         eDATABody,
106         eDATATerminateBody,
107         eQUIT,
108         eMaxSMTPC
109 } eSMTP_C_States;
110
111 const double SMTP_C_ConnTimeout = 300.; /* wail 1 minute for connections... */
112 const double SMTP_C_ReadTimeouts[eMaxSMTPC] = {
113         300., /* Greeting... */
114         30., /* EHLO */
115         30., /* HELO */
116         30., /* Auth */
117         30., /* From */
118         90., /* RCPT */
119         30., /* DATA */
120         90., /* DATABody */
121         90., /* end of body... */
122         30.  /* QUIT */
123 };
124 const double SMTP_C_SendTimeouts[eMaxSMTPC] = {
125         90., /* Greeting... */
126         30., /* EHLO */
127         30., /* HELO */
128         30., /* Auth */
129         30., /* From */
130         30., /* RCPT */
131         30., /* DATA */
132         90., /* DATABody */
133         900., /* end of body... */
134         30.  /* QUIT */
135 };
136
137 static const ConstStr ReadErrors[eMaxSMTPC] = {
138         {HKEY("Connection broken during SMTP conversation")},
139         {HKEY("Connection broken during SMTP EHLO")},
140         {HKEY("Connection broken during SMTP HELO")},
141         {HKEY("Connection broken during SMTP AUTH")},
142         {HKEY("Connection broken during SMTP MAIL FROM")},
143         {HKEY("Connection broken during SMTP RCPT")},
144         {HKEY("Connection broken during SMTP DATA")},
145         {HKEY("Connection broken during SMTP message transmit")},
146         {HKEY("")}/* quit reply, don't care. */
147 };
148
149
150 typedef struct _stmp_out_msg {
151         MailQEntry *MyQEntry;
152         OneQueItem *MyQItem;
153         long n;
154         AsyncIO IO;
155
156         eSMTP_C_States State;
157
158         struct ares_mx_reply *AllMX;
159         struct ares_mx_reply *CurrMX;
160         const char *mx_port;
161         const char *mx_host;
162
163         struct hostent *OneMX;
164
165         ParsedURL *Relay;
166         ParsedURL *pCurrRelay;
167         StrBuf *msgtext;
168         char *envelope_from;
169         char user[1024];
170         char node[1024];
171         char name[1024];
172         char mailfrom[1024];
173 } SmtpOutMsg;
174
175 void DeleteSmtpOutMsg(void *v)
176 {
177         SmtpOutMsg *Msg = v;
178
179         ares_free_data(Msg->AllMX);
180         
181         FreeStrBuf(&Msg->msgtext);
182         FreeAsyncIOContents(&Msg->IO);
183         free(Msg);
184 }
185
186 eNextState SMTP_C_Timeout(AsyncIO *IO);
187 eNextState SMTP_C_ConnFail(AsyncIO *IO);
188 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
189 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
190 eNextState SMTP_C_Terminate(AsyncIO *IO);
191 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
192
193 typedef eNextState (*SMTPReadHandler)(SmtpOutMsg *Msg);
194 typedef eNextState (*SMTPSendHandler)(SmtpOutMsg *Msg);
195
196
197 #define SMTP_ERROR(WHICH_ERR, ERRSTR) do {\
198                 SendMsg->MyQEntry->Status = WHICH_ERR; \
199                 StrBufAppendBufPlain(SendMsg->MyQEntry->StatusMessage, HKEY(ERRSTR), 0); \
200                 return eAbort; } \
201         while (0)
202
203 #define SMTP_VERROR(WHICH_ERR) do {\
204                 SendMsg->MyQEntry->Status = WHICH_ERR; \
205                 StrBufPlain(SendMsg->MyQEntry->StatusMessage, \
206                             ChrPtr(SendMsg->IO.IOBuf) + 4, \
207                             StrLength(SendMsg->IO.IOBuf) - 4); \
208                 return eAbort; } \
209         while (0)
210
211 #define SMTP_IS_STATE(WHICH_STATE) (ChrPtr(SendMsg->IO.IOBuf)[0] == WHICH_STATE)
212
213 #define SMTP_DBG_SEND() CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: > %s\n", SendMsg->n, ChrPtr(SendMsg->IO.SendBuf.Buf))
214 #define SMTP_DBG_READ() CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: < %s\n", SendMsg->n, ChrPtr(SendMsg->IO.IOBuf))
215
216
217 void FinalizeMessageSend(SmtpOutMsg *Msg)
218 {
219         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
220         
221         if (DecreaseQReference(Msg->MyQItem)) 
222         {
223                 int nRemain;
224                 StrBuf *MsgData;
225
226                 nRemain = CountActiveQueueEntries(Msg->MyQItem);
227
228                 MsgData = SerializeQueueItem(Msg->MyQItem);
229                 /*
230                  * Uncompleted delivery instructions remain, so delete the old
231                  * instructions and replace with the updated ones.
232                  */
233                 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
234                 smtpq_do_bounce(Msg->MyQItem,
235                                Msg->msgtext); 
236                 if (nRemain > 0) {
237                         struct CtdlMessage *msg;
238                         msg = malloc(sizeof(struct CtdlMessage));
239                         memset(msg, 0, sizeof(struct CtdlMessage));
240                         msg->cm_magic = CTDLMESSAGE_MAGIC;
241                         msg->cm_anon_type = MES_NORMAL;
242                         msg->cm_format_type = FMT_RFC822;
243                         msg->cm_fields['M'] = SmashStrBuf(&MsgData);
244                         CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
245                         CtdlFreeMessage(msg);
246                 }
247                 else {
248                         CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->MessageID, 1, "");
249                         FreeStrBuf(&MsgData);
250                 }
251
252                 RemoveQItem(Msg->MyQItem);
253         }
254         DeleteSmtpOutMsg(Msg);
255 }
256
257
258 void SetConnectStatus(AsyncIO *IO)
259 {
260         
261         SmtpOutMsg *SendMsg = IO->Data;
262         char buf[256];
263         void *src;
264
265         buf[0] = '\0';
266
267         if (IO->IP6) {
268                 src = &IO->Addr.sin6_addr;
269         }
270         else {
271                 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->Addr;
272
273                 src = &addr->sin_addr.s_addr;
274         }
275
276         inet_ntop((IO->IP6)?AF_INET6:AF_INET,
277                   src,
278                   buf, sizeof(buf));
279         if (SendMsg->mx_host == NULL)
280                 SendMsg->mx_host = "<no name>";
281
282         CtdlLogPrintf(CTDL_DEBUG, 
283                       "SMTP client[%ld]: connecting to %s [%s]:%d ...\n", 
284                       SendMsg->n, 
285                       SendMsg->mx_host, 
286                       buf,
287                       SendMsg->IO.dport);
288
289         SendMsg->MyQEntry->Status = 5; 
290         StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
291                      "Timeout while connecting %s [%s]:%d ", 
292                      SendMsg->mx_host,
293                      buf,
294                      SendMsg->IO.dport);
295 }
296
297 eNextState mx_connect_relay_ip(AsyncIO *IO)
298 {
299         
300         SmtpOutMsg *SendMsg = IO->Data;
301
302         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
303
304         IO->IP6 = SendMsg->pCurrRelay->af == AF_INET6;
305         
306         if (SendMsg->pCurrRelay->Port != 0)
307                 IO->dport = SendMsg->pCurrRelay->Port;
308
309         memset(&IO->Addr, 0, sizeof(struct sockaddr_in6));
310         if (IO->IP6) {
311                 memcpy(&IO->Addr.sin6_addr.s6_addr, 
312                        &SendMsg->pCurrRelay->Addr,
313                        sizeof(struct in6_addr));
314
315                 IO->Addr.sin6_family = AF_INET6;
316                 IO->Addr.sin6_port = htons(IO->dport);
317         }
318         else {
319                 struct sockaddr_in *addr = (struct sockaddr_in*) &IO->Addr;
320                 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
321                 memcpy(&addr->sin_addr,///.s_addr, 
322                        &SendMsg->pCurrRelay->Addr,
323                        sizeof(struct in_addr));
324                 
325                 addr->sin_family = AF_INET;
326                 addr->sin_port = htons(IO->dport);
327         }
328
329         SetConnectStatus(IO);
330
331         return InitEventIO(IO, SendMsg, 
332                            SMTP_C_ConnTimeout, 
333                            SMTP_C_ReadTimeouts[0],
334                             1);
335 }
336
337 void get_one_mx_host_ip_done(void *Ctx, 
338                              int status,
339                              int timeouts,
340                              struct hostent *hostent)
341 {
342         AsyncIO *IO = (AsyncIO *) Ctx;
343         SmtpOutMsg *SendMsg = IO->Data;
344         eNextState State = eAbort;
345
346         if ((status == ARES_SUCCESS) && (hostent != NULL) ) {
347                 
348                 IO->IP6  = hostent->h_addrtype == AF_INET6;
349                 IO->HEnt = hostent;
350
351                 memset(&IO->Addr, 0, sizeof(struct in6_addr));
352                 if (IO->IP6) {
353                         memcpy(&IO->Addr.sin6_addr.s6_addr, 
354                                &hostent->h_addr_list[0],
355                                sizeof(struct in6_addr));
356                         
357                         IO->Addr.sin6_family = hostent->h_addrtype;
358                         IO->Addr.sin6_port = htons(IO->dport);
359                 }
360                 else {
361                         struct sockaddr_in *addr = (struct sockaddr_in*) &IO->Addr;
362                         /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
363 //                      addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
364                         memcpy(&addr->sin_addr.s_addr, hostent->h_addr_list[0], sizeof(uint32_t));
365                         
366                         addr->sin_family = hostent->h_addrtype;
367                         addr->sin_port = htons(IO->dport);
368                         
369                 }
370                 SendMsg->IO.HEnt = hostent;
371                 SetConnectStatus(IO);
372                 State = InitEventIO(IO, SendMsg, 
373                                    SMTP_C_ConnTimeout, 
374                                    SMTP_C_ReadTimeouts[0],
375                                    1);
376         }
377         if ((State == eAbort) && (IO->sock != -1))
378                 SMTP_C_Terminate(IO);
379 }
380
381 const unsigned short DefaultMXPort = 25;
382 eNextState get_one_mx_host_ip(AsyncIO *IO)
383 {
384         SmtpOutMsg * SendMsg = IO->Data;
385         const char *Hostname;
386         //char *endpart;
387         //char buf[SIZ];
388         InitC_ares_dns(IO);
389
390         if (SendMsg->CurrMX) {
391                 SendMsg->mx_host = SendMsg->CurrMX->host;
392                 SendMsg->CurrMX = SendMsg->CurrMX->next;
393         }
394
395         if (SendMsg->pCurrRelay != NULL) {
396                 SendMsg->mx_host = Hostname = SendMsg->pCurrRelay->Host;
397                 if (SendMsg->pCurrRelay->Port != 0)
398                         SendMsg->IO.dport = SendMsg->pCurrRelay->Port;
399         }
400         else if (SendMsg->mx_host != NULL) Hostname = SendMsg->mx_host;
401         else Hostname = SendMsg->node;
402
403         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
404
405         CtdlLogPrintf(CTDL_DEBUG, 
406                       "SMTP client[%ld]: looking up %s : %d ...\n", 
407                       SendMsg->n, 
408                       Hostname, 
409                       SendMsg->IO.dport);
410
411         ares_gethostbyname(SendMsg->IO.DNSChannel,
412                            Hostname,   
413                            AF_INET6, /* it falls back to ipv4 in doubt... */
414                            get_one_mx_host_ip_done,
415                            &SendMsg->IO);
416         return IO->NextState;
417 }
418
419
420 eNextState smtp_resolve_mx_done(AsyncIO *IO)
421 {
422         SmtpOutMsg * SendMsg = IO->Data;
423
424         QueryCbDone(IO);
425
426         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
427
428         SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
429
430         SendMsg->CurrMX = SendMsg->AllMX = IO->VParsedDNSReply;
431         //// TODO: should we remove the current ares context???
432         get_one_mx_host_ip(IO);
433         return IO->NextState;
434 }
435
436
437 eNextState resolve_mx_records(AsyncIO *IO)
438 {
439         SmtpOutMsg * SendMsg = IO->Data;
440
441         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
442
443         if (!QueueQuery(ns_t_mx, 
444                         SendMsg->node, 
445                         &SendMsg->IO, 
446                         smtp_resolve_mx_done))
447         {
448                 SendMsg->MyQEntry->Status = 5;
449                 StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
450                              "No MX hosts found for <%s>", SendMsg->node);
451                 return IO->NextState;
452         }
453         return eAbort;
454 }
455
456
457 int smtp_resolve_recipients(SmtpOutMsg *SendMsg)
458 {
459         const char *ptr;
460         char buf[1024];
461         int scan_done;
462         int lp, rp;
463         int i;
464
465         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
466
467         if ((SendMsg==NULL) || 
468             (SendMsg->MyQEntry == NULL) || 
469             (StrLength(SendMsg->MyQEntry->Recipient) == 0)) {
470                 return 0;
471         }
472
473         /* Parse out the host portion of the recipient address */
474         process_rfc822_addr(ChrPtr(SendMsg->MyQEntry->Recipient), 
475                             SendMsg->user, 
476                             SendMsg->node, 
477                             SendMsg->name);
478
479         CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: Attempting delivery to <%s> @ <%s> (%s)\n",
480                       SendMsg->n, SendMsg->user, SendMsg->node, SendMsg->name);
481         /* If no envelope_from is supplied, extract one from the message */
482         if ( (SendMsg->envelope_from == NULL) || 
483              (IsEmptyStr(SendMsg->envelope_from)) ) {
484                 SendMsg->mailfrom[0] = '\0';
485                 scan_done = 0;
486                 ptr = ChrPtr(SendMsg->msgtext);
487                 do {
488                         if (ptr = cmemreadline(ptr, buf, sizeof buf), *ptr == 0) {
489                                 scan_done = 1;
490                         }
491                         if (!strncasecmp(buf, "From:", 5)) {
492                                 safestrncpy(SendMsg->mailfrom, &buf[5], sizeof SendMsg->mailfrom);
493                                 striplt(SendMsg->mailfrom);
494                                 for (i=0; SendMsg->mailfrom[i]; ++i) {
495                                         if (!isprint(SendMsg->mailfrom[i])) {
496                                                 strcpy(&SendMsg->mailfrom[i], &SendMsg->mailfrom[i+1]);
497                                                 i=0;
498                                         }
499                                 }
500         
501                                 /* Strip out parenthesized names */
502                                 lp = (-1);
503                                 rp = (-1);
504                                 for (i=0; !IsEmptyStr(SendMsg->mailfrom + i); ++i) {
505                                         if (SendMsg->mailfrom[i] == '(') lp = i;
506                                         if (SendMsg->mailfrom[i] == ')') rp = i;
507                                 }
508                                 if ((lp>0)&&(rp>lp)) {
509                                         strcpy(&SendMsg->mailfrom[lp-1], &SendMsg->mailfrom[rp+1]);
510                                 }
511         
512                                 /* Prefer brokketized names */
513                                 lp = (-1);
514                                 rp = (-1);
515                                 for (i=0; !IsEmptyStr(SendMsg->mailfrom + i); ++i) {
516                                         if (SendMsg->mailfrom[i] == '<') lp = i;
517                                         if (SendMsg->mailfrom[i] == '>') rp = i;
518                                 }
519                                 if ( (lp>=0) && (rp>lp) ) {
520                                         SendMsg->mailfrom[rp] = 0;
521                                         memmove(SendMsg->mailfrom, 
522                                                 &SendMsg->mailfrom[lp + 1], 
523                                                 rp - lp);
524                                 }
525         
526                                 scan_done = 1;
527                         }
528                 } while (scan_done == 0);
529                 if (IsEmptyStr(SendMsg->mailfrom)) strcpy(SendMsg->mailfrom, "someone@somewhere.org");
530                 stripallbut(SendMsg->mailfrom, '<', '>');
531                 SendMsg->envelope_from = SendMsg->mailfrom;
532         }
533
534         return 1;
535 }
536
537
538
539 void smtp_try(OneQueItem *MyQItem, 
540               MailQEntry *MyQEntry, 
541               StrBuf *MsgText, 
542               int KeepMsgText,  /* KeepMsgText allows us to use MsgText as ours. */
543               int MsgCount)
544 {
545         SmtpOutMsg * SendMsg;
546
547         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
548
549         SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
550         memset(SendMsg, 0, sizeof(SmtpOutMsg));
551         SendMsg->IO.sock      = (-1);
552         SendMsg->IO.NextState = eReadMessage;
553         SendMsg->n            = MsgCount++;
554         SendMsg->MyQEntry     = MyQEntry;
555         SendMsg->MyQItem      = MyQItem;
556         SendMsg->pCurrRelay   = MyQItem->URL;
557
558         SendMsg->IO.dport       = DefaultMXPort;
559         SendMsg->IO.Data        = SendMsg;
560         SendMsg->IO.SendDone    = SMTP_C_DispatchWriteDone;
561         SendMsg->IO.ReadDone    = SMTP_C_DispatchReadDone;
562         SendMsg->IO.Terminate   = SMTP_C_Terminate;
563         SendMsg->IO.LineReader  = SMTP_C_ReadServerStatus;
564         SendMsg->IO.ConnFail    = SMTP_C_ConnFail;
565         SendMsg->IO.Timeout     = SMTP_C_Timeout;
566         SendMsg->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
567         SendMsg->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
568         SendMsg->IO.IOBuf       = NewStrBuf();
569
570         if (KeepMsgText) {
571                 SendMsg->msgtext    = MsgText;
572         }
573         else {
574                 SendMsg->msgtext = NewStrBufDup(MsgText);
575         }
576
577         if (smtp_resolve_recipients(SendMsg)) {
578                 if (SendMsg->pCurrRelay == NULL)
579                         QueueEventContext(&SendMsg->IO,
580                                           resolve_mx_records);
581                 else {
582                         if (SendMsg->pCurrRelay->IsIP) {
583                                 QueueEventContext(&SendMsg->IO,
584                                                   mx_connect_relay_ip);
585                         }
586                         else {
587                                 QueueEventContext(&SendMsg->IO,
588                                                   get_one_mx_host_ip);
589                         }
590                 }
591         }
592         else {
593                 if ((SendMsg==NULL) || 
594                     (SendMsg->MyQEntry == NULL)) {
595                         SendMsg->MyQEntry->Status = 5;
596                         StrBufPlain(SendMsg->MyQEntry->StatusMessage, 
597                                     HKEY("Invalid Recipient!"));
598                 }
599                 FinalizeMessageSend(SendMsg);
600         }
601 }
602
603
604
605
606
607 /*****************************************************************************/
608 /*                     SMTP CLIENT STATE CALLBACKS                           */
609 /*****************************************************************************/
610 eNextState SMTPC_read_greeting(SmtpOutMsg *SendMsg)
611 {
612         /* Process the SMTP greeting from the server */
613         SMTP_DBG_READ();
614
615         if (!SMTP_IS_STATE('2')) {
616                 if (SMTP_IS_STATE('4')) 
617                         SMTP_VERROR(4);
618                 else 
619                         SMTP_VERROR(5);
620         }
621         return eSendReply;
622 }
623
624 eNextState SMTPC_send_EHLO(SmtpOutMsg *SendMsg)
625 {
626         /* At this point we know we are talking to a real SMTP server */
627
628         /* Do a EHLO command.  If it fails, try the HELO command. */
629         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
630                      "EHLO %s\r\n", config.c_fqdn);
631
632         SMTP_DBG_SEND();
633         return eReadMessage;
634 }
635
636 eNextState SMTPC_read_EHLO_reply(SmtpOutMsg *SendMsg)
637 {
638         SMTP_DBG_READ();
639
640         if (SMTP_IS_STATE('2')) {
641                 SendMsg->State ++;
642
643                 if ((SendMsg->pCurrRelay == NULL) || 
644                     (SendMsg->pCurrRelay->User == NULL))
645                         SendMsg->State ++; /* Skip auth... */
646         }
647         /* else we fall back to 'helo' */
648         return eSendReply;
649 }
650
651 eNextState STMPC_send_HELO(SmtpOutMsg *SendMsg)
652 {
653         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
654                      "HELO %s\r\n", config.c_fqdn);
655
656         SMTP_DBG_SEND();
657         return eReadMessage;
658 }
659
660 eNextState SMTPC_read_HELO_reply(SmtpOutMsg *SendMsg)
661 {
662         SMTP_DBG_READ();
663
664         if (!SMTP_IS_STATE('2')) {
665                 if (SMTP_IS_STATE('4'))
666                         SMTP_VERROR(4);
667                 else 
668                         SMTP_VERROR(5);
669         }
670                 if ((SendMsg->pCurrRelay == NULL) || 
671                     (SendMsg->pCurrRelay->User == NULL))
672                 SendMsg->State ++; /* Skip auth... */
673         return eSendReply;
674 }
675
676 eNextState SMTPC_send_auth(SmtpOutMsg *SendMsg)
677 {
678         char buf[SIZ];
679         char encoded[1024];
680
681         if ((SendMsg->pCurrRelay == NULL) || 
682             (SendMsg->pCurrRelay->User == NULL))
683                 SendMsg->State ++; /* Skip auth, shouldn't even come here!... */
684         else {
685         /* Do an AUTH command if necessary */
686         sprintf(buf, "%s%c%s%c%s", 
687                 SendMsg->pCurrRelay->User, '\0', 
688                 SendMsg->pCurrRelay->User, '\0', 
689                 SendMsg->pCurrRelay->Pass);
690         CtdlEncodeBase64(encoded, buf, 
691                          strlen(SendMsg->pCurrRelay->User) * 2 +
692                          strlen(SendMsg->pCurrRelay->Pass) + 2, 0);
693         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
694                      "AUTH PLAIN %s\r\n", encoded);
695         }
696         SMTP_DBG_SEND();
697         return eReadMessage;
698 }
699
700 eNextState SMTPC_read_auth_reply(SmtpOutMsg *SendMsg)
701 {
702         /* Do an AUTH command if necessary */
703         
704         SMTP_DBG_READ();
705         
706         if (!SMTP_IS_STATE('2')) {
707                 if (SMTP_IS_STATE('4'))
708                         SMTP_VERROR(4);
709                 else 
710                         SMTP_VERROR(5);
711         }
712         return eSendReply;
713 }
714
715 eNextState SMTPC_send_FROM(SmtpOutMsg *SendMsg)
716 {
717         /* previous command succeeded, now try the MAIL FROM: command */
718         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
719                      "MAIL FROM:<%s>\r\n", 
720                      SendMsg->envelope_from);
721
722         SMTP_DBG_SEND();
723         return eReadMessage;
724 }
725
726 eNextState SMTPC_read_FROM_reply(SmtpOutMsg *SendMsg)
727 {
728         SMTP_DBG_READ();
729
730         if (!SMTP_IS_STATE('2')) {
731                 if (SMTP_IS_STATE('4'))
732                         SMTP_VERROR(4);
733                 else 
734                         SMTP_VERROR(5);
735         }
736         return eSendReply;
737 }
738
739
740 eNextState SMTPC_send_RCPT(SmtpOutMsg *SendMsg)
741 {
742         /* MAIL succeeded, now try the RCPT To: command */
743         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
744                      "RCPT TO:<%s@%s>\r\n", 
745                      SendMsg->user, 
746                      SendMsg->node);
747
748         SMTP_DBG_SEND();
749         return eReadMessage;
750 }
751
752 eNextState SMTPC_read_RCPT_reply(SmtpOutMsg *SendMsg)
753 {
754         SMTP_DBG_READ();
755
756         if (!SMTP_IS_STATE('2')) {
757                 if (SMTP_IS_STATE('4')) 
758                         SMTP_VERROR(4);
759                 else 
760                         SMTP_VERROR(5);
761         }
762         return eSendReply;
763 }
764
765 eNextState SMTPC_send_DATAcmd(SmtpOutMsg *SendMsg)
766 {
767         /* RCPT succeeded, now try the DATA command */
768         StrBufPlain(SendMsg->IO.SendBuf.Buf,
769                     HKEY("DATA\r\n"));
770
771         SMTP_DBG_SEND();
772         return eReadMessage;
773 }
774
775 eNextState SMTPC_read_DATAcmd_reply(SmtpOutMsg *SendMsg)
776 {
777         SMTP_DBG_READ();
778
779         if (!SMTP_IS_STATE('3')) {
780                 if (SMTP_IS_STATE('4')) 
781                         SMTP_VERROR(3);
782                 else 
783                         SMTP_VERROR(5);
784         }
785         return eSendReply;
786 }
787
788 eNextState SMTPC_send_data_body(SmtpOutMsg *SendMsg)
789 {
790         StrBuf *Buf;
791         /* If we reach this point, the server is expecting data.*/
792
793         Buf = SendMsg->IO.SendBuf.Buf;
794         SendMsg->IO.SendBuf.Buf = SendMsg->msgtext;
795         SendMsg->msgtext = Buf;
796         SendMsg->State ++;
797
798         return eSendMore;
799 }
800
801 eNextState SMTPC_send_terminate_data_body(SmtpOutMsg *SendMsg)
802 {
803         StrBuf *Buf;
804
805         Buf = SendMsg->IO.SendBuf.Buf;
806         SendMsg->IO.SendBuf.Buf = SendMsg->msgtext;
807         SendMsg->msgtext = Buf;
808
809         StrBufPlain(SendMsg->IO.SendBuf.Buf,
810                     HKEY(".\r\n"));
811
812         return eReadMessage;
813
814 }
815
816 eNextState SMTPC_read_data_body_reply(SmtpOutMsg *SendMsg)
817 {
818         SMTP_DBG_READ();
819
820         if (!SMTP_IS_STATE('2')) {
821                 if (SMTP_IS_STATE('4'))
822                         SMTP_VERROR(4);
823                 else 
824                         SMTP_VERROR(5);
825         }
826
827         /* We did it! */
828         StrBufPlain(SendMsg->MyQEntry->StatusMessage, 
829                     &ChrPtr(SendMsg->IO.RecvBuf.Buf)[4],
830                     StrLength(SendMsg->IO.RecvBuf.Buf) - 4);
831         SendMsg->MyQEntry->Status = 2;
832         return eSendReply;
833 }
834
835 eNextState SMTPC_send_QUIT(SmtpOutMsg *SendMsg)
836 {
837         StrBufPlain(SendMsg->IO.SendBuf.Buf,
838                     HKEY("QUIT\r\n"));
839
840         SMTP_DBG_SEND();
841         return eReadMessage;
842 }
843
844 eNextState SMTPC_read_QUIT_reply(SmtpOutMsg *SendMsg)
845 {
846         SMTP_DBG_READ();
847
848         CtdlLogPrintf(CTDL_INFO, "SMTP client[%ld]: delivery to <%s> @ <%s> (%s) succeeded\n",
849                       SendMsg->n, SendMsg->user, SendMsg->node, SendMsg->name);
850         return eTerminateConnection;
851 }
852
853 eNextState SMTPC_read_dummy(SmtpOutMsg *SendMsg)
854 {
855         return eSendReply;
856 }
857
858 eNextState SMTPC_send_dummy(SmtpOutMsg *SendMsg)
859 {
860         return eReadMessage;
861 }
862
863
864 /*****************************************************************************/
865 /*                     SMTP CLIENT DISPATCHER                                */
866 /*****************************************************************************/
867 SMTPReadHandler ReadHandlers[eMaxSMTPC] = {
868         SMTPC_read_greeting,
869         SMTPC_read_EHLO_reply,
870         SMTPC_read_HELO_reply,
871         SMTPC_read_auth_reply,
872         SMTPC_read_FROM_reply,
873         SMTPC_read_RCPT_reply,
874         SMTPC_read_DATAcmd_reply,
875         SMTPC_read_dummy,
876         SMTPC_read_data_body_reply,
877         SMTPC_read_QUIT_reply
878 };
879 SMTPSendHandler SendHandlers[eMaxSMTPC] = {
880         SMTPC_send_dummy, /* we don't send a greeting, the server does... */
881         SMTPC_send_EHLO,
882         STMPC_send_HELO,
883         SMTPC_send_auth,
884         SMTPC_send_FROM,
885         SMTPC_send_RCPT,
886         SMTPC_send_DATAcmd,
887         SMTPC_send_data_body,
888         SMTPC_send_terminate_data_body,
889         SMTPC_send_QUIT
890 };
891
892 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
893 {
894         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
895         double Timeout;
896         switch (NextTCPState) {
897         case eSendReply:
898         case eSendMore:
899                 Timeout = SMTP_C_SendTimeouts[pMsg->State];
900                 if (pMsg->State == eDATABody) {
901                         /* if we're sending a huge message, we need more time. */
902                         Timeout += StrLength(pMsg->msgtext) / 1024;
903                 }
904                 break;
905         case eReadMessage:
906                 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
907                 if (pMsg->State == eDATATerminateBody) {
908                         /* 
909                          * some mailservers take a nap before accepting the message
910                          * content inspection and such.
911                          */
912                         Timeout += StrLength(pMsg->msgtext) / 1024;
913                 }
914                 break;
915         case eTerminateConnection:
916         case eAbort:
917                 return;
918         }
919         SetNextTimeout(&pMsg->IO, Timeout);
920 }
921 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
922 {
923         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
924         SmtpOutMsg *pMsg = IO->Data;
925         eNextState rc;
926
927         rc = ReadHandlers[pMsg->State](pMsg);
928         pMsg->State++;
929         SMTPSetTimeout(rc, pMsg);
930         return rc;
931 }
932 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
933 {
934         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
935         SmtpOutMsg *pMsg = IO->Data;
936         eNextState rc;
937
938         rc = SendHandlers[pMsg->State](pMsg);
939         SMTPSetTimeout(rc, pMsg);
940         return rc;
941 }
942
943
944 /*****************************************************************************/
945 /*                     SMTP CLIENT ERROR CATCHERS                            */
946 /*****************************************************************************/
947 eNextState SMTP_C_Terminate(AsyncIO *IO)
948 {
949         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
950         SmtpOutMsg *pMsg = IO->Data;
951         FinalizeMessageSend(pMsg);
952         return eAbort;
953 }
954 eNextState SMTP_C_Timeout(AsyncIO *IO)
955 {
956         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
957         SmtpOutMsg *pMsg = IO->Data;
958         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
959         FinalizeMessageSend(pMsg);
960         return eAbort;
961 }
962 eNextState SMTP_C_ConnFail(AsyncIO *IO)
963 {
964         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
965         SmtpOutMsg *pMsg = IO->Data;
966         FinalizeMessageSend(pMsg);
967         return eAbort;
968 }
969
970
971 /**
972  * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
973  */
974 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
975 {
976         eReadState Finished = eBufferNotEmpty; 
977
978         while (Finished == eBufferNotEmpty) {
979                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
980                 
981                 switch (Finished) {
982                 case eMustReadMore: /// read new from socket... 
983                         return Finished;
984                         break;
985                 case eBufferNotEmpty: /* shouldn't happen... */
986                 case eReadSuccess: /// done for now...
987                         if (StrLength(IO->IOBuf) < 4)
988                                 continue;
989                         if (ChrPtr(IO->IOBuf)[3] == '-')
990                                 Finished = eBufferNotEmpty;
991                         else 
992                                 return Finished;
993                         break;
994                 case eReadFail: /// WHUT?
995                         ///todo: shut down! 
996                         break;
997                 }
998         }
999         return Finished;
1000 }
1001
1002 #endif
1003 CTDL_MODULE_INIT(smtp_eventclient)
1004 {
1005         return "smtpeventclient";
1006 }