libev migration; relaying implementation
[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                 unsigned long psaddr;
272                 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->Addr;
273
274                 src = &addr->sin_addr.s_addr;
275                 memcpy(&psaddr, &addr->sin_addr.s_addr, sizeof(psaddr));
276 ///             psaddr = ntohl(psaddr); 
277 /*
278                 CtdlLogPrintf(CTDL_DEBUG, 
279                               "SMTP client[%ld]: connecting to %s [%ld.%ld.%ld.%ld:%d] ...\n", 
280                               SendMsg->n, 
281                               SendMsg->mx_host, 
282                               (psaddr >> 24) & 0xFF,
283                               (psaddr >> 16) & 0xFF,
284                               (psaddr >>  8) & 0xFF,
285                               (psaddr >>  0) & 0xFF,
286                               SendMsg->IO.dport);
287
288                 SendMsg->MyQEntry->Status = 5; 
289                 StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
290                              "Timeout while connecting %s [%ld.%ld.%ld.%ld:%d] ", 
291                              SendMsg->mx_host,
292                              (psaddr >> 24) & 0xFF,
293                              (psaddr >> 16) & 0xFF,
294                              (psaddr >>  8) & 0xFF,
295                              (psaddr >>  0) & 0xFF,
296                              SendMsg->IO.dport);
297
298 */
299         }
300
301         inet_ntop((IO->IP6)?AF_INET6:AF_INET,
302                   src,
303                   buf, sizeof(buf));
304
305         CtdlLogPrintf(CTDL_DEBUG, 
306                       "SMTP client[%ld]: connecting to %s [%s]:%d ...\n", 
307                       SendMsg->n, 
308                       SendMsg->mx_host, 
309                       buf,
310                       SendMsg->IO.dport);
311
312         SendMsg->MyQEntry->Status = 5; 
313         StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
314                      "Timeout while connecting %s [%s]:%d ", 
315                      SendMsg->mx_host,
316                      buf,
317                      SendMsg->IO.dport);
318 }
319
320 eNextState mx_connect_relay_ip(AsyncIO *IO)
321 {
322         
323         SmtpOutMsg *SendMsg = IO->Data;
324
325         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
326
327         IO->IP6 = SendMsg->pCurrRelay->af == AF_INET6;
328         
329         if (SendMsg->pCurrRelay->Port != 0)
330                 IO->dport = SendMsg->pCurrRelay->Port;
331
332         memset(&IO->Addr, 0, sizeof(struct in6_addr));
333         if (IO->IP6) {
334                 memcpy(&IO->Addr.sin6_addr.s6_addr, 
335                        &SendMsg->pCurrRelay->Addr,
336                        sizeof(struct in6_addr));
337                 
338                 IO->Addr.sin6_family = AF_INET6;
339                 IO->Addr.sin6_port = htons(IO->dport);
340         }
341         else {
342                 struct sockaddr_in *addr = (struct sockaddr_in*) &IO->Addr;
343                 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
344                 memcpy(&addr->sin_addr,///.s_addr, 
345                        &SendMsg->pCurrRelay->Addr,
346                        sizeof(struct in_addr));
347                 
348                 addr->sin_family = AF_INET;
349                 addr->sin_port = htons(IO->dport);
350         }
351
352         SetConnectStatus(IO);
353
354         return InitEventIO(IO, SendMsg, 
355                            SMTP_C_ConnTimeout, 
356                            SMTP_C_ReadTimeouts[0],
357                             1);
358 }
359
360 void get_one_mx_host_ip_done(void *Ctx, 
361                              int status,
362                              int timeouts,
363                              struct hostent *hostent)
364 {
365         AsyncIO *IO = (AsyncIO *) Ctx;
366         SmtpOutMsg *SendMsg = IO->Data;
367         eNextState State = eAbort;
368
369         if ((status == ARES_SUCCESS) && (hostent != NULL) ) {
370                 
371                 IO->IP6  = hostent->h_addrtype == AF_INET6;
372                 IO->HEnt = hostent;
373
374                 memset(&IO->Addr, 0, sizeof(struct in6_addr));
375                 if (IO->IP6) {
376                         memcpy(&IO->Addr.sin6_addr.s6_addr, 
377                                &hostent->h_addr_list[0],
378                                sizeof(struct in6_addr));
379                         
380                         IO->Addr.sin6_family = hostent->h_addrtype;
381                         IO->Addr.sin6_port = htons(IO->dport);
382                 }
383                 else {
384                         struct sockaddr_in *addr = (struct sockaddr_in*) &IO->Addr;
385                         /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
386 //                      addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
387                         memcpy(&addr->sin_addr.s_addr, hostent->h_addr_list[0], sizeof(uint32_t));
388                         
389                         addr->sin_family = hostent->h_addrtype;
390                         addr->sin_port = htons(IO->dport);
391                         
392                 }
393                 SendMsg->IO.HEnt = hostent;
394                 SetConnectStatus(IO);
395                 State = InitEventIO(IO, SendMsg, 
396                                    SMTP_C_ConnTimeout, 
397                                    SMTP_C_ReadTimeouts[0],
398                                    1);
399         }
400         if (State == eAbort)
401                 SMTP_C_Terminate(IO);
402 }
403
404 const unsigned short DefaultMXPort = 25;
405 eNextState get_one_mx_host_ip(AsyncIO *IO)
406 {
407         SmtpOutMsg * SendMsg = IO->Data;
408         const char *Hostname;
409         //char *endpart;
410         //char buf[SIZ];
411         InitC_ares_dns(IO);
412
413         if (SendMsg->CurrMX) {
414                 SendMsg->mx_host = SendMsg->CurrMX->host;
415                 SendMsg->CurrMX = SendMsg->CurrMX->next;
416         }
417
418         if (SendMsg->pCurrRelay != NULL) Hostname = SendMsg->pCurrRelay->Host;
419         else if (SendMsg->mx_host != NULL) Hostname = SendMsg->mx_host;
420         else Hostname = SendMsg->node;
421
422         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
423
424         CtdlLogPrintf(CTDL_DEBUG, 
425                       "SMTP client[%ld]: looking up %s : %d ...\n", 
426                       SendMsg->n, 
427                       Hostname, 
428                       SendMsg->IO.dport);
429
430         ares_gethostbyname(SendMsg->IO.DNSChannel,
431                            Hostname,   
432                            AF_INET6, /* it falls back to ipv4 in doubt... */
433                            get_one_mx_host_ip_done,
434                            &SendMsg->IO);
435         return IO->NextState;
436 }
437
438
439 eNextState smtp_resolve_mx_done(AsyncIO *IO)
440 {
441         SmtpOutMsg * SendMsg = IO->Data;
442
443         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
444
445         SendMsg->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
446         SendMsg->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
447         SendMsg->IO.IOBuf = NewStrBuf();
448         SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
449
450         SendMsg->CurrMX = SendMsg->AllMX = IO->VParsedDNSReply;
451         //// TODO: should we remove the current ares context???
452         get_one_mx_host_ip(IO);
453         return IO->NextState;
454 }
455
456
457 eNextState resolve_mx_records(AsyncIO *IO)
458 {
459         SmtpOutMsg * SendMsg = IO->Data;
460
461         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
462
463         if (!QueueQuery(ns_t_mx, 
464                         SendMsg->node, 
465                         &SendMsg->IO, 
466                         smtp_resolve_mx_done))
467         {
468                 SendMsg->MyQEntry->Status = 5;
469                 StrBufPrintf(SendMsg->MyQEntry->StatusMessage, 
470                              "No MX hosts found for <%s>", SendMsg->node);
471                 return IO->NextState;
472         }
473         return eAbort;
474 }
475
476
477 int smtp_resolve_recipients(SmtpOutMsg *SendMsg)
478 {
479         const char *ptr;
480         char buf[1024];
481         int scan_done;
482         int lp, rp;
483         int i;
484
485         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
486
487         if ((SendMsg==NULL) || 
488             (SendMsg->MyQEntry == NULL) || 
489             (StrLength(SendMsg->MyQEntry->Recipient) == 0)) {
490                 return 0;
491         }
492
493         /* Parse out the host portion of the recipient address */
494         process_rfc822_addr(ChrPtr(SendMsg->MyQEntry->Recipient), 
495                             SendMsg->user, 
496                             SendMsg->node, 
497                             SendMsg->name);
498
499         CtdlLogPrintf(CTDL_DEBUG, "SMTP client[%ld]: Attempting delivery to <%s> @ <%s> (%s)\n",
500                       SendMsg->n, SendMsg->user, SendMsg->node, SendMsg->name);
501         /* If no envelope_from is supplied, extract one from the message */
502         if ( (SendMsg->envelope_from == NULL) || 
503              (IsEmptyStr(SendMsg->envelope_from)) ) {
504                 SendMsg->mailfrom[0] = '\0';
505                 scan_done = 0;
506                 ptr = ChrPtr(SendMsg->msgtext);
507                 do {
508                         if (ptr = cmemreadline(ptr, buf, sizeof buf), *ptr == 0) {
509                                 scan_done = 1;
510                         }
511                         if (!strncasecmp(buf, "From:", 5)) {
512                                 safestrncpy(SendMsg->mailfrom, &buf[5], sizeof SendMsg->mailfrom);
513                                 striplt(SendMsg->mailfrom);
514                                 for (i=0; SendMsg->mailfrom[i]; ++i) {
515                                         if (!isprint(SendMsg->mailfrom[i])) {
516                                                 strcpy(&SendMsg->mailfrom[i], &SendMsg->mailfrom[i+1]);
517                                                 i=0;
518                                         }
519                                 }
520         
521                                 /* Strip out parenthesized names */
522                                 lp = (-1);
523                                 rp = (-1);
524                                 for (i=0; !IsEmptyStr(SendMsg->mailfrom + i); ++i) {
525                                         if (SendMsg->mailfrom[i] == '(') lp = i;
526                                         if (SendMsg->mailfrom[i] == ')') rp = i;
527                                 }
528                                 if ((lp>0)&&(rp>lp)) {
529                                         strcpy(&SendMsg->mailfrom[lp-1], &SendMsg->mailfrom[rp+1]);
530                                 }
531         
532                                 /* Prefer brokketized names */
533                                 lp = (-1);
534                                 rp = (-1);
535                                 for (i=0; !IsEmptyStr(SendMsg->mailfrom + i); ++i) {
536                                         if (SendMsg->mailfrom[i] == '<') lp = i;
537                                         if (SendMsg->mailfrom[i] == '>') rp = i;
538                                 }
539                                 if ( (lp>=0) && (rp>lp) ) {
540                                         SendMsg->mailfrom[rp] = 0;
541                                         memmove(SendMsg->mailfrom, 
542                                                 &SendMsg->mailfrom[lp + 1], 
543                                                 rp - lp);
544                                 }
545         
546                                 scan_done = 1;
547                         }
548                 } while (scan_done == 0);
549                 if (IsEmptyStr(SendMsg->mailfrom)) strcpy(SendMsg->mailfrom, "someone@somewhere.org");
550                 stripallbut(SendMsg->mailfrom, '<', '>');
551                 SendMsg->envelope_from = SendMsg->mailfrom;
552         }
553
554         return 1;
555 }
556
557
558
559 void smtp_try(OneQueItem *MyQItem, 
560               MailQEntry *MyQEntry, 
561               StrBuf *MsgText, 
562               int KeepMsgText,  /* KeepMsgText allows us to use MsgText as ours. */
563               int MsgCount)
564 {
565         SmtpOutMsg * SendMsg;
566
567         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
568
569         SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
570         memset(SendMsg, 0, sizeof(SmtpOutMsg));
571         SendMsg->IO.sock      = (-1);
572         SendMsg->IO.NextState = eReadMessage;
573         SendMsg->n            = MsgCount++;
574         SendMsg->MyQEntry     = MyQEntry;
575         SendMsg->MyQItem      = MyQItem;
576         SendMsg->pCurrRelay   = MyQItem->URL;
577
578         SendMsg->IO.dport       = DefaultMXPort;
579         SendMsg->IO.Data        = SendMsg;
580         SendMsg->IO.SendDone    = SMTP_C_DispatchWriteDone;
581         SendMsg->IO.ReadDone    = SMTP_C_DispatchReadDone;
582         SendMsg->IO.Terminate   = SMTP_C_Terminate;
583         SendMsg->IO.LineReader  = SMTP_C_ReadServerStatus;
584         SendMsg->IO.ConnFail    = SMTP_C_ConnFail;
585         SendMsg->IO.Timeout     = SMTP_C_Timeout;
586
587         if (KeepMsgText) {
588                 SendMsg->msgtext    = MsgText;
589         }
590         else {
591                 SendMsg->msgtext = NewStrBufDup(MsgText);
592         }
593
594         if (smtp_resolve_recipients(SendMsg)) {
595                 if (SendMsg->pCurrRelay == NULL)
596                         QueueEventContext(&SendMsg->IO,
597                                           resolve_mx_records);
598                 else {
599                         if (SendMsg->pCurrRelay->IsIP) {
600                                 QueueEventContext(&SendMsg->IO,
601                                                   mx_connect_relay_ip);
602                         }
603                         else {
604                                 QueueEventContext(&SendMsg->IO,
605                                                   get_one_mx_host_ip);
606                         }
607                 }
608         }
609         else {
610                 if ((SendMsg==NULL) || 
611                     (SendMsg->MyQEntry == NULL)) {
612                         SendMsg->MyQEntry->Status = 5;
613                         StrBufPlain(SendMsg->MyQEntry->StatusMessage, 
614                                     HKEY("Invalid Recipient!"));
615                 }
616                 FinalizeMessageSend(SendMsg);
617         }
618 }
619
620
621
622
623
624 /*****************************************************************************/
625 /*                     SMTP CLIENT STATE CALLBACKS                           */
626 /*****************************************************************************/
627 eNextState SMTPC_read_greeting(SmtpOutMsg *SendMsg)
628 {
629         /* Process the SMTP greeting from the server */
630         SMTP_DBG_READ();
631
632         if (!SMTP_IS_STATE('2')) {
633                 if (SMTP_IS_STATE('4')) 
634                         SMTP_VERROR(4);
635                 else 
636                         SMTP_VERROR(5);
637         }
638         return eSendReply;
639 }
640
641 eNextState SMTPC_send_EHLO(SmtpOutMsg *SendMsg)
642 {
643         /* At this point we know we are talking to a real SMTP server */
644
645         /* Do a EHLO command.  If it fails, try the HELO command. */
646         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
647                      "EHLO %s\r\n", config.c_fqdn);
648
649         SMTP_DBG_SEND();
650         return eReadMessage;
651 }
652
653 eNextState SMTPC_read_EHLO_reply(SmtpOutMsg *SendMsg)
654 {
655         SMTP_DBG_READ();
656
657         if (SMTP_IS_STATE('2')) {
658                 SendMsg->State ++;
659
660                 if ((SendMsg->pCurrRelay == NULL) || 
661                     (SendMsg->pCurrRelay->User == NULL))
662                         SendMsg->State ++; /* Skip auth... */
663         }
664         /* else we fall back to 'helo' */
665         return eSendReply;
666 }
667
668 eNextState STMPC_send_HELO(SmtpOutMsg *SendMsg)
669 {
670         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
671                      "HELO %s\r\n", config.c_fqdn);
672
673         SMTP_DBG_SEND();
674         return eReadMessage;
675 }
676
677 eNextState SMTPC_read_HELO_reply(SmtpOutMsg *SendMsg)
678 {
679         SMTP_DBG_READ();
680
681         if (!SMTP_IS_STATE('2')) {
682                 if (SMTP_IS_STATE('4'))
683                         SMTP_VERROR(4);
684                 else 
685                         SMTP_VERROR(5);
686         }
687                 if ((SendMsg->pCurrRelay == NULL) || 
688                     (SendMsg->pCurrRelay->User == NULL))
689                 SendMsg->State ++; /* Skip auth... */
690         return eSendReply;
691 }
692
693 eNextState SMTPC_send_auth(SmtpOutMsg *SendMsg)
694 {
695         char buf[SIZ];
696         char encoded[1024];
697
698         if ((SendMsg->pCurrRelay == NULL) || 
699             (SendMsg->pCurrRelay->User == NULL))
700                 SendMsg->State ++; /* Skip auth, shouldn't even come here!... */
701         else {
702         /* Do an AUTH command if necessary */
703         sprintf(buf, "%s%c%s%c%s", 
704                 SendMsg->pCurrRelay->User, '\0', 
705                 SendMsg->pCurrRelay->User, '\0', 
706                 SendMsg->pCurrRelay->Pass);
707         CtdlEncodeBase64(encoded, buf, 
708                          strlen(SendMsg->pCurrRelay->User) * 2 +
709                          strlen(SendMsg->pCurrRelay->Pass) + 2, 0);
710         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
711                      "AUTH PLAIN %s\r\n", encoded);
712         }
713         SMTP_DBG_SEND();
714         return eReadMessage;
715 }
716
717 eNextState SMTPC_read_auth_reply(SmtpOutMsg *SendMsg)
718 {
719         /* Do an AUTH command if necessary */
720         
721         SMTP_DBG_READ();
722         
723         if (!SMTP_IS_STATE('2')) {
724                 if (SMTP_IS_STATE('4'))
725                         SMTP_VERROR(4);
726                 else 
727                         SMTP_VERROR(5);
728         }
729         return eSendReply;
730 }
731
732 eNextState SMTPC_send_FROM(SmtpOutMsg *SendMsg)
733 {
734         /* previous command succeeded, now try the MAIL FROM: command */
735         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
736                      "MAIL FROM:<%s>\r\n", 
737                      SendMsg->envelope_from);
738
739         SMTP_DBG_SEND();
740         return eReadMessage;
741 }
742
743 eNextState SMTPC_read_FROM_reply(SmtpOutMsg *SendMsg)
744 {
745         SMTP_DBG_READ();
746
747         if (!SMTP_IS_STATE('2')) {
748                 if (SMTP_IS_STATE('4'))
749                         SMTP_VERROR(4);
750                 else 
751                         SMTP_VERROR(5);
752         }
753         return eSendReply;
754 }
755
756
757 eNextState SMTPC_send_RCPT(SmtpOutMsg *SendMsg)
758 {
759         /* MAIL succeeded, now try the RCPT To: command */
760         StrBufPrintf(SendMsg->IO.SendBuf.Buf,
761                      "RCPT TO:<%s@%s>\r\n", 
762                      SendMsg->user, 
763                      SendMsg->node);
764
765         SMTP_DBG_SEND();
766         return eReadMessage;
767 }
768
769 eNextState SMTPC_read_RCPT_reply(SmtpOutMsg *SendMsg)
770 {
771         SMTP_DBG_READ();
772
773         if (!SMTP_IS_STATE('2')) {
774                 if (SMTP_IS_STATE('4')) 
775                         SMTP_VERROR(4);
776                 else 
777                         SMTP_VERROR(5);
778         }
779         return eSendReply;
780 }
781
782 eNextState SMTPC_send_DATAcmd(SmtpOutMsg *SendMsg)
783 {
784         /* RCPT succeeded, now try the DATA command */
785         StrBufPlain(SendMsg->IO.SendBuf.Buf,
786                     HKEY("DATA\r\n"));
787
788         SMTP_DBG_SEND();
789         return eReadMessage;
790 }
791
792 eNextState SMTPC_read_DATAcmd_reply(SmtpOutMsg *SendMsg)
793 {
794         SMTP_DBG_READ();
795
796         if (!SMTP_IS_STATE('3')) {
797                 if (SMTP_IS_STATE('4')) 
798                         SMTP_VERROR(3);
799                 else 
800                         SMTP_VERROR(5);
801         }
802         return eSendReply;
803 }
804
805 eNextState SMTPC_send_data_body(SmtpOutMsg *SendMsg)
806 {
807         StrBuf *Buf;
808         /* If we reach this point, the server is expecting data.*/
809
810         Buf = SendMsg->IO.SendBuf.Buf;
811         SendMsg->IO.SendBuf.Buf = SendMsg->msgtext;
812         SendMsg->msgtext = Buf;
813         SendMsg->State ++;
814
815         return eSendMore;
816 }
817
818 eNextState SMTPC_send_terminate_data_body(SmtpOutMsg *SendMsg)
819 {
820         StrBuf *Buf;
821
822         Buf = SendMsg->IO.SendBuf.Buf;
823         SendMsg->IO.SendBuf.Buf = SendMsg->msgtext;
824         SendMsg->msgtext = Buf;
825
826         StrBufPlain(SendMsg->IO.SendBuf.Buf,
827                     HKEY(".\r\n"));
828
829         return eReadMessage;
830
831 }
832
833 eNextState SMTPC_read_data_body_reply(SmtpOutMsg *SendMsg)
834 {
835         SMTP_DBG_READ();
836
837         if (!SMTP_IS_STATE('2')) {
838                 if (SMTP_IS_STATE('4'))
839                         SMTP_VERROR(4);
840                 else 
841                         SMTP_VERROR(5);
842         }
843
844         /* We did it! */
845         StrBufPlain(SendMsg->MyQEntry->StatusMessage, 
846                     &ChrPtr(SendMsg->IO.RecvBuf.Buf)[4],
847                     StrLength(SendMsg->IO.RecvBuf.Buf) - 4);
848         SendMsg->MyQEntry->Status = 2;
849         return eSendReply;
850 }
851
852 eNextState SMTPC_send_QUIT(SmtpOutMsg *SendMsg)
853 {
854         StrBufPlain(SendMsg->IO.SendBuf.Buf,
855                     HKEY("QUIT\r\n"));
856
857         SMTP_DBG_SEND();
858         return eReadMessage;
859 }
860
861 eNextState SMTPC_read_QUIT_reply(SmtpOutMsg *SendMsg)
862 {
863         SMTP_DBG_READ();
864
865         CtdlLogPrintf(CTDL_INFO, "SMTP client[%ld]: delivery to <%s> @ <%s> (%s) succeeded\n",
866                       SendMsg->n, SendMsg->user, SendMsg->node, SendMsg->name);
867         return eTerminateConnection;
868 }
869
870 eNextState SMTPC_read_dummy(SmtpOutMsg *SendMsg)
871 {
872         return eSendReply;
873 }
874
875 eNextState SMTPC_send_dummy(SmtpOutMsg *SendMsg)
876 {
877         return eReadMessage;
878 }
879
880
881 /*****************************************************************************/
882 /*                     SMTP CLIENT DISPATCHER                                */
883 /*****************************************************************************/
884 SMTPReadHandler ReadHandlers[eMaxSMTPC] = {
885         SMTPC_read_greeting,
886         SMTPC_read_EHLO_reply,
887         SMTPC_read_HELO_reply,
888         SMTPC_read_auth_reply,
889         SMTPC_read_FROM_reply,
890         SMTPC_read_RCPT_reply,
891         SMTPC_read_DATAcmd_reply,
892         SMTPC_read_dummy,
893         SMTPC_read_data_body_reply,
894         SMTPC_read_QUIT_reply
895 };
896 SMTPSendHandler SendHandlers[eMaxSMTPC] = {
897         SMTPC_send_dummy, /* we don't send a greeting, the server does... */
898         SMTPC_send_EHLO,
899         STMPC_send_HELO,
900         SMTPC_send_auth,
901         SMTPC_send_FROM,
902         SMTPC_send_RCPT,
903         SMTPC_send_DATAcmd,
904         SMTPC_send_data_body,
905         SMTPC_send_terminate_data_body,
906         SMTPC_send_QUIT
907 };
908
909 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
910 {
911         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
912         double Timeout;
913         switch (NextTCPState) {
914         case eSendReply:
915         case eSendMore:
916                 Timeout = SMTP_C_SendTimeouts[pMsg->State];
917                 if (pMsg->State == eDATABody) {
918                         /* if we're sending a huge message, we need more time. */
919                         Timeout += StrLength(pMsg->msgtext) / 1024;
920                 }
921                 break;
922         case eReadMessage:
923                 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
924                 if (pMsg->State == eDATATerminateBody) {
925                         /* 
926                          * some mailservers take a nap before accepting the message
927                          * content inspection and such.
928                          */
929                         Timeout += StrLength(pMsg->msgtext) / 1024;
930                 }
931                 break;
932         case eTerminateConnection:
933         case eAbort:
934                 return;
935         }
936         SetNextTimeout(&pMsg->IO, Timeout);
937 }
938 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
939 {
940         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
941         SmtpOutMsg *pMsg = IO->Data;
942         eNextState rc;
943
944         rc = ReadHandlers[pMsg->State](pMsg);
945         pMsg->State++;
946         SMTPSetTimeout(rc, pMsg);
947         return rc;
948 }
949 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
950 {
951         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
952         SmtpOutMsg *pMsg = IO->Data;
953         eNextState rc;
954
955         rc = SendHandlers[pMsg->State](pMsg);
956         SMTPSetTimeout(rc, pMsg);
957         return rc;
958 }
959
960
961 /*****************************************************************************/
962 /*                     SMTP CLIENT ERROR CATCHERS                            */
963 /*****************************************************************************/
964 eNextState SMTP_C_Terminate(AsyncIO *IO)
965 {
966         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
967         SmtpOutMsg *pMsg = IO->Data;
968         FinalizeMessageSend(pMsg);
969         return eAbort;
970 }
971 eNextState SMTP_C_Timeout(AsyncIO *IO)
972 {
973         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
974         SmtpOutMsg *pMsg = IO->Data;
975         StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
976         FinalizeMessageSend(pMsg);
977         return eAbort;
978 }
979 eNextState SMTP_C_ConnFail(AsyncIO *IO)
980 {
981         CtdlLogPrintf(CTDL_DEBUG, "SMTP: %s\n", __FUNCTION__);
982         SmtpOutMsg *pMsg = IO->Data;
983         FinalizeMessageSend(pMsg);
984         return eAbort;
985 }
986
987
988 /**
989  * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
990  */
991 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
992 {
993         eReadState Finished = eBufferNotEmpty; 
994
995         while (Finished == eBufferNotEmpty) {
996                 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
997                 
998                 switch (Finished) {
999                 case eMustReadMore: /// read new from socket... 
1000                         return Finished;
1001                         break;
1002                 case eBufferNotEmpty: /* shouldn't happen... */
1003                 case eReadSuccess: /// done for now...
1004                         if (StrLength(IO->IOBuf) < 4)
1005                                 continue;
1006                         if (ChrPtr(IO->IOBuf)[3] == '-')
1007                                 Finished = eBufferNotEmpty;
1008                         else 
1009                                 return Finished;
1010                         break;
1011                 case eReadFail: /// WHUT?
1012                         ///todo: shut down! 
1013                         break;
1014                 }
1015         }
1016         return Finished;
1017 }
1018
1019 #endif
1020 CTDL_MODULE_INIT(smtp_eventclient)
1021 {
1022         return "smtpeventclient";
1023 }