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 int SMTPClientDebugEnabled = 0;
94 const unsigned short DefaultMXPort = 25;
95 void DeleteSmtpOutMsg(void *v)
98 AsyncIO *IO = &Msg->IO;
99 EVS_syslog(LOG_DEBUG, "%s Exit\n", __FUNCTION__);
101 /* these are kept in our own space and free'd below */
102 Msg->IO.ConnectMe = NULL;
104 ares_free_data(Msg->AllMX);
105 if (Msg->HostLookup.VParsedDNSReply != NULL)
106 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
107 FreeURL(&Msg->Relay);
108 FreeStrBuf(&Msg->msgtext);
109 FreeAsyncIOContents(&Msg->IO);
110 memset (Msg, 0, sizeof(SmtpOutMsg)); /* just to be shure... */
114 eNextState SMTP_C_Shutdown(AsyncIO *IO);
115 eNextState SMTP_C_Timeout(AsyncIO *IO);
116 eNextState SMTP_C_ConnFail(AsyncIO *IO);
117 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
118 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
119 eNextState SMTP_C_DNSFail(AsyncIO *IO);
120 eNextState SMTP_C_Terminate(AsyncIO *IO);
121 eNextState SMTP_C_TerminateDB(AsyncIO *IO);
122 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
124 eNextState mx_connect_ip(AsyncIO *IO);
125 eNextState get_one_mx_host_ip(AsyncIO *IO);
127 /******************************************************************************
128 * So, we're finished with sending (regardless of success or failure) *
129 * This Message might be referenced by several Queue-Items, if we're the last,*
130 * we need to free the memory and send bounce messages (on terminal failure) *
131 * else we just free our SMTP-Message struct. *
132 ******************************************************************************/
133 eNextState FinalizeMessageSend_DB(AsyncIO *IO)
136 SmtpOutMsg *Msg = IO->Data;
138 if (Msg->MyQEntry->Status == 2)
139 Status = "Delivery successful.";
140 else if (Msg->MyQEntry->Status == 5)
141 Status = "Delivery failed permanently; giving up.";
143 Status = "Delivery failed temporarily; will retry later.";
146 "%s Time[%fs] Recipient <%s> @ <%s> (%s) Status message: %s\n",
148 Msg->IO.Now - Msg->IO.StartIO,
152 ChrPtr(Msg->MyQEntry->StatusMessage));
155 Msg->IDestructQueItem = DecreaseQReference(Msg->MyQItem);
157 Msg->nRemain = CountActiveQueueEntries(Msg->MyQItem);
159 if (Msg->MyQEntry->Active &&
160 CheckQEntryIsBounce(Msg->MyQEntry))
162 /* are we casue for a bounce mail? */
163 Msg->MyQItem->SendBounceMail |= (1<<Msg->MyQEntry->Status);
166 if ((Msg->nRemain > 0) || Msg->IDestructQueItem)
167 Msg->QMsgData = SerializeQueueItem(Msg->MyQItem);
169 Msg->QMsgData = NULL;
172 * Uncompleted delivery instructions remain, so delete the old
173 * instructions and replace with the updated ones.
175 EVS_syslog(LOG_DEBUG, "%ld", Msg->MyQItem->QueMsgID);
176 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
177 Msg->MyQItem->QueMsgID = -1;
179 if (Msg->IDestructQueItem)
180 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
182 if (Msg->nRemain > 0)
184 struct CtdlMessage *msg;
185 msg = malloc(sizeof(struct CtdlMessage));
186 memset(msg, 0, sizeof(struct CtdlMessage));
187 msg->cm_magic = CTDLMESSAGE_MAGIC;
188 msg->cm_anon_type = MES_NORMAL;
189 msg->cm_format_type = FMT_RFC822;
190 msg->cm_fields['M'] = SmashStrBuf(&Msg->QMsgData);
191 msg->cm_fields['U'] = strdup("QMSG");
192 Msg->MyQItem->QueMsgID =
193 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
194 EVS_syslog(LOG_DEBUG, "%ld", Msg->MyQItem->QueMsgID);
195 CtdlFreeMessage(msg);
198 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
199 &Msg->MyQItem->MessageID,
202 FreeStrBuf(&Msg->QMsgData);
205 RemoveContext(Msg->IO.CitContext);
209 eNextState Terminate(AsyncIO *IO)
211 SmtpOutMsg *Msg = IO->Data;
213 if (Msg->IDestructQueItem)
214 RemoveQItem(Msg->MyQItem);
216 DeleteSmtpOutMsg(Msg);
219 eNextState FinalizeMessageSend(SmtpOutMsg *Msg)
221 /* hand over to DB Queue */
222 return QueueDBOperation(&Msg->IO, FinalizeMessageSend_DB);
225 eNextState FailOneAttempt(AsyncIO *IO)
227 SmtpOutMsg *Msg = IO->Data;
229 if (Msg->MyQEntry->Status == 2)
233 * possible ways here:
234 * - connection timeout
235 * - dns lookup failed
237 StopClientWatchers(IO);
239 if (Msg->pCurrRelay != NULL)
240 Msg->pCurrRelay = Msg->pCurrRelay->Next;
242 if (Msg->pCurrRelay == NULL) {
243 EVS_syslog(LOG_DEBUG, "%s Aborting\n", __FUNCTION__);
246 if (Msg->pCurrRelay->IsIP) {
247 EVS_syslog(LOG_DEBUG, "%s connecting IP\n", __FUNCTION__);
248 return mx_connect_ip(IO);
251 EVS_syslog(LOG_DEBUG,
252 "%s resolving next MX Record\n",
254 return get_one_mx_host_ip(IO);
259 void SetConnectStatus(AsyncIO *IO)
261 SmtpOutMsg *Msg = IO->Data;
267 if (IO->ConnectMe->IPv6) {
268 src = &IO->ConnectMe->Addr.sin6_addr;
271 struct sockaddr_in *addr;
273 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
274 src = &addr->sin_addr.s_addr;
277 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
282 if (Msg->mx_host == NULL)
283 Msg->mx_host = "<no MX-Record>";
286 "connecting to %s [%s]:%d ...\n",
289 Msg->IO.ConnectMe->Port);
291 Msg->MyQEntry->Status = 4;
292 StrBufPrintf(Msg->MyQEntry->StatusMessage,
293 "Timeout while connecting %s [%s]:%d ",
296 Msg->IO.ConnectMe->Port);
297 Msg->IO.NextState = eConnect;
300 /*****************************************************************************
301 * So we connect our Relay IP here. *
302 *****************************************************************************/
303 eNextState mx_connect_ip(AsyncIO *IO)
305 SmtpOutMsg *Msg = IO->Data;
307 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
309 IO->ConnectMe = Msg->pCurrRelay;
310 Msg->State = eConnectMX;
312 SetConnectStatus(IO);
314 return EvConnectSock(IO,
316 SMTP_C_ReadTimeouts[0],
320 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
322 SmtpOutMsg *Msg = IO->Data;
323 struct hostent *hostent;
326 EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
328 IO->Now - IO->DNS.Start);
330 hostent = Msg->HostLookup.VParsedDNSReply;
331 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
332 (hostent != NULL) ) {
333 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
334 if (Msg->pCurrRelay->IPv6) {
335 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
336 &hostent->h_addr_list[0],
337 sizeof(struct in6_addr));
339 Msg->pCurrRelay->Addr.sin6_family =
341 Msg->pCurrRelay->Addr.sin6_port =
342 htons(DefaultMXPort);
345 struct sockaddr_in *addr;
347 * Bypass the ns lookup result like this:
348 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
349 * addr->sin_addr.s_addr =
350 * htonl((uint32_t)&hostent->h_addr_list[0]);
353 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
355 memcpy(&addr->sin_addr.s_addr,
356 hostent->h_addr_list[0],
359 addr->sin_family = hostent->h_addrtype;
360 addr->sin_port = htons(DefaultMXPort);
362 Msg->mx_host = Msg->pCurrRelay->Host;
363 if (Msg->HostLookup.VParsedDNSReply != NULL) {
364 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
365 Msg->HostLookup.VParsedDNSReply = NULL;
367 return mx_connect_ip(IO);
370 if (Msg->HostLookup.VParsedDNSReply != NULL) {
371 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
372 Msg->HostLookup.VParsedDNSReply = NULL;
374 return FailOneAttempt(IO);
378 eNextState get_one_mx_host_ip(AsyncIO *IO)
380 SmtpOutMsg * Msg = IO->Data;
382 * here we start with the lookup of one host. it might be...
383 * - the relay host *sigh*
384 * - the direct hostname if there was no mx record
388 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
390 EVS_syslog(LOG_DEBUG,
391 "looking up %s-Record %s : %d ...\n",
392 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
393 Msg->pCurrRelay->Host,
394 Msg->pCurrRelay->Port);
396 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
397 Msg->pCurrRelay->Host,
400 get_one_mx_host_ip_done))
402 Msg->MyQEntry->Status = 5;
403 StrBufPrintf(Msg->MyQEntry->StatusMessage,
404 "No MX hosts found for <%s>", Msg->node);
405 Msg->IO.NextState = eTerminateConnection;
406 return IO->NextState;
408 IO->NextState = eReadDNSReply;
409 return IO->NextState;
413 /*****************************************************************************
414 * here we try to find out about the MX records for our recipients. *
415 *****************************************************************************/
416 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
418 SmtpOutMsg * Msg = IO->Data;
423 EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
425 IO->Now - IO->DNS.Start);
428 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
431 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
432 (IO->DNS.Query->VParsedDNSReply != NULL))
433 { /* ok, we found mx records. */
437 = IO->DNS.Query->VParsedDNSReply;
438 while (Msg->CurrMX) {
440 for (i = 0; i < 2; i++) {
443 p = (ParsedURL*) malloc(sizeof(ParsedURL));
444 memset(p, 0, sizeof(ParsedURL));
445 p->Priority = Msg->CurrMX->priority;
447 p->Port = DefaultMXPort;
449 p->Host = Msg->CurrMX->host;
453 ParsedURL *ppp = *pp;
455 while ((ppp->Next != NULL) &&
456 (ppp->Next->Priority <= p->Priority))
459 (ppp->Priority > p->Priority)) {
469 Msg->CurrMX = Msg->CurrMX->next;
471 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
473 else { /* else fall back to the plain hostname */
475 for (i = 0; i < 2; i++) {
478 p = (ParsedURL*) malloc(sizeof(ParsedURL));
479 memset(p, 0, sizeof(ParsedURL));
481 p->Port = DefaultMXPort;
488 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
490 if (Msg->MyQItem->FallBackHost != NULL)
492 Msg->MyQItem->FallBackHost->Next = *pp;
493 *pp = Msg->MyQItem->FallBackHost;
495 Msg->pCurrRelay = Msg->Relay;
496 return get_one_mx_host_ip(IO);
499 eNextState resolve_mx_records(AsyncIO *IO)
501 SmtpOutMsg * Msg = IO->Data;
503 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
504 /* start resolving MX records here. */
505 if (!QueueQuery(ns_t_mx,
509 smtp_resolve_mx_record_done))
511 Msg->MyQEntry->Status = 5;
512 StrBufPrintf(Msg->MyQEntry->StatusMessage,
513 "No MX hosts found for <%s>", Msg->node);
514 return IO->NextState;
516 Msg->IO.NextState = eReadDNSReply;
517 return IO->NextState;
522 /******************************************************************************
523 * so, we're going to start a SMTP delivery. lets get it on. *
524 ******************************************************************************/
526 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
527 MailQEntry *MyQEntry,
532 Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
535 memset(Msg, 0, sizeof(SmtpOutMsg));
538 Msg->MyQEntry = MyQEntry;
539 Msg->MyQItem = MyQItem;
540 Msg->pCurrRelay = MyQItem->URL;
542 InitIOStruct(&Msg->IO,
545 SMTP_C_ReadServerStatus,
547 SMTP_C_DispatchWriteDone,
548 SMTP_C_DispatchReadDone,
555 Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
560 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
561 MailQEntry *MyQEntry,
563 /*KeepMsgText allows us to use MsgText as ours.*/
569 SMTPC_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
571 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
573 SMTPC_syslog(LOG_DEBUG, "%s Failed to alocate message context.\n", __FUNCTION__);
575 FreeStrBuf (&MsgText);
578 if (KeepMsgText) Msg->msgtext = MsgText;
579 else Msg->msgtext = NewStrBufDup(MsgText);
581 if (smtp_resolve_recipients(Msg)) {
584 ((CitContext *)Msg->IO.CitContext)->cs_host,
586 sizeof(((CitContext *)
587 Msg->IO.CitContext)->cs_host));
589 SMTPC_syslog(LOG_DEBUG, "Starting: [%ld] <%s> CC <%d> \n",
590 Msg->MyQItem->MessageID,
591 ChrPtr(Msg->MyQEntry->Recipient),
592 ((CitContext*)Msg->IO.CitContext)->cs_pid);
593 if (Msg->pCurrRelay == NULL)
594 QueueEventContext(&Msg->IO,
596 else { /* oh... via relay host */
597 if (Msg->pCurrRelay->IsIP) {
598 QueueEventContext(&Msg->IO,
602 /* uneducated admin has chosen to
603 add DNS to the equation... */
604 QueueEventContext(&Msg->IO,
610 /* No recipients? well fail then. */
611 if (Msg->MyQEntry == NULL) {
612 Msg->MyQEntry->Status = 5;
613 StrBufPlain(Msg->MyQEntry->StatusMessage,
614 HKEY("Invalid Recipient!"));
616 FinalizeMessageSend_DB(&Msg->IO);
617 DeleteSmtpOutMsg(&Msg->IO);
626 /*****************************************************************************/
627 /* SMTP CLIENT DISPATCHER */
628 /*****************************************************************************/
630 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
632 double Timeout = 0.0;
633 AsyncIO *IO = &Msg->IO;
635 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
637 switch (NextTCPState) {
641 Timeout = SMTP_C_SendTimeouts[Msg->State];
642 if (Msg->State == eDATABody) {
643 /* if we're sending a huge message,
646 Timeout += StrLength(Msg->msgtext) / 512;
650 Timeout = SMTP_C_ReadTimeouts[Msg->State];
651 if (Msg->State == eDATATerminateBody) {
653 * some mailservers take a nap before accepting
654 * the message content inspection and such.
656 Timeout += StrLength(Msg->msgtext) / 512;
666 case eTerminateConnection:
670 SetNextTimeout(&Msg->IO, Timeout);
672 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
674 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
675 SmtpOutMsg *Msg = IO->Data;
678 rc = ReadHandlers[Msg->State](Msg);
682 SMTPSetTimeout(rc, Msg);
686 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
688 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
689 SmtpOutMsg *Msg = IO->Data;
692 rc = SendHandlers[Msg->State](Msg);
693 SMTPSetTimeout(rc, Msg);
698 /*****************************************************************************/
699 /* SMTP CLIENT ERROR CATCHERS */
700 /*****************************************************************************/
701 eNextState SMTP_C_Terminate(AsyncIO *IO)
703 SmtpOutMsg *Msg = IO->Data;
705 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
706 return FinalizeMessageSend(Msg);
708 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
710 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
711 return Terminate(IO);
713 eNextState SMTP_C_Timeout(AsyncIO *IO)
715 SmtpOutMsg *Msg = IO->Data;
717 Msg->MyQEntry->Status = 4;
718 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
719 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
720 if (Msg->State > eRCPT)
723 return FailOneAttempt(IO);
725 eNextState SMTP_C_ConnFail(AsyncIO *IO)
727 SmtpOutMsg *Msg = IO->Data;
729 Msg->MyQEntry->Status = 4;
730 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
731 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
732 return FailOneAttempt(IO);
734 eNextState SMTP_C_DNSFail(AsyncIO *IO)
736 SmtpOutMsg *Msg = IO->Data;
737 Msg->MyQEntry->Status = 4;
738 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
739 return FailOneAttempt(IO);
741 eNextState SMTP_C_Shutdown(AsyncIO *IO)
743 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
744 SmtpOutMsg *Msg = IO->Data;
746 Msg->MyQEntry->Status = 3;
747 StrBufPlain(Msg->MyQEntry->StatusMessage,
748 HKEY("server shutdown during message submit."));
749 return FinalizeMessageSend(Msg);
754 * @brief lineread Handler;
755 * understands when to read more SMTP lines, and when this is a one-lined reply.
757 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
759 eReadState Finished = eBufferNotEmpty;
761 while (Finished == eBufferNotEmpty) {
762 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
765 case eMustReadMore: /// read new from socket...
768 case eBufferNotEmpty: /* shouldn't happen... */
769 case eReadSuccess: /// done for now...
770 if (StrLength(IO->IOBuf) < 4)
772 if (ChrPtr(IO->IOBuf)[3] == '-')
773 Finished = eBufferNotEmpty;
777 case eReadFail: /// WHUT?
785 void LogDebugEnableSMTPClient(const int n)
787 SMTPClientDebugEnabled = n;
790 CTDL_MODULE_INIT(smtp_eventclient)
793 CtdlRegisterDebugFlagHook(HKEY("smtpeventclient"), LogDebugEnableSMTPClient, &SMTPClientDebugEnabled);
794 return "smtpeventclient";