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 void DeleteSmtpOutMsg(void *v)
97 AsyncIO *IO = &Msg->IO;
98 EV_syslog(LOG_DEBUG, "%s Exit\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);
126 /******************************************************************************
127 * So, we're finished with sending (regardless of success or failure) *
128 * This Message might be referenced by several Queue-Items, if we're the last,*
129 * we need to free the memory and send bounce messages (on terminal failure) *
130 * else we just free our SMTP-Message struct. *
131 ******************************************************************************/
132 eNextState FinalizeMessageSend_DB(AsyncIO *IO)
135 SmtpOutMsg *Msg = IO->Data;
137 if (Msg->MyQEntry->Status == 2)
138 Status = "Delivery successful.";
139 else if (Msg->MyQEntry->Status == 5)
140 Status = "Delivery failed permanently; giving up.";
142 Status = "Delivery failed temporarily; will retry later.";
145 "%s Time[%fs] Recipient <%s> @ <%s> (%s) Status message: %s\n",
147 Msg->IO.Now - Msg->IO.StartIO,
151 ChrPtr(Msg->MyQEntry->StatusMessage));
154 Msg->IDestructQueItem = DecreaseQReference(Msg->MyQItem);
156 Msg->nRemain = CountActiveQueueEntries(Msg->MyQItem, 0);
158 if (Msg->MyQEntry->Active &&
159 !Msg->MyQEntry->StillActive &&
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, Msg->pCurrRelay);
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, 1);
239 if (Msg->pCurrRelay != NULL)
240 Msg->pCurrRelay = Msg->pCurrRelay->Next;
241 if ((Msg->pCurrRelay != NULL) &&
242 !Msg->pCurrRelay->IsRelay &&
243 Msg->MyQItem->HaveRelay)
245 EVS_syslog(LOG_DEBUG, "%s Aborting; last relay failed.\n", __FUNCTION__);
249 if (Msg->pCurrRelay == NULL) {
250 EVS_syslog(LOG_DEBUG, "%s Aborting\n", __FUNCTION__);
253 if (Msg->pCurrRelay->IsIP) {
254 EVS_syslog(LOG_DEBUG, "%s connecting IP\n", __FUNCTION__);
255 return mx_connect_ip(IO);
258 EVS_syslog(LOG_DEBUG,
259 "%s resolving next MX Record\n",
261 return get_one_mx_host_ip(IO);
266 void SetConnectStatus(AsyncIO *IO)
268 SmtpOutMsg *Msg = IO->Data;
274 if (IO->ConnectMe->IPv6) {
275 src = &IO->ConnectMe->Addr.sin6_addr;
278 struct sockaddr_in *addr;
280 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
281 src = &addr->sin_addr.s_addr;
284 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
289 if (Msg->mx_host == NULL)
290 Msg->mx_host = "<no MX-Record>";
293 "connecting to %s [%s]:%d ...\n",
296 Msg->IO.ConnectMe->Port);
298 Msg->MyQEntry->Status = 4;
299 StrBufPrintf(Msg->MyQEntry->StatusMessage,
300 "Timeout while connecting %s [%s]:%d ",
303 Msg->IO.ConnectMe->Port);
304 Msg->IO.NextState = eConnect;
307 /*****************************************************************************
308 * So we connect our Relay IP here. *
309 *****************************************************************************/
310 eNextState mx_connect_ip(AsyncIO *IO)
312 SmtpOutMsg *Msg = IO->Data;
314 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
316 IO->ConnectMe = Msg->pCurrRelay;
317 Msg->State = eConnectMX;
319 SetConnectStatus(IO);
321 return EvConnectSock(IO,
323 SMTP_C_ReadTimeouts[0],
327 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
329 SmtpOutMsg *Msg = IO->Data;
330 struct hostent *hostent;
332 IO->ConnectMe = Msg->pCurrRelay;
335 EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
337 IO->Now - IO->DNS.Start);
339 hostent = Msg->HostLookup.VParsedDNSReply;
340 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
341 (hostent != NULL) ) {
342 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
343 if (Msg->pCurrRelay->IPv6) {
344 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
345 &hostent->h_addr_list[0],
346 sizeof(struct in6_addr));
348 Msg->pCurrRelay->Addr.sin6_family =
350 Msg->pCurrRelay->Addr.sin6_port =
351 htons(Msg->IO.ConnectMe->Port);
354 struct sockaddr_in *addr;
356 * Bypass the ns lookup result like this:
357 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
358 * addr->sin_addr.s_addr =
359 * htonl((uint32_t)&hostent->h_addr_list[0]);
362 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
364 memcpy(&addr->sin_addr.s_addr,
365 hostent->h_addr_list[0],
368 addr->sin_family = hostent->h_addrtype;
369 addr->sin_port = htons(Msg->IO.ConnectMe->Port);
371 Msg->mx_host = Msg->pCurrRelay->Host;
372 if (Msg->HostLookup.VParsedDNSReply != NULL) {
373 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
374 Msg->HostLookup.VParsedDNSReply = NULL;
376 return mx_connect_ip(IO);
379 if (Msg->HostLookup.VParsedDNSReply != NULL) {
380 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
381 Msg->HostLookup.VParsedDNSReply = NULL;
383 return FailOneAttempt(IO);
387 eNextState get_one_mx_host_ip(AsyncIO *IO)
389 SmtpOutMsg * Msg = IO->Data;
391 * here we start with the lookup of one host. it might be...
392 * - the relay host *sigh*
393 * - the direct hostname if there was no mx record
397 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
399 EVS_syslog(LOG_DEBUG,
400 "looking up %s-Record %s : %d ...\n",
401 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
402 Msg->pCurrRelay->Host,
403 Msg->pCurrRelay->Port);
405 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
406 Msg->pCurrRelay->Host,
409 get_one_mx_host_ip_done))
411 Msg->MyQEntry->Status = 5;
412 StrBufPrintf(Msg->MyQEntry->StatusMessage,
413 "No MX hosts found for <%s>", Msg->node);
414 Msg->IO.NextState = eTerminateConnection;
415 return IO->NextState;
417 IO->NextState = eReadDNSReply;
418 return IO->NextState;
422 /*****************************************************************************
423 * here we try to find out about the MX records for our recipients. *
424 *****************************************************************************/
425 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
427 SmtpOutMsg * Msg = IO->Data;
432 EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
434 IO->Now - IO->DNS.Start);
437 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
440 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
441 (IO->DNS.Query->VParsedDNSReply != NULL))
442 { /* ok, we found mx records. */
446 = IO->DNS.Query->VParsedDNSReply;
447 while (Msg->CurrMX) {
449 for (i = 0; i < 2; i++) {
452 p = (ParsedURL*) malloc(sizeof(ParsedURL));
453 memset(p, 0, sizeof(ParsedURL));
454 p->Priority = Msg->CurrMX->priority;
456 p->Port = DefaultMXPort;
458 p->Host = Msg->CurrMX->host;
462 ParsedURL *ppp = *pp;
464 while ((ppp->Next != NULL) &&
465 (ppp->Next->Priority <= p->Priority))
468 (ppp->Priority > p->Priority)) {
478 Msg->CurrMX = Msg->CurrMX->next;
480 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
482 else { /* else fall back to the plain hostname */
484 for (i = 0; i < 2; i++) {
487 p = (ParsedURL*) malloc(sizeof(ParsedURL));
488 memset(p, 0, sizeof(ParsedURL));
490 p->Port = DefaultMXPort;
497 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
499 if (Msg->MyQItem->FallBackHost != NULL)
501 Msg->MyQItem->FallBackHost->Next = *pp;
502 *pp = Msg->MyQItem->FallBackHost;
504 Msg->pCurrRelay = Msg->Relay;
505 return get_one_mx_host_ip(IO);
508 eNextState resolve_mx_records(AsyncIO *IO)
510 SmtpOutMsg * Msg = IO->Data;
512 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
513 /* start resolving MX records here. */
514 if (!QueueQuery(ns_t_mx,
518 smtp_resolve_mx_record_done))
520 Msg->MyQEntry->Status = 5;
521 StrBufPrintf(Msg->MyQEntry->StatusMessage,
522 "No MX hosts found for <%s>", Msg->node);
523 return IO->NextState;
525 Msg->IO.NextState = eReadDNSReply;
526 return IO->NextState;
531 /******************************************************************************
532 * so, we're going to start a SMTP delivery. lets get it on. *
533 ******************************************************************************/
535 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
536 MailQEntry *MyQEntry,
541 Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
544 memset(Msg, 0, sizeof(SmtpOutMsg));
547 Msg->MyQEntry = MyQEntry;
548 Msg->MyQItem = MyQItem;
549 Msg->pCurrRelay = MyQItem->URL;
551 InitIOStruct(&Msg->IO,
554 SMTP_C_ReadServerStatus,
556 SMTP_C_DispatchWriteDone,
557 SMTP_C_DispatchReadDone,
564 Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
569 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
570 MailQEntry *MyQEntry,
572 /*KeepMsgText allows us to use MsgText as ours.*/
578 SMTPC_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
580 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
582 SMTPC_syslog(LOG_DEBUG, "%s Failed to alocate message context.\n", __FUNCTION__);
584 FreeStrBuf (&MsgText);
587 if (KeepMsgText) Msg->msgtext = MsgText;
588 else Msg->msgtext = NewStrBufDup(MsgText);
590 if (smtp_resolve_recipients(Msg)) {
593 ((CitContext *)Msg->IO.CitContext)->cs_host,
595 sizeof(((CitContext *)
596 Msg->IO.CitContext)->cs_host));
598 SMTPC_syslog(LOG_DEBUG, "Starting: [%ld] <%s> CC <%d> \n",
599 Msg->MyQItem->MessageID,
600 ChrPtr(Msg->MyQEntry->Recipient),
601 ((CitContext*)Msg->IO.CitContext)->cs_pid);
602 if (Msg->pCurrRelay == NULL)
603 QueueEventContext(&Msg->IO,
605 else { /* oh... via relay host */
606 if (Msg->pCurrRelay->IsIP) {
607 QueueEventContext(&Msg->IO,
611 /* uneducated admin has chosen to
612 add DNS to the equation... */
613 QueueEventContext(&Msg->IO,
619 /* No recipients? well fail then. */
620 if (Msg->MyQEntry != NULL) {
621 Msg->MyQEntry->Status = 5;
622 StrBufPlain(Msg->MyQEntry->StatusMessage,
623 HKEY("Invalid Recipient!"));
625 FinalizeMessageSend_DB(&Msg->IO);
626 DeleteSmtpOutMsg(&Msg->IO);
635 /*****************************************************************************/
636 /* SMTP CLIENT DISPATCHER */
637 /*****************************************************************************/
639 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
641 double Timeout = 0.0;
642 AsyncIO *IO = &Msg->IO;
644 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
646 switch (NextTCPState) {
650 Timeout = SMTP_C_SendTimeouts[Msg->State];
651 if (Msg->State == eDATABody) {
652 /* if we're sending a huge message,
655 Timeout += StrLength(Msg->msgtext) / 512;
659 Timeout = SMTP_C_ReadTimeouts[Msg->State];
660 if (Msg->State == eDATATerminateBody) {
662 * some mailservers take a nap before accepting
663 * the message content inspection and such.
665 Timeout += StrLength(Msg->msgtext) / 512;
675 case eTerminateConnection:
679 SetNextTimeout(&Msg->IO, Timeout);
681 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
683 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
684 SmtpOutMsg *Msg = IO->Data;
687 rc = ReadHandlers[Msg->State](Msg);
691 SMTPSetTimeout(rc, Msg);
695 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
697 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
698 SmtpOutMsg *Msg = IO->Data;
701 rc = SendHandlers[Msg->State](Msg);
702 SMTPSetTimeout(rc, Msg);
707 /*****************************************************************************/
708 /* SMTP CLIENT ERROR CATCHERS */
709 /*****************************************************************************/
710 eNextState SMTP_C_Terminate(AsyncIO *IO)
712 SmtpOutMsg *Msg = IO->Data;
714 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
715 return FinalizeMessageSend(Msg);
717 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
719 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
720 return Terminate(IO);
722 eNextState SMTP_C_Timeout(AsyncIO *IO)
724 SmtpOutMsg *Msg = IO->Data;
726 Msg->MyQEntry->Status = 4;
727 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
728 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
729 if (Msg->State > eRCPT)
732 return FailOneAttempt(IO);
734 eNextState SMTP_C_ConnFail(AsyncIO *IO)
736 SmtpOutMsg *Msg = IO->Data;
738 Msg->MyQEntry->Status = 4;
739 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
740 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
741 return FailOneAttempt(IO);
743 eNextState SMTP_C_DNSFail(AsyncIO *IO)
745 SmtpOutMsg *Msg = IO->Data;
746 Msg->MyQEntry->Status = 4;
747 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
748 return FailOneAttempt(IO);
750 eNextState SMTP_C_Shutdown(AsyncIO *IO)
752 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
753 SmtpOutMsg *Msg = IO->Data;
755 Msg->MyQEntry->Status = 3;
756 StrBufPlain(Msg->MyQEntry->StatusMessage,
757 HKEY("server shutdown during message submit."));
758 return FinalizeMessageSend(Msg);
763 * @brief lineread Handler;
764 * understands when to read more SMTP lines, and when this is a one-lined reply.
766 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
768 eReadState Finished = eBufferNotEmpty;
770 while (Finished == eBufferNotEmpty) {
771 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
774 case eMustReadMore: /// read new from socket...
777 case eBufferNotEmpty: /* shouldn't happen... */
778 case eReadSuccess: /// done for now...
779 if (StrLength(IO->IOBuf) < 4)
781 if (ChrPtr(IO->IOBuf)[3] == '-')
782 Finished = eBufferNotEmpty;
786 case eReadFail: /// WHUT?
794 void LogDebugEnableSMTPClient(const int n)
796 SMTPClientDebugEnabled = n;
799 CTDL_MODULE_INIT(smtp_eventclient)
802 CtdlRegisterDebugFlagHook(HKEY("smtpeventclient"), LogDebugEnableSMTPClient, &SMTPClientDebugEnabled);
803 return "smtpeventclient";