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);
158 if (Msg->MyQEntry->Active &&
159 CheckQEntryIsBounce(Msg->MyQEntry))
161 /* are we casue for a bounce mail? */
162 Msg->MyQItem->SendBounceMail |= (1<<Msg->MyQEntry->Status);
165 if ((Msg->nRemain > 0) || Msg->IDestructQueItem)
166 Msg->QMsgData = SerializeQueueItem(Msg->MyQItem);
168 Msg->QMsgData = NULL;
171 * Uncompleted delivery instructions remain, so delete the old
172 * instructions and replace with the updated ones.
174 EVS_syslog(LOG_DEBUG, "%ld", Msg->MyQItem->QueMsgID);
175 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
176 Msg->MyQItem->QueMsgID = -1;
178 if (Msg->IDestructQueItem)
179 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
181 if (Msg->nRemain > 0)
183 struct CtdlMessage *msg;
184 msg = malloc(sizeof(struct CtdlMessage));
185 memset(msg, 0, sizeof(struct CtdlMessage));
186 msg->cm_magic = CTDLMESSAGE_MAGIC;
187 msg->cm_anon_type = MES_NORMAL;
188 msg->cm_format_type = FMT_RFC822;
189 msg->cm_fields['M'] = SmashStrBuf(&Msg->QMsgData);
190 msg->cm_fields['U'] = strdup("QMSG");
191 Msg->MyQItem->QueMsgID =
192 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
193 EVS_syslog(LOG_DEBUG, "%ld", Msg->MyQItem->QueMsgID);
194 CtdlFreeMessage(msg);
197 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
198 &Msg->MyQItem->MessageID,
201 FreeStrBuf(&Msg->QMsgData);
204 RemoveContext(Msg->IO.CitContext);
208 eNextState Terminate(AsyncIO *IO)
210 SmtpOutMsg *Msg = IO->Data;
212 if (Msg->IDestructQueItem)
213 RemoveQItem(Msg->MyQItem);
215 DeleteSmtpOutMsg(Msg);
218 eNextState FinalizeMessageSend(SmtpOutMsg *Msg)
220 /* hand over to DB Queue */
221 return QueueDBOperation(&Msg->IO, FinalizeMessageSend_DB);
224 eNextState FailOneAttempt(AsyncIO *IO)
226 SmtpOutMsg *Msg = IO->Data;
228 if (Msg->MyQEntry->Status == 2)
232 * possible ways here:
233 * - connection timeout
234 * - dns lookup failed
236 StopClientWatchers(IO);
238 if (Msg->pCurrRelay != NULL)
239 Msg->pCurrRelay = Msg->pCurrRelay->Next;
241 if (Msg->pCurrRelay == NULL) {
242 EVS_syslog(LOG_DEBUG, "%s Aborting\n", __FUNCTION__);
245 if (Msg->pCurrRelay->IsIP) {
246 EVS_syslog(LOG_DEBUG, "%s connecting IP\n", __FUNCTION__);
247 return mx_connect_ip(IO);
250 EVS_syslog(LOG_DEBUG,
251 "%s resolving next MX Record\n",
253 return get_one_mx_host_ip(IO);
258 void SetConnectStatus(AsyncIO *IO)
260 SmtpOutMsg *Msg = IO->Data;
266 if (IO->ConnectMe->IPv6) {
267 src = &IO->ConnectMe->Addr.sin6_addr;
270 struct sockaddr_in *addr;
272 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
273 src = &addr->sin_addr.s_addr;
276 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
281 if (Msg->mx_host == NULL)
282 Msg->mx_host = "<no MX-Record>";
285 "connecting to %s [%s]:%d ...\n",
288 Msg->IO.ConnectMe->Port);
290 Msg->MyQEntry->Status = 4;
291 StrBufPrintf(Msg->MyQEntry->StatusMessage,
292 "Timeout while connecting %s [%s]:%d ",
295 Msg->IO.ConnectMe->Port);
296 Msg->IO.NextState = eConnect;
299 /*****************************************************************************
300 * So we connect our Relay IP here. *
301 *****************************************************************************/
302 eNextState mx_connect_ip(AsyncIO *IO)
304 SmtpOutMsg *Msg = IO->Data;
306 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
308 IO->ConnectMe = Msg->pCurrRelay;
309 Msg->State = eConnectMX;
311 SetConnectStatus(IO);
313 return EvConnectSock(IO,
315 SMTP_C_ReadTimeouts[0],
319 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
321 SmtpOutMsg *Msg = IO->Data;
322 struct hostent *hostent;
324 IO->ConnectMe = Msg->pCurrRelay;
327 EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
329 IO->Now - IO->DNS.Start);
331 hostent = Msg->HostLookup.VParsedDNSReply;
332 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
333 (hostent != NULL) ) {
334 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
335 if (Msg->pCurrRelay->IPv6) {
336 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
337 &hostent->h_addr_list[0],
338 sizeof(struct in6_addr));
340 Msg->pCurrRelay->Addr.sin6_family =
342 Msg->pCurrRelay->Addr.sin6_port =
343 htons(Msg->IO.ConnectMe->Port);
346 struct sockaddr_in *addr;
348 * Bypass the ns lookup result like this:
349 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
350 * addr->sin_addr.s_addr =
351 * htonl((uint32_t)&hostent->h_addr_list[0]);
354 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
356 memcpy(&addr->sin_addr.s_addr,
357 hostent->h_addr_list[0],
360 addr->sin_family = hostent->h_addrtype;
361 addr->sin_port = htons(Msg->IO.ConnectMe->Port);
363 Msg->mx_host = Msg->pCurrRelay->Host;
364 if (Msg->HostLookup.VParsedDNSReply != NULL) {
365 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
366 Msg->HostLookup.VParsedDNSReply = NULL;
368 return mx_connect_ip(IO);
371 if (Msg->HostLookup.VParsedDNSReply != NULL) {
372 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
373 Msg->HostLookup.VParsedDNSReply = NULL;
375 return FailOneAttempt(IO);
379 eNextState get_one_mx_host_ip(AsyncIO *IO)
381 SmtpOutMsg * Msg = IO->Data;
383 * here we start with the lookup of one host. it might be...
384 * - the relay host *sigh*
385 * - the direct hostname if there was no mx record
389 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
391 EVS_syslog(LOG_DEBUG,
392 "looking up %s-Record %s : %d ...\n",
393 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
394 Msg->pCurrRelay->Host,
395 Msg->pCurrRelay->Port);
397 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
398 Msg->pCurrRelay->Host,
401 get_one_mx_host_ip_done))
403 Msg->MyQEntry->Status = 5;
404 StrBufPrintf(Msg->MyQEntry->StatusMessage,
405 "No MX hosts found for <%s>", Msg->node);
406 Msg->IO.NextState = eTerminateConnection;
407 return IO->NextState;
409 IO->NextState = eReadDNSReply;
410 return IO->NextState;
414 /*****************************************************************************
415 * here we try to find out about the MX records for our recipients. *
416 *****************************************************************************/
417 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
419 SmtpOutMsg * Msg = IO->Data;
424 EVS_syslog(LOG_DEBUG, "%s Time[%fs]\n",
426 IO->Now - IO->DNS.Start);
429 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
432 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
433 (IO->DNS.Query->VParsedDNSReply != NULL))
434 { /* ok, we found mx records. */
438 = IO->DNS.Query->VParsedDNSReply;
439 while (Msg->CurrMX) {
441 for (i = 0; i < 2; i++) {
444 p = (ParsedURL*) malloc(sizeof(ParsedURL));
445 memset(p, 0, sizeof(ParsedURL));
446 p->Priority = Msg->CurrMX->priority;
448 p->Port = DefaultMXPort;
450 p->Host = Msg->CurrMX->host;
454 ParsedURL *ppp = *pp;
456 while ((ppp->Next != NULL) &&
457 (ppp->Next->Priority <= p->Priority))
460 (ppp->Priority > p->Priority)) {
470 Msg->CurrMX = Msg->CurrMX->next;
472 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
474 else { /* else fall back to the plain hostname */
476 for (i = 0; i < 2; i++) {
479 p = (ParsedURL*) malloc(sizeof(ParsedURL));
480 memset(p, 0, sizeof(ParsedURL));
482 p->Port = DefaultMXPort;
489 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
491 if (Msg->MyQItem->FallBackHost != NULL)
493 Msg->MyQItem->FallBackHost->Next = *pp;
494 *pp = Msg->MyQItem->FallBackHost;
496 Msg->pCurrRelay = Msg->Relay;
497 return get_one_mx_host_ip(IO);
500 eNextState resolve_mx_records(AsyncIO *IO)
502 SmtpOutMsg * Msg = IO->Data;
504 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
505 /* start resolving MX records here. */
506 if (!QueueQuery(ns_t_mx,
510 smtp_resolve_mx_record_done))
512 Msg->MyQEntry->Status = 5;
513 StrBufPrintf(Msg->MyQEntry->StatusMessage,
514 "No MX hosts found for <%s>", Msg->node);
515 return IO->NextState;
517 Msg->IO.NextState = eReadDNSReply;
518 return IO->NextState;
523 /******************************************************************************
524 * so, we're going to start a SMTP delivery. lets get it on. *
525 ******************************************************************************/
527 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
528 MailQEntry *MyQEntry,
533 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 SMTPC_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
572 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
574 SMTPC_syslog(LOG_DEBUG, "%s Failed to alocate message context.\n", __FUNCTION__);
576 FreeStrBuf (&MsgText);
579 if (KeepMsgText) Msg->msgtext = MsgText;
580 else Msg->msgtext = NewStrBufDup(MsgText);
582 if (smtp_resolve_recipients(Msg)) {
585 ((CitContext *)Msg->IO.CitContext)->cs_host,
587 sizeof(((CitContext *)
588 Msg->IO.CitContext)->cs_host));
590 SMTPC_syslog(LOG_DEBUG, "Starting: [%ld] <%s> CC <%d> \n",
591 Msg->MyQItem->MessageID,
592 ChrPtr(Msg->MyQEntry->Recipient),
593 ((CitContext*)Msg->IO.CitContext)->cs_pid);
594 if (Msg->pCurrRelay == NULL)
595 QueueEventContext(&Msg->IO,
597 else { /* oh... via relay host */
598 if (Msg->pCurrRelay->IsIP) {
599 QueueEventContext(&Msg->IO,
603 /* uneducated admin has chosen to
604 add DNS to the equation... */
605 QueueEventContext(&Msg->IO,
611 /* No recipients? well fail then. */
612 if (Msg->MyQEntry != NULL) {
613 Msg->MyQEntry->Status = 5;
614 StrBufPlain(Msg->MyQEntry->StatusMessage,
615 HKEY("Invalid Recipient!"));
617 FinalizeMessageSend_DB(&Msg->IO);
618 DeleteSmtpOutMsg(&Msg->IO);
627 /*****************************************************************************/
628 /* SMTP CLIENT DISPATCHER */
629 /*****************************************************************************/
631 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
633 double Timeout = 0.0;
634 AsyncIO *IO = &Msg->IO;
636 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
638 switch (NextTCPState) {
642 Timeout = SMTP_C_SendTimeouts[Msg->State];
643 if (Msg->State == eDATABody) {
644 /* if we're sending a huge message,
647 Timeout += StrLength(Msg->msgtext) / 512;
651 Timeout = SMTP_C_ReadTimeouts[Msg->State];
652 if (Msg->State == eDATATerminateBody) {
654 * some mailservers take a nap before accepting
655 * the message content inspection and such.
657 Timeout += StrLength(Msg->msgtext) / 512;
667 case eTerminateConnection:
671 SetNextTimeout(&Msg->IO, Timeout);
673 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
675 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
676 SmtpOutMsg *Msg = IO->Data;
679 rc = ReadHandlers[Msg->State](Msg);
683 SMTPSetTimeout(rc, Msg);
687 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
689 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
690 SmtpOutMsg *Msg = IO->Data;
693 rc = SendHandlers[Msg->State](Msg);
694 SMTPSetTimeout(rc, Msg);
699 /*****************************************************************************/
700 /* SMTP CLIENT ERROR CATCHERS */
701 /*****************************************************************************/
702 eNextState SMTP_C_Terminate(AsyncIO *IO)
704 SmtpOutMsg *Msg = IO->Data;
706 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
707 return FinalizeMessageSend(Msg);
709 eNextState SMTP_C_TerminateDB(AsyncIO *IO)
711 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
712 return Terminate(IO);
714 eNextState SMTP_C_Timeout(AsyncIO *IO)
716 SmtpOutMsg *Msg = IO->Data;
718 Msg->MyQEntry->Status = 4;
719 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
720 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
721 if (Msg->State > eRCPT)
724 return FailOneAttempt(IO);
726 eNextState SMTP_C_ConnFail(AsyncIO *IO)
728 SmtpOutMsg *Msg = IO->Data;
730 Msg->MyQEntry->Status = 4;
731 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
732 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
733 return FailOneAttempt(IO);
735 eNextState SMTP_C_DNSFail(AsyncIO *IO)
737 SmtpOutMsg *Msg = IO->Data;
738 Msg->MyQEntry->Status = 4;
739 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
740 return FailOneAttempt(IO);
742 eNextState SMTP_C_Shutdown(AsyncIO *IO)
744 EVS_syslog(LOG_DEBUG, "%s\n", __FUNCTION__);
745 SmtpOutMsg *Msg = IO->Data;
747 Msg->MyQEntry->Status = 3;
748 StrBufPlain(Msg->MyQEntry->StatusMessage,
749 HKEY("server shutdown during message submit."));
750 return FinalizeMessageSend(Msg);
755 * @brief lineread Handler;
756 * understands when to read more SMTP lines, and when this is a one-lined reply.
758 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
760 eReadState Finished = eBufferNotEmpty;
762 while (Finished == eBufferNotEmpty) {
763 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
766 case eMustReadMore: /// read new from socket...
769 case eBufferNotEmpty: /* shouldn't happen... */
770 case eReadSuccess: /// done for now...
771 if (StrLength(IO->IOBuf) < 4)
773 if (ChrPtr(IO->IOBuf)[3] == '-')
774 Finished = eBufferNotEmpty;
778 case eReadFail: /// WHUT?
786 void LogDebugEnableSMTPClient(const int n)
788 SMTPClientDebugEnabled = n;
791 CTDL_MODULE_INIT(smtp_eventclient)
794 CtdlRegisterDebugFlagHook(HKEY("smtpeventclient"), LogDebugEnableSMTPClient, &SMTPClientDebugEnabled);
795 return "smtpeventclient";