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);
129 eNextState FinalizeMessageSend_DB4(AsyncIO *IO);
131 /******************************************************************************
132 * So, we're finished with sending (regardless of success or failure) *
133 * This Message might be referenced by several Queue-Items, if we're the last,*
134 * we need to free the memory and send bounce messages (on terminal failure) *
135 * else we just free our SMTP-Message struct. *
136 ******************************************************************************/
137 inline void FinalizeMessageSend_1(AsyncIO *IO)
139 SmtpOutMsg *Msg = IO->Data;
140 Msg->IDestructQueItem = DecreaseQReference(Msg->MyQItem);
142 Msg->nRemain = CountActiveQueueEntries(Msg->MyQItem);
144 if (Msg->MyQEntry->Active &&
145 CheckQEntryIsBounce(Msg->MyQEntry))
147 /* are we casue for a bounce mail? */
148 Msg->MyQItem->SendBounceMail |= (1<<Msg->MyQEntry->Status);
151 if ((Msg->nRemain > 0) || Msg->IDestructQueItem)
152 Msg->QMsgData = SerializeQueueItem(Msg->MyQItem);
154 Msg->QMsgData = NULL;
156 eNextState FinalizeMessageSend(SmtpOutMsg *Msg)
158 return QueueDBOperation(&Msg->IO, FinalizeMessageSend_DB1);
161 inline void FinalizeMessageSend_DB_1(AsyncIO *IO)
163 SmtpOutMsg *Msg = IO->Data;
166 * Uncompleted delivery instructions remain, so delete the old
167 * instructions and replace with the updated ones.
169 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
170 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
172 eNextState FinalizeMessageSend_DB1(AsyncIO *IO)
174 FinalizeMessageSend_1(IO);
175 FinalizeMessageSend_DB_1(IO);
176 return NextDBOperation(IO, FinalizeMessageSend_DB2);
180 inline void FinalizeMessageSend_DB_2(AsyncIO *IO)
182 SmtpOutMsg *Msg = IO->Data;
184 if (Msg->IDestructQueItem)
185 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
187 eNextState FinalizeMessageSend_DB2(AsyncIO *IO)
189 FinalizeMessageSend_DB_2(IO);
191 return NextDBOperation(IO, FinalizeMessageSend_DB3);
195 inline void FinalizeMessageSend_DB_3(AsyncIO *IO)
197 SmtpOutMsg *Msg = IO->Data;
199 if (Msg->nRemain > 0)
201 struct CtdlMessage *msg;
202 msg = malloc(sizeof(struct CtdlMessage));
203 memset(msg, 0, sizeof(struct CtdlMessage));
204 msg->cm_magic = CTDLMESSAGE_MAGIC;
205 msg->cm_anon_type = MES_NORMAL;
206 msg->cm_format_type = FMT_RFC822;
207 msg->cm_fields['M'] = SmashStrBuf(&Msg->QMsgData);
208 msg->cm_fields['U'] = strdup("QMSG");
209 Msg->MyQItem->QueMsgID =
210 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
211 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
212 CtdlFreeMessage(msg);
215 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
216 &Msg->MyQItem->MessageID,
219 FreeStrBuf(&Msg->QMsgData);
221 DecreaseShutdownDeliveries(Msg->MyQItem);
223 eNextState FinalizeMessageSend_DB3(AsyncIO *IO)
225 SmtpOutMsg *Msg = IO->Data;
226 FinalizeMessageSend_DB_3(IO);
227 if (!Msg->IDestructQueItem)
229 return NextDBOperation(IO, FinalizeMessageSend_DB4);
232 eNextState FinalizeMessageSend_DB4(AsyncIO *IO)
235 SmtpOutMsg *Msg = IO->Data;
237 n = GetShutdownDeliveries(Msg->MyQItem);
239 return NextDBOperation(IO, FinalizeMessageSend_DB4);
244 eNextState FinalizeMessageSend_DB(AsyncIO *IO)
246 SmtpOutMsg *Msg = IO->Data;
248 RemoveContext(Msg->IO.CitContext);
249 if (Msg->IDestructQueItem)
250 RemoveQItem(Msg->MyQItem);
251 DeleteSmtpOutMsg(Msg);
255 eNextState FailOneAttempt(AsyncIO *IO)
257 SmtpOutMsg *Msg = IO->Data;
259 if (Msg->MyQEntry->Status == 2)
263 * possible ways here:
264 * - connection timeout
265 * - dns lookup failed
267 StopClientWatchers(IO);
269 if (Msg->pCurrRelay != NULL)
270 Msg->pCurrRelay = Msg->pCurrRelay->Next;
272 if (Msg->pCurrRelay == NULL) {
273 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
276 if (Msg->pCurrRelay->IsIP) {
277 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
278 return mx_connect_ip(IO);
281 EVS_syslog(LOG_DEBUG,
282 "SMTP: %s resolving next MX Record\n",
284 return get_one_mx_host_ip(IO);
289 void SetConnectStatus(AsyncIO *IO)
291 SmtpOutMsg *Msg = IO->Data;
297 if (IO->ConnectMe->IPv6) {
298 src = &IO->ConnectMe->Addr.sin6_addr;
301 struct sockaddr_in *addr;
303 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
304 src = &addr->sin_addr.s_addr;
307 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
312 if (Msg->mx_host == NULL)
313 Msg->mx_host = "<no MX-Record>";
315 EVS_syslog(LOG_DEBUG,
316 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
320 Msg->IO.ConnectMe->Port);
322 Msg->MyQEntry->Status = 5;
323 StrBufPrintf(Msg->MyQEntry->StatusMessage,
324 "Timeout while connecting %s [%s]:%d ",
327 Msg->IO.ConnectMe->Port);
328 Msg->IO.NextState = eConnect;
331 /*****************************************************************************
332 * So we connect our Relay IP here. *
333 *****************************************************************************/
334 eNextState mx_connect_ip(AsyncIO *IO)
336 SmtpOutMsg *Msg = IO->Data;
338 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
340 IO->ConnectMe = Msg->pCurrRelay;
341 Msg->State = eConnectMX;
343 SetConnectStatus(IO);
345 return EvConnectSock(IO,
347 SMTP_C_ReadTimeouts[0],
351 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
353 SmtpOutMsg *Msg = IO->Data;
354 struct hostent *hostent;
358 hostent = Msg->HostLookup.VParsedDNSReply;
359 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
360 (hostent != NULL) ) {
361 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
362 if (Msg->pCurrRelay->IPv6) {
363 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
364 &hostent->h_addr_list[0],
365 sizeof(struct in6_addr));
367 Msg->pCurrRelay->Addr.sin6_family =
369 Msg->pCurrRelay->Addr.sin6_port =
370 htons(DefaultMXPort);
373 struct sockaddr_in *addr;
375 * Bypass the ns lookup result like this:
376 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
377 * addr->sin_addr.s_addr =
378 * htonl((uint32_t)&hostent->h_addr_list[0]);
381 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
383 memcpy(&addr->sin_addr.s_addr,
384 hostent->h_addr_list[0],
387 addr->sin_family = hostent->h_addrtype;
388 addr->sin_port = htons(DefaultMXPort);
390 Msg->mx_host = Msg->pCurrRelay->Host;
391 return mx_connect_ip(IO);
394 return FailOneAttempt(IO);
397 eNextState get_one_mx_host_ip(AsyncIO *IO)
399 SmtpOutMsg * Msg = IO->Data;
401 * here we start with the lookup of one host. it might be...
402 * - the relay host *sigh*
403 * - the direct hostname if there was no mx record
409 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
411 EVS_syslog(LOG_DEBUG,
412 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
414 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
415 Msg->pCurrRelay->Host,
416 Msg->pCurrRelay->Port);
418 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
419 Msg->pCurrRelay->Host,
422 get_one_mx_host_ip_done))
424 Msg->MyQEntry->Status = 5;
425 StrBufPrintf(Msg->MyQEntry->StatusMessage,
426 "No MX hosts found for <%s>", Msg->node);
427 Msg->IO.NextState = eTerminateConnection;
428 return IO->NextState;
430 IO->NextState = eReadDNSReply;
431 return IO->NextState;
435 /*****************************************************************************
436 * here we try to find out about the MX records for our recipients. *
437 *****************************************************************************/
438 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
440 SmtpOutMsg * Msg = IO->Data;
445 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
448 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
451 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
452 (IO->DNS.Query->VParsedDNSReply != NULL))
453 { /* ok, we found mx records. */
457 = IO->DNS.Query->VParsedDNSReply;
458 while (Msg->CurrMX) {
460 for (i = 0; i < 2; i++) {
463 p = (ParsedURL*) malloc(sizeof(ParsedURL));
464 memset(p, 0, sizeof(ParsedURL));
465 p->Priority = Msg->CurrMX->priority;
467 p->Port = DefaultMXPort;
469 p->Host = Msg->CurrMX->host;
473 ParsedURL *ppp = *pp;
475 while ((ppp->Next != NULL) &&
476 (ppp->Next->Priority <= p->Priority))
479 (ppp->Priority > p->Priority)) {
489 Msg->CurrMX = Msg->CurrMX->next;
491 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
493 else { /* else fall back to the plain hostname */
495 for (i = 0; i < 2; i++) {
498 p = (ParsedURL*) malloc(sizeof(ParsedURL));
499 memset(p, 0, sizeof(ParsedURL));
501 p->Port = DefaultMXPort;
508 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
510 if (Msg->MyQItem->FallBackHost != NULL)
512 Msg->MyQItem->FallBackHost->Next = *pp;
513 *pp = Msg->MyQItem->FallBackHost;
515 Msg->pCurrRelay = Msg->Relay;
516 return get_one_mx_host_ip(IO);
519 eNextState resolve_mx_records(AsyncIO *IO)
521 SmtpOutMsg * Msg = IO->Data;
523 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
524 /* start resolving MX records here. */
525 if (!QueueQuery(ns_t_mx,
529 smtp_resolve_mx_record_done))
531 Msg->MyQEntry->Status = 5;
532 StrBufPrintf(Msg->MyQEntry->StatusMessage,
533 "No MX hosts found for <%s>", Msg->node);
534 return IO->NextState;
536 Msg->IO.NextState = eReadDNSReply;
537 return IO->NextState;
542 /******************************************************************************
543 * so, we're going to start a SMTP delivery. lets get it on. *
544 ******************************************************************************/
546 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
547 MailQEntry *MyQEntry,
552 Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
553 memset(Msg, 0, sizeof(SmtpOutMsg));
556 Msg->MyQEntry = MyQEntry;
557 Msg->MyQItem = MyQItem;
558 Msg->pCurrRelay = MyQItem->URL;
560 InitIOStruct(&Msg->IO,
563 SMTP_C_ReadServerStatus,
565 SMTP_C_DispatchWriteDone,
566 SMTP_C_DispatchReadDone,
573 Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
578 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
579 MailQEntry *MyQEntry,
581 /*KeepMsgText allows us to use MsgText as ours.*/
587 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
589 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
590 if (KeepMsgText) Msg->msgtext = MsgText;
591 else Msg->msgtext = NewStrBufDup(MsgText);
593 if (smtp_resolve_recipients(Msg)) {
596 ((CitContext *)Msg->IO.CitContext)->cs_host,
598 sizeof(((CitContext *)
599 Msg->IO.CitContext)->cs_host));
601 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
602 Msg->MyQItem->MessageID,
603 ChrPtr(Msg->MyQEntry->Recipient),
604 ((CitContext*)Msg->IO.CitContext)->cs_pid);
605 if (Msg->pCurrRelay == NULL)
606 QueueEventContext(&Msg->IO,
608 else { /* oh... via relay host */
609 if (Msg->pCurrRelay->IsIP) {
610 QueueEventContext(&Msg->IO,
614 /* uneducated admin has chosen to
615 add DNS to the equation... */
616 QueueEventContext(&Msg->IO,
622 /* No recipients? well fail then. */
624 (Msg->MyQEntry == NULL)) {
625 Msg->MyQEntry->Status = 5;
626 StrBufPlain(Msg->MyQEntry->StatusMessage,
627 HKEY("Invalid Recipient!"));
629 FinalizeMessageSend_1(&Msg->IO);
630 FinalizeMessageSend_DB_1(&Msg->IO);
631 FinalizeMessageSend_DB_2(&Msg->IO);
632 FinalizeMessageSend_DB_3(&Msg->IO);
633 FinalizeMessageSend_DB(&Msg->IO);
642 /*****************************************************************************/
643 /* SMTP CLIENT DISPATCHER */
644 /*****************************************************************************/
646 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
648 double Timeout = 0.0;
649 AsyncIO *IO = &Msg->IO;
651 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
653 switch (NextTCPState) {
657 Timeout = SMTP_C_SendTimeouts[Msg->State];
658 if (Msg->State == eDATABody) {
659 /* if we're sending a huge message,
662 Timeout += StrLength(Msg->msgtext) / 512;
666 Timeout = SMTP_C_ReadTimeouts[Msg->State];
667 if (Msg->State == eDATATerminateBody) {
669 * some mailservers take a nap before accepting
670 * the message content inspection and such.
672 Timeout += StrLength(Msg->msgtext) / 512;
682 case eTerminateConnection:
686 SetNextTimeout(&Msg->IO, Timeout);
688 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
690 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
691 SmtpOutMsg *Msg = IO->Data;
694 rc = ReadHandlers[Msg->State](Msg);
698 SMTPSetTimeout(rc, Msg);
702 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
704 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
705 SmtpOutMsg *Msg = IO->Data;
708 rc = SendHandlers[Msg->State](Msg);
709 SMTPSetTimeout(rc, Msg);
714 /*****************************************************************************/
715 /* SMTP CLIENT ERROR CATCHERS */
716 /*****************************************************************************/
717 eNextState SMTP_C_Terminate(AsyncIO *IO)
719 SmtpOutMsg *Msg = IO->Data;
721 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
722 return FinalizeMessageSend(Msg);
724 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
726 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
727 return FinalizeMessageSend_DB(IO);
729 eNextState SMTP_C_Timeout(AsyncIO *IO)
731 SmtpOutMsg *Msg = IO->Data;
733 Msg->MyQEntry->Status = 4;
734 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
735 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
736 if (Msg->State > eRCPT)
739 return FailOneAttempt(IO);
741 eNextState SMTP_C_ConnFail(AsyncIO *IO)
743 SmtpOutMsg *Msg = IO->Data;
745 Msg->MyQEntry->Status = 4;
746 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
747 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
748 return FailOneAttempt(IO);
750 eNextState SMTP_C_DNSFail(AsyncIO *IO)
752 SmtpOutMsg *Msg = IO->Data;
753 Msg->MyQEntry->Status = 4;
754 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
755 return FailOneAttempt(IO);
757 eNextState SMTP_C_Shutdown(AsyncIO *IO)
759 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
760 SmtpOutMsg *Msg = IO->Data;
762 Msg->MyQEntry->Status = 3;
763 StrBufPlain(Msg->MyQEntry->StatusMessage,
764 HKEY("server shutdown during message submit."));
765 return FinalizeMessageSend(Msg);
770 * @brief lineread Handler;
771 * understands when to read more SMTP lines, and when this is a one-lined reply.
773 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
775 eReadState Finished = eBufferNotEmpty;
777 while (Finished == eBufferNotEmpty) {
778 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
781 case eMustReadMore: /// read new from socket...
784 case eBufferNotEmpty: /* shouldn't happen... */
785 case eReadSuccess: /// done for now...
786 if (StrLength(IO->IOBuf) < 4)
788 if (ChrPtr(IO->IOBuf)[3] == '-')
789 Finished = eBufferNotEmpty;
793 case eReadFail: /// WHUT?
801 CTDL_MODULE_INIT(smtp_eventclient)
803 return "smtpeventclient";