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 eNextState SMTP_C_TerminateDB(AsyncIO *IO);
121 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
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);
130 /******************************************************************************
131 * So, we're finished with sending (regardless of success or failure) *
132 * This Message might be referenced by several Queue-Items, if we're the last,*
133 * we need to free the memory and send bounce messages (on terminal failure) *
134 * else we just free our SMTP-Message struct. *
135 ******************************************************************************/
136 inline void FinalizeMessageSend_1(AsyncIO *IO)
138 SmtpOutMsg *Msg = IO->Data;
139 Msg->IDestructQueItem = DecreaseQReference(Msg->MyQItem);
141 Msg->nRemain = CountActiveQueueEntries(Msg->MyQItem);
143 if (Msg->MyQEntry->Active &&
144 CheckQEntryIsBounce(Msg->MyQEntry))
146 /* are we casue for a bounce mail? */
147 Msg->MyQItem->SendBounceMail |= (1<<Msg->MyQEntry->Status);
150 if ((Msg->nRemain > 0) || Msg->IDestructQueItem)
151 Msg->QMsgData = SerializeQueueItem(Msg->MyQItem);
153 Msg->QMsgData = NULL;
155 eNextState FinalizeMessageSend(SmtpOutMsg *Msg)
157 return QueueDBOperation(&Msg->IO, FinalizeMessageSend_DB1);
160 inline void FinalizeMessageSend_DB_1(AsyncIO *IO)
162 SmtpOutMsg *Msg = IO->Data;
165 * Uncompleted delivery instructions remain, so delete the old
166 * instructions and replace with the updated ones.
168 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
169 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
171 eNextState FinalizeMessageSend_DB1(AsyncIO *IO)
173 FinalizeMessageSend_1(IO);
174 FinalizeMessageSend_DB_1(IO);
175 return NextDBOperation(IO, FinalizeMessageSend_DB2);
179 inline void FinalizeMessageSend_DB_2(AsyncIO *IO)
181 SmtpOutMsg *Msg = IO->Data;
183 if (Msg->IDestructQueItem)
184 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
186 eNextState FinalizeMessageSend_DB2(AsyncIO *IO)
188 FinalizeMessageSend_DB_2(IO);
190 return NextDBOperation(IO, FinalizeMessageSend_DB3);
194 inline void FinalizeMessageSend_DB_3(AsyncIO *IO)
196 SmtpOutMsg *Msg = IO->Data;
198 if (Msg->nRemain > 0)
200 struct CtdlMessage *msg;
201 msg = malloc(sizeof(struct CtdlMessage));
202 memset(msg, 0, sizeof(struct CtdlMessage));
203 msg->cm_magic = CTDLMESSAGE_MAGIC;
204 msg->cm_anon_type = MES_NORMAL;
205 msg->cm_format_type = FMT_RFC822;
206 msg->cm_fields['M'] = SmashStrBuf(&Msg->QMsgData);
207 msg->cm_fields['U'] = strdup("QMSG");
208 Msg->MyQItem->QueMsgID =
209 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
210 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
211 CtdlFreeMessage(msg);
214 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
215 &Msg->MyQItem->MessageID,
218 FreeStrBuf(&Msg->QMsgData);
221 eNextState FinalizeMessageSend_DB3(AsyncIO *IO)
223 FinalizeMessageSend_DB_3(IO);
227 eNextState FinalizeMessageSend_DB(AsyncIO *IO)
229 SmtpOutMsg *Msg = IO->Data;
231 RemoveContext(Msg->IO.CitContext);
232 if (Msg->IDestructQueItem)
233 RemoveQItem(Msg->MyQItem);
234 DeleteSmtpOutMsg(Msg);
238 eNextState FailOneAttempt(AsyncIO *IO)
240 SmtpOutMsg *Msg = IO->Data;
242 if (Msg->MyQEntry->Status == 2)
246 * possible ways here:
247 * - connection timeout
248 * - dns lookup failed
250 StopClientWatchers(IO);
252 if (Msg->pCurrRelay != NULL)
253 Msg->pCurrRelay = Msg->pCurrRelay->Next;
255 if (Msg->pCurrRelay == NULL) {
256 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
259 if (Msg->pCurrRelay->IsIP) {
260 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
261 return mx_connect_ip(IO);
264 EVS_syslog(LOG_DEBUG,
265 "SMTP: %s resolving next MX Record\n",
267 return get_one_mx_host_ip(IO);
272 void SetConnectStatus(AsyncIO *IO)
274 SmtpOutMsg *Msg = IO->Data;
280 if (IO->ConnectMe->IPv6) {
281 src = &IO->ConnectMe->Addr.sin6_addr;
284 struct sockaddr_in *addr;
286 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
287 src = &addr->sin_addr.s_addr;
290 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
295 if (Msg->mx_host == NULL)
296 Msg->mx_host = "<no MX-Record>";
298 EVS_syslog(LOG_DEBUG,
299 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
303 Msg->IO.ConnectMe->Port);
305 Msg->MyQEntry->Status = 5;
306 StrBufPrintf(Msg->MyQEntry->StatusMessage,
307 "Timeout while connecting %s [%s]:%d ",
310 Msg->IO.ConnectMe->Port);
311 Msg->IO.NextState = eConnect;
314 /*****************************************************************************
315 * So we connect our Relay IP here. *
316 *****************************************************************************/
317 eNextState mx_connect_ip(AsyncIO *IO)
319 SmtpOutMsg *Msg = IO->Data;
321 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
323 IO->ConnectMe = Msg->pCurrRelay;
324 Msg->State = eConnectMX;
326 SetConnectStatus(IO);
328 return EvConnectSock(IO,
330 SMTP_C_ReadTimeouts[0],
334 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
336 SmtpOutMsg *Msg = IO->Data;
337 struct hostent *hostent;
341 hostent = Msg->HostLookup.VParsedDNSReply;
342 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
343 (hostent != NULL) ) {
344 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
345 if (Msg->pCurrRelay->IPv6) {
346 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
347 &hostent->h_addr_list[0],
348 sizeof(struct in6_addr));
350 Msg->pCurrRelay->Addr.sin6_family =
352 Msg->pCurrRelay->Addr.sin6_port =
353 htons(DefaultMXPort);
356 struct sockaddr_in *addr;
358 * Bypass the ns lookup result like this:
359 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
360 * addr->sin_addr.s_addr =
361 * htonl((uint32_t)&hostent->h_addr_list[0]);
364 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
366 memcpy(&addr->sin_addr.s_addr,
367 hostent->h_addr_list[0],
370 addr->sin_family = hostent->h_addrtype;
371 addr->sin_port = htons(DefaultMXPort);
373 Msg->mx_host = Msg->pCurrRelay->Host;
374 return mx_connect_ip(IO);
377 return FailOneAttempt(IO);
380 eNextState get_one_mx_host_ip(AsyncIO *IO)
382 SmtpOutMsg * Msg = IO->Data;
384 * here we start with the lookup of one host. it might be...
385 * - the relay host *sigh*
386 * - the direct hostname if there was no mx record
392 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
394 EVS_syslog(LOG_DEBUG,
395 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
397 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
398 Msg->pCurrRelay->Host,
399 Msg->pCurrRelay->Port);
401 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
402 Msg->pCurrRelay->Host,
405 get_one_mx_host_ip_done))
407 Msg->MyQEntry->Status = 5;
408 StrBufPrintf(Msg->MyQEntry->StatusMessage,
409 "No MX hosts found for <%s>", Msg->node);
410 Msg->IO.NextState = eTerminateConnection;
411 return IO->NextState;
413 IO->NextState = eReadDNSReply;
414 return IO->NextState;
418 /*****************************************************************************
419 * here we try to find out about the MX records for our recipients. *
420 *****************************************************************************/
421 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
423 SmtpOutMsg * Msg = IO->Data;
428 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
431 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
434 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
435 (IO->DNS.Query->VParsedDNSReply != NULL))
436 { /* ok, we found mx records. */
440 = IO->DNS.Query->VParsedDNSReply;
441 while (Msg->CurrMX) {
443 for (i = 0; i < 2; i++) {
446 p = (ParsedURL*) malloc(sizeof(ParsedURL));
447 memset(p, 0, sizeof(ParsedURL));
448 p->Priority = Msg->CurrMX->priority;
450 p->Port = DefaultMXPort;
452 p->Host = Msg->CurrMX->host;
456 ParsedURL *ppp = *pp;
458 while ((ppp->Next != NULL) &&
459 (ppp->Next->Priority <= p->Priority))
462 (ppp->Priority > p->Priority)) {
472 Msg->CurrMX = Msg->CurrMX->next;
474 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
476 else { /* else fall back to the plain hostname */
478 for (i = 0; i < 2; i++) {
481 p = (ParsedURL*) malloc(sizeof(ParsedURL));
482 memset(p, 0, sizeof(ParsedURL));
484 p->Port = DefaultMXPort;
491 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
493 if (Msg->MyQItem->FallBackHost != NULL)
495 Msg->MyQItem->FallBackHost->Next = *pp;
496 *pp = Msg->MyQItem->FallBackHost;
498 Msg->pCurrRelay = Msg->Relay;
499 return get_one_mx_host_ip(IO);
502 eNextState resolve_mx_records(AsyncIO *IO)
504 SmtpOutMsg * Msg = IO->Data;
506 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
507 /* start resolving MX records here. */
508 if (!QueueQuery(ns_t_mx,
512 smtp_resolve_mx_record_done))
514 Msg->MyQEntry->Status = 5;
515 StrBufPrintf(Msg->MyQEntry->StatusMessage,
516 "No MX hosts found for <%s>", Msg->node);
517 return IO->NextState;
519 Msg->IO.NextState = eReadDNSReply;
520 return IO->NextState;
525 /******************************************************************************
526 * so, we're going to start a SMTP delivery. lets get it on. *
527 ******************************************************************************/
529 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
530 MailQEntry *MyQEntry,
535 Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
536 memset(Msg, 0, sizeof(SmtpOutMsg));
539 Msg->MyQEntry = MyQEntry;
540 Msg->MyQItem = MyQItem;
541 Msg->pCurrRelay = MyQItem->URL;
543 InitIOStruct(&Msg->IO,
546 SMTP_C_ReadServerStatus,
548 SMTP_C_DispatchWriteDone,
549 SMTP_C_DispatchReadDone,
556 Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
561 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
562 MailQEntry *MyQEntry,
564 /*KeepMsgText allows us to use MsgText as ours.*/
570 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
572 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
573 if (KeepMsgText) Msg->msgtext = MsgText;
574 else Msg->msgtext = NewStrBufDup(MsgText);
576 if (smtp_resolve_recipients(Msg)) {
579 ((CitContext *)Msg->IO.CitContext)->cs_host,
581 sizeof(((CitContext *)
582 Msg->IO.CitContext)->cs_host));
584 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
585 Msg->MyQItem->MessageID,
586 ChrPtr(Msg->MyQEntry->Recipient),
587 ((CitContext*)Msg->IO.CitContext)->cs_pid);
588 if (Msg->pCurrRelay == NULL)
589 QueueEventContext(&Msg->IO,
591 else { /* oh... via relay host */
592 if (Msg->pCurrRelay->IsIP) {
593 QueueEventContext(&Msg->IO,
597 /* uneducated admin has chosen to
598 add DNS to the equation... */
599 QueueEventContext(&Msg->IO,
605 /* No recipients? well fail then. */
607 (Msg->MyQEntry == NULL)) {
608 Msg->MyQEntry->Status = 5;
609 StrBufPlain(Msg->MyQEntry->StatusMessage,
610 HKEY("Invalid Recipient!"));
612 FinalizeMessageSend_1(&Msg->IO);
613 FinalizeMessageSend_DB_1(&Msg->IO);
614 FinalizeMessageSend_DB_2(&Msg->IO);
615 FinalizeMessageSend_DB_3(&Msg->IO);
616 FinalizeMessageSend_DB(&Msg->IO);
625 /*****************************************************************************/
626 /* SMTP CLIENT DISPATCHER */
627 /*****************************************************************************/
629 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
631 double Timeout = 0.0;
632 AsyncIO *IO = &Msg->IO;
634 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
636 switch (NextTCPState) {
640 Timeout = SMTP_C_SendTimeouts[Msg->State];
641 if (Msg->State == eDATABody) {
642 /* if we're sending a huge message,
645 Timeout += StrLength(Msg->msgtext) / 512;
649 Timeout = SMTP_C_ReadTimeouts[Msg->State];
650 if (Msg->State == eDATATerminateBody) {
652 * some mailservers take a nap before accepting
653 * the message content inspection and such.
655 Timeout += StrLength(Msg->msgtext) / 512;
665 case eTerminateConnection:
669 SetNextTimeout(&Msg->IO, Timeout);
671 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
673 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
674 SmtpOutMsg *Msg = IO->Data;
677 rc = ReadHandlers[Msg->State](Msg);
681 SMTPSetTimeout(rc, Msg);
685 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
687 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
688 SmtpOutMsg *Msg = IO->Data;
691 rc = SendHandlers[Msg->State](Msg);
692 SMTPSetTimeout(rc, Msg);
697 /*****************************************************************************/
698 /* SMTP CLIENT ERROR CATCHERS */
699 /*****************************************************************************/
700 eNextState SMTP_C_Terminate(AsyncIO *IO)
702 SmtpOutMsg *Msg = IO->Data;
704 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
705 return FinalizeMessageSend(Msg);
707 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
709 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
710 return FinalizeMessageSend_DB(IO);
712 eNextState SMTP_C_Timeout(AsyncIO *IO)
714 SmtpOutMsg *Msg = IO->Data;
716 Msg->MyQEntry->Status = 4;
717 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
718 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
719 if (Msg->State > eRCPT)
722 return FailOneAttempt(IO);
724 eNextState SMTP_C_ConnFail(AsyncIO *IO)
726 SmtpOutMsg *Msg = IO->Data;
728 Msg->MyQEntry->Status = 4;
729 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
730 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
731 return FailOneAttempt(IO);
733 eNextState SMTP_C_DNSFail(AsyncIO *IO)
735 SmtpOutMsg *Msg = IO->Data;
736 Msg->MyQEntry->Status = 4;
737 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
738 return FailOneAttempt(IO);
740 eNextState SMTP_C_Shutdown(AsyncIO *IO)
742 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
743 SmtpOutMsg *Msg = IO->Data;
745 Msg->MyQEntry->Status = 3;
746 StrBufPlain(Msg->MyQEntry->StatusMessage,
747 HKEY("server shutdown during message submit."));
748 return FinalizeMessageSend(Msg);
753 * @brief lineread Handler;
754 * understands when to read more SMTP lines, and when this is a one-lined reply.
756 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
758 eReadState Finished = eBufferNotEmpty;
760 while (Finished == eBufferNotEmpty) {
761 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
764 case eMustReadMore: /// read new from socket...
767 case eBufferNotEmpty: /* shouldn't happen... */
768 case eReadSuccess: /// done for now...
769 if (StrLength(IO->IOBuf) < 4)
771 if (ChrPtr(IO->IOBuf)[3] == '-')
772 Finished = eBufferNotEmpty;
776 case eReadFail: /// WHUT?
784 CTDL_MODULE_INIT(smtp_eventclient)
786 return "smtpeventclient";