2 * This module is an SMTP and ESMTP implementation for the Citadel system.
3 * It is compliant with all of the following:
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
20 * The VRFY and EXPN commands have been removed from this implementation
21 * because nobody uses these commands anymore, except for spammers.
23 * Copyright (c) 1998-2012 by the citadel.org team
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.
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.
49 #include <sys/types.h>
52 #if TIME_WITH_SYS_TIME
53 # include <sys/time.h>
57 # include <sys/time.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
68 #include <arpa/inet.h>
69 #include <libcitadel.h>
72 #include "citserver.h"
79 #include "internet_addressing.h"
82 #include "clientsocket.h"
83 #include "locate_host.h"
84 #include "citadel_dirs.h"
86 #include "ctdl_module.h"
88 #include "smtp_util.h"
89 #include "event_client.h"
90 #include "smtpqueue.h"
91 #include "smtp_clienthandlers.h"
93 const unsigned short DefaultMXPort = 25;
94 void DeleteSmtpOutMsg(void *v)
97 AsyncIO *IO = &Msg->IO;
98 EV_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
100 /* these are kept in our own space and free'd below */
101 Msg->IO.ConnectMe = NULL;
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... */
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 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
122 eNextState mx_connect_ip(AsyncIO *IO);
123 eNextState get_one_mx_host_ip(AsyncIO *IO);
125 /******************************************************************************
126 * So, we're finished with sending (regardless of success or failure) *
127 * This Message might be referenced by several Queue-Items, if we're the last,*
128 * we need to free the memory and send bounce messages (on terminal failure) *
129 * else we just free our SMTP-Message struct. *
130 ******************************************************************************/
131 void FinalizeMessageSend(SmtpOutMsg *Msg)
133 int IDestructQueItem;
136 AsyncIO *IO = &Msg->IO;
138 IDestructQueItem = DecreaseQReference(Msg->MyQItem);
140 nRemain = CountActiveQueueEntries(Msg->MyQItem);
142 if ((nRemain > 0) || IDestructQueItem)
143 MsgData = SerializeQueueItem(Msg->MyQItem);
148 * Uncompleted delivery instructions remain, so delete the old
149 * instructions and replace with the updated ones.
151 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
152 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
154 if (IDestructQueItem)
155 smtpq_do_bounce(Msg->MyQItem,Msg->msgtext);
159 struct CtdlMessage *msg;
160 msg = malloc(sizeof(struct CtdlMessage));
161 memset(msg, 0, sizeof(struct CtdlMessage));
162 msg->cm_magic = CTDLMESSAGE_MAGIC;
163 msg->cm_anon_type = MES_NORMAL;
164 msg->cm_format_type = FMT_RFC822;
165 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
166 Msg->MyQItem->QueMsgID =
167 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
168 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
169 CtdlFreeMessage(msg);
172 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
173 &Msg->MyQItem->MessageID,
176 FreeStrBuf(&MsgData);
178 RemoveContext(Msg->IO.CitContext);
179 if (IDestructQueItem)
180 RemoveQItem(Msg->MyQItem);
181 DeleteSmtpOutMsg(Msg);
184 eNextState FailOneAttempt(AsyncIO *IO)
186 SmtpOutMsg *Msg = IO->Data;
188 if (Msg->MyQEntry->Status == 2)
192 * possible ways here:
193 * - connection timeout
194 * - dns lookup failed
196 StopClientWatchers(IO);
198 if (Msg->pCurrRelay != NULL)
199 Msg->pCurrRelay = Msg->pCurrRelay->Next;
201 if (Msg->pCurrRelay == NULL) {
202 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
205 if (Msg->pCurrRelay->IsIP) {
206 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
207 return mx_connect_ip(IO);
210 EVS_syslog(LOG_DEBUG,
211 "SMTP: %s resolving next MX Record\n",
213 return get_one_mx_host_ip(IO);
218 void SetConnectStatus(AsyncIO *IO)
220 SmtpOutMsg *Msg = IO->Data;
226 if (IO->ConnectMe->IPv6) {
227 src = &IO->ConnectMe->Addr.sin6_addr;
230 struct sockaddr_in *addr;
232 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
233 src = &addr->sin_addr.s_addr;
236 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
241 if (Msg->mx_host == NULL)
242 Msg->mx_host = "<no MX-Record>";
244 EVS_syslog(LOG_DEBUG,
245 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
249 Msg->IO.ConnectMe->Port);
251 Msg->MyQEntry->Status = 5;
252 StrBufPrintf(Msg->MyQEntry->StatusMessage,
253 "Timeout while connecting %s [%s]:%d ",
256 Msg->IO.ConnectMe->Port);
257 Msg->IO.NextState = eConnect;
260 /*****************************************************************************
261 * So we connect our Relay IP here. *
262 *****************************************************************************/
263 eNextState mx_connect_ip(AsyncIO *IO)
265 SmtpOutMsg *Msg = IO->Data;
267 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
269 IO->ConnectMe = Msg->pCurrRelay;
270 Msg->State = eConnectMX;
272 SetConnectStatus(IO);
274 return EvConnectSock(IO,
276 SMTP_C_ReadTimeouts[0],
280 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
282 SmtpOutMsg *Msg = IO->Data;
283 struct hostent *hostent;
287 hostent = Msg->HostLookup.VParsedDNSReply;
288 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
289 (hostent != NULL) ) {
290 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
291 if (Msg->pCurrRelay->IPv6) {
292 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
293 &hostent->h_addr_list[0],
294 sizeof(struct in6_addr));
296 Msg->pCurrRelay->Addr.sin6_family =
298 Msg->pCurrRelay->Addr.sin6_port =
299 htons(DefaultMXPort);
302 struct sockaddr_in *addr;
304 * Bypass the ns lookup result like this:
305 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
306 * addr->sin_addr.s_addr =
307 * htonl((uint32_t)&hostent->h_addr_list[0]);
310 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
312 memcpy(&addr->sin_addr.s_addr,
313 hostent->h_addr_list[0],
316 addr->sin_family = hostent->h_addrtype;
317 addr->sin_port = htons(DefaultMXPort);
319 Msg->mx_host = Msg->pCurrRelay->Host;
320 return mx_connect_ip(IO);
323 return FailOneAttempt(IO);
326 eNextState get_one_mx_host_ip(AsyncIO *IO)
328 SmtpOutMsg * Msg = IO->Data;
330 * here we start with the lookup of one host. it might be...
331 * - the relay host *sigh*
332 * - the direct hostname if there was no mx record
338 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
340 EVS_syslog(LOG_DEBUG,
341 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
343 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
344 Msg->pCurrRelay->Host,
345 Msg->pCurrRelay->Port);
347 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
348 Msg->pCurrRelay->Host,
351 get_one_mx_host_ip_done))
353 Msg->MyQEntry->Status = 5;
354 StrBufPrintf(Msg->MyQEntry->StatusMessage,
355 "No MX hosts found for <%s>", Msg->node);
356 Msg->IO.NextState = eTerminateConnection;
357 return IO->NextState;
359 IO->NextState = eReadDNSReply;
360 return IO->NextState;
364 /*****************************************************************************
365 * here we try to find out about the MX records for our recipients. *
366 *****************************************************************************/
367 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
369 SmtpOutMsg * Msg = IO->Data;
374 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
376 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
379 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
380 (IO->DNS.Query->VParsedDNSReply != NULL))
381 { /* ok, we found mx records. */
382 Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
386 = IO->DNS.Query->VParsedDNSReply;
387 while (Msg->CurrMX) {
389 for (i = 0; i < 2; i++) {
392 p = (ParsedURL*) malloc(sizeof(ParsedURL));
393 memset(p, 0, sizeof(ParsedURL));
395 p->Port = DefaultMXPort;
397 p->Host = Msg->CurrMX->host;
402 Msg->CurrMX = Msg->CurrMX->next;
404 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
406 else { /* else fall back to the plain hostname */
408 for (i = 0; i < 2; i++) {
411 p = (ParsedURL*) malloc(sizeof(ParsedURL));
412 memset(p, 0, sizeof(ParsedURL));
414 p->Port = DefaultMXPort;
421 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
423 *pp = Msg->MyQItem->FallBackHost;
424 Msg->pCurrRelay = Msg->Relay;
425 return get_one_mx_host_ip(IO);
428 eNextState resolve_mx_records(AsyncIO *IO)
430 SmtpOutMsg * Msg = IO->Data;
432 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
433 /* start resolving MX records here. */
434 if (!QueueQuery(ns_t_mx,
438 smtp_resolve_mx_record_done))
440 Msg->MyQEntry->Status = 5;
441 StrBufPrintf(Msg->MyQEntry->StatusMessage,
442 "No MX hosts found for <%s>", Msg->node);
443 return IO->NextState;
445 Msg->IO.NextState = eReadDNSReply;
446 return IO->NextState;
451 /******************************************************************************
452 * so, we're going to start a SMTP delivery. lets get it on. *
453 ******************************************************************************/
455 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
456 MailQEntry *MyQEntry,
461 Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
462 memset(Msg, 0, sizeof(SmtpOutMsg));
465 Msg->MyQEntry = MyQEntry;
466 Msg->MyQItem = MyQItem;
467 Msg->pCurrRelay = MyQItem->URL;
469 InitIOStruct(&Msg->IO,
472 SMTP_C_ReadServerStatus,
474 SMTP_C_DispatchWriteDone,
475 SMTP_C_DispatchReadDone,
484 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
485 MailQEntry *MyQEntry,
487 /*KeepMsgText allows us to use MsgText as ours.*/
493 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
495 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
496 if (KeepMsgText) Msg->msgtext = MsgText;
497 else Msg->msgtext = NewStrBufDup(MsgText);
499 if (smtp_resolve_recipients(Msg)) {
502 ((CitContext *)Msg->IO.CitContext)->cs_host,
504 sizeof(((CitContext *)
505 Msg->IO.CitContext)->cs_host));
507 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
508 Msg->MyQItem->MessageID,
509 ChrPtr(Msg->MyQEntry->Recipient),
510 ((CitContext*)Msg->IO.CitContext)->cs_pid);
511 if (Msg->pCurrRelay == NULL)
512 QueueEventContext(&Msg->IO,
514 else { /* oh... via relay host */
515 if (Msg->pCurrRelay->IsIP) {
516 QueueEventContext(&Msg->IO,
520 /* uneducated admin has chosen to
521 add DNS to the equation... */
522 QueueEventContext(&Msg->IO,
528 /* No recipients? well fail then. */
530 (Msg->MyQEntry == NULL)) {
531 Msg->MyQEntry->Status = 5;
532 StrBufPlain(Msg->MyQEntry->StatusMessage,
533 HKEY("Invalid Recipient!"));
535 FinalizeMessageSend(Msg);
544 /*****************************************************************************/
545 /* SMTP CLIENT DISPATCHER */
546 /*****************************************************************************/
548 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
550 double Timeout = 0.0;
551 AsyncIO *IO = &Msg->IO;
553 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
555 switch (NextTCPState) {
559 Timeout = SMTP_C_SendTimeouts[Msg->State];
560 if (Msg->State == eDATABody) {
561 /* if we're sending a huge message,
564 Timeout += StrLength(Msg->msgtext) / 512;
568 Timeout = SMTP_C_ReadTimeouts[Msg->State];
569 if (Msg->State == eDATATerminateBody) {
571 * some mailservers take a nap before accepting
572 * the message content inspection and such.
574 Timeout += StrLength(Msg->msgtext) / 512;
584 case eTerminateConnection:
588 SetNextTimeout(&Msg->IO, Timeout);
590 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
592 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
593 SmtpOutMsg *Msg = IO->Data;
596 rc = ReadHandlers[Msg->State](Msg);
600 SMTPSetTimeout(rc, Msg);
604 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
606 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
607 SmtpOutMsg *Msg = IO->Data;
610 rc = SendHandlers[Msg->State](Msg);
611 SMTPSetTimeout(rc, Msg);
616 /*****************************************************************************/
617 /* SMTP CLIENT ERROR CATCHERS */
618 /*****************************************************************************/
619 eNextState SMTP_C_Terminate(AsyncIO *IO)
621 SmtpOutMsg *Msg = IO->Data;
623 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
624 FinalizeMessageSend(Msg);
627 eNextState SMTP_C_Timeout(AsyncIO *IO)
629 SmtpOutMsg *Msg = IO->Data;
631 Msg->MyQEntry->Status = 4;
632 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
633 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
634 if (Msg->State > eRCPT)
637 return FailOneAttempt(IO);
639 eNextState SMTP_C_ConnFail(AsyncIO *IO)
641 SmtpOutMsg *Msg = IO->Data;
643 Msg->MyQEntry->Status = 4;
644 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
645 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
646 return FailOneAttempt(IO);
648 eNextState SMTP_C_DNSFail(AsyncIO *IO)
650 SmtpOutMsg *Msg = IO->Data;
651 Msg->MyQEntry->Status = 4;
652 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
653 return FailOneAttempt(IO);
655 eNextState SMTP_C_Shutdown(AsyncIO *IO)
657 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
658 SmtpOutMsg *Msg = IO->Data;
660 Msg->MyQEntry->Status = 3;
661 StrBufPlain(Msg->MyQEntry->StatusMessage,
662 HKEY("server shutdown during message submit."));
663 FinalizeMessageSend(Msg);
669 * @brief lineread Handler;
670 * understands when to read more SMTP lines, and when this is a one-lined reply.
672 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
674 eReadState Finished = eBufferNotEmpty;
676 while (Finished == eBufferNotEmpty) {
677 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
680 case eMustReadMore: /// read new from socket...
683 case eBufferNotEmpty: /* shouldn't happen... */
684 case eReadSuccess: /// done for now...
685 if (StrLength(IO->IOBuf) < 4)
687 if (ChrPtr(IO->IOBuf)[3] == '-')
688 Finished = eBufferNotEmpty;
692 case eReadFail: /// WHUT?
700 CTDL_MODULE_INIT(smtp_eventclient)
702 return "smtpeventclient";