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 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
122 eNextState mx_connect_ip(AsyncIO *IO);
123 eNextState get_one_mx_host_ip(AsyncIO *IO);
125 /******************************************************************************
126 * So, we're finished with sending (regardless of success or failure) *
127 * This Message might be referenced by several Queue-Items, if we're the last,*
128 * we need to free the memory and send bounce messages (on terminal failure) *
129 * else we just free our SMTP-Message struct. *
130 ******************************************************************************/
131 void FinalizeMessageSend(SmtpOutMsg *Msg)
133 int IDestructQueItem;
136 AsyncIO *IO = &Msg->IO;
138 IDestructQueItem = DecreaseQReference(Msg->MyQItem);
140 nRemain = CountActiveQueueEntries(Msg->MyQItem);
142 if (Msg->MyQEntry->Active &&
143 CheckQEntryIsBounce(Msg->MyQEntry))
145 /* are we casue for a bounce mail? */
146 Msg->MyQItem->SendBounceMail = 1;
149 if ((nRemain > 0) || IDestructQueItem)
150 MsgData = SerializeQueueItem(Msg->MyQItem);
155 * Uncompleted delivery instructions remain, so delete the old
156 * instructions and replace with the updated ones.
158 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
159 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
161 if (IDestructQueItem)
162 smtpq_do_bounce(Msg->MyQItem, Msg->msgtext);
166 struct CtdlMessage *msg;
167 msg = malloc(sizeof(struct CtdlMessage));
168 memset(msg, 0, sizeof(struct CtdlMessage));
169 msg->cm_magic = CTDLMESSAGE_MAGIC;
170 msg->cm_anon_type = MES_NORMAL;
171 msg->cm_format_type = FMT_RFC822;
172 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
173 msg->cm_fields['U'] = strdup("QMSG");
174 Msg->MyQItem->QueMsgID =
175 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
176 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
177 CtdlFreeMessage(msg);
180 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
181 &Msg->MyQItem->MessageID,
184 FreeStrBuf(&MsgData);
186 RemoveContext(Msg->IO.CitContext);
187 if (IDestructQueItem)
188 RemoveQItem(Msg->MyQItem);
189 DeleteSmtpOutMsg(Msg);
192 eNextState FailOneAttempt(AsyncIO *IO)
194 SmtpOutMsg *Msg = IO->Data;
196 if (Msg->MyQEntry->Status == 2)
200 * possible ways here:
201 * - connection timeout
202 * - dns lookup failed
204 StopClientWatchers(IO);
206 if (Msg->pCurrRelay != NULL)
207 Msg->pCurrRelay = Msg->pCurrRelay->Next;
209 if (Msg->pCurrRelay == NULL) {
210 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
213 if (Msg->pCurrRelay->IsIP) {
214 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
215 return mx_connect_ip(IO);
218 EVS_syslog(LOG_DEBUG,
219 "SMTP: %s resolving next MX Record\n",
221 return get_one_mx_host_ip(IO);
226 void SetConnectStatus(AsyncIO *IO)
228 SmtpOutMsg *Msg = IO->Data;
234 if (IO->ConnectMe->IPv6) {
235 src = &IO->ConnectMe->Addr.sin6_addr;
238 struct sockaddr_in *addr;
240 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
241 src = &addr->sin_addr.s_addr;
244 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
249 if (Msg->mx_host == NULL)
250 Msg->mx_host = "<no MX-Record>";
252 EVS_syslog(LOG_DEBUG,
253 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
257 Msg->IO.ConnectMe->Port);
259 Msg->MyQEntry->Status = 5;
260 StrBufPrintf(Msg->MyQEntry->StatusMessage,
261 "Timeout while connecting %s [%s]:%d ",
264 Msg->IO.ConnectMe->Port);
265 Msg->IO.NextState = eConnect;
268 /*****************************************************************************
269 * So we connect our Relay IP here. *
270 *****************************************************************************/
271 eNextState mx_connect_ip(AsyncIO *IO)
273 SmtpOutMsg *Msg = IO->Data;
275 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
277 IO->ConnectMe = Msg->pCurrRelay;
278 Msg->State = eConnectMX;
280 SetConnectStatus(IO);
282 return EvConnectSock(IO,
284 SMTP_C_ReadTimeouts[0],
288 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
290 SmtpOutMsg *Msg = IO->Data;
291 struct hostent *hostent;
295 hostent = Msg->HostLookup.VParsedDNSReply;
296 if ((Msg->HostLookup.DNSStatus == ARES_SUCCESS) &&
297 (hostent != NULL) ) {
298 memset(&Msg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
299 if (Msg->pCurrRelay->IPv6) {
300 memcpy(&Msg->pCurrRelay->Addr.sin6_addr.s6_addr,
301 &hostent->h_addr_list[0],
302 sizeof(struct in6_addr));
304 Msg->pCurrRelay->Addr.sin6_family =
306 Msg->pCurrRelay->Addr.sin6_port =
307 htons(DefaultMXPort);
310 struct sockaddr_in *addr;
312 * Bypass the ns lookup result like this:
313 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
314 * addr->sin_addr.s_addr =
315 * htonl((uint32_t)&hostent->h_addr_list[0]);
318 addr = (struct sockaddr_in*) &Msg->pCurrRelay->Addr;
320 memcpy(&addr->sin_addr.s_addr,
321 hostent->h_addr_list[0],
324 addr->sin_family = hostent->h_addrtype;
325 addr->sin_port = htons(DefaultMXPort);
327 Msg->mx_host = Msg->pCurrRelay->Host;
328 return mx_connect_ip(IO);
331 return FailOneAttempt(IO);
334 eNextState get_one_mx_host_ip(AsyncIO *IO)
336 SmtpOutMsg * Msg = IO->Data;
338 * here we start with the lookup of one host. it might be...
339 * - the relay host *sigh*
340 * - the direct hostname if there was no mx record
346 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
348 EVS_syslog(LOG_DEBUG,
349 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
351 (Msg->pCurrRelay->IPv6)? "aaaa": "a",
352 Msg->pCurrRelay->Host,
353 Msg->pCurrRelay->Port);
355 if (!QueueQuery((Msg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
356 Msg->pCurrRelay->Host,
359 get_one_mx_host_ip_done))
361 Msg->MyQEntry->Status = 5;
362 StrBufPrintf(Msg->MyQEntry->StatusMessage,
363 "No MX hosts found for <%s>", Msg->node);
364 Msg->IO.NextState = eTerminateConnection;
365 return IO->NextState;
367 IO->NextState = eReadDNSReply;
368 return IO->NextState;
372 /*****************************************************************************
373 * here we try to find out about the MX records for our recipients. *
374 *****************************************************************************/
375 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
377 SmtpOutMsg * Msg = IO->Data;
382 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
385 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
388 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
389 (IO->DNS.Query->VParsedDNSReply != NULL))
390 { /* ok, we found mx records. */
394 = IO->DNS.Query->VParsedDNSReply;
395 while (Msg->CurrMX) {
397 for (i = 0; i < 2; i++) {
400 p = (ParsedURL*) malloc(sizeof(ParsedURL));
401 memset(p, 0, sizeof(ParsedURL));
402 p->Priority = Msg->CurrMX->priority;
404 p->Port = DefaultMXPort;
406 p->Host = Msg->CurrMX->host;
410 ParsedURL *ppp = *pp;
412 while ((ppp->Next != NULL) &&
413 (ppp->Next->Priority <= p->Priority))
416 (ppp->Priority > p->Priority)) {
426 Msg->CurrMX = Msg->CurrMX->next;
428 Msg->CXFlags = Msg->CXFlags & F_HAVE_MX;
430 else { /* else fall back to the plain hostname */
432 for (i = 0; i < 2; i++) {
435 p = (ParsedURL*) malloc(sizeof(ParsedURL));
436 memset(p, 0, sizeof(ParsedURL));
438 p->Port = DefaultMXPort;
445 Msg->CXFlags = Msg->CXFlags & F_DIRECT;
447 if (Msg->MyQItem->FallBackHost != NULL)
449 Msg->MyQItem->FallBackHost->Next = *pp;
450 *pp = Msg->MyQItem->FallBackHost;
452 Msg->pCurrRelay = Msg->Relay;
453 return get_one_mx_host_ip(IO);
456 eNextState resolve_mx_records(AsyncIO *IO)
458 SmtpOutMsg * Msg = IO->Data;
460 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
461 /* start resolving MX records here. */
462 if (!QueueQuery(ns_t_mx,
466 smtp_resolve_mx_record_done))
468 Msg->MyQEntry->Status = 5;
469 StrBufPrintf(Msg->MyQEntry->StatusMessage,
470 "No MX hosts found for <%s>", Msg->node);
471 return IO->NextState;
473 Msg->IO.NextState = eReadDNSReply;
474 return IO->NextState;
479 /******************************************************************************
480 * so, we're going to start a SMTP delivery. lets get it on. *
481 ******************************************************************************/
483 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
484 MailQEntry *MyQEntry,
489 Msg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
490 memset(Msg, 0, sizeof(SmtpOutMsg));
493 Msg->MyQEntry = MyQEntry;
494 Msg->MyQItem = MyQItem;
495 Msg->pCurrRelay = MyQItem->URL;
497 InitIOStruct(&Msg->IO,
500 SMTP_C_ReadServerStatus,
502 SMTP_C_DispatchWriteDone,
503 SMTP_C_DispatchReadDone,
509 Msg->IO.ErrMsg = Msg->MyQEntry->StatusMessage;
514 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
515 MailQEntry *MyQEntry,
517 /*KeepMsgText allows us to use MsgText as ours.*/
523 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
525 Msg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
526 if (KeepMsgText) Msg->msgtext = MsgText;
527 else Msg->msgtext = NewStrBufDup(MsgText);
529 if (smtp_resolve_recipients(Msg)) {
532 ((CitContext *)Msg->IO.CitContext)->cs_host,
534 sizeof(((CitContext *)
535 Msg->IO.CitContext)->cs_host));
537 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
538 Msg->MyQItem->MessageID,
539 ChrPtr(Msg->MyQEntry->Recipient),
540 ((CitContext*)Msg->IO.CitContext)->cs_pid);
541 if (Msg->pCurrRelay == NULL)
542 QueueEventContext(&Msg->IO,
544 else { /* oh... via relay host */
545 if (Msg->pCurrRelay->IsIP) {
546 QueueEventContext(&Msg->IO,
550 /* uneducated admin has chosen to
551 add DNS to the equation... */
552 QueueEventContext(&Msg->IO,
558 /* No recipients? well fail then. */
560 (Msg->MyQEntry == NULL)) {
561 Msg->MyQEntry->Status = 5;
562 StrBufPlain(Msg->MyQEntry->StatusMessage,
563 HKEY("Invalid Recipient!"));
565 FinalizeMessageSend(Msg);
574 /*****************************************************************************/
575 /* SMTP CLIENT DISPATCHER */
576 /*****************************************************************************/
578 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *Msg)
580 double Timeout = 0.0;
581 AsyncIO *IO = &Msg->IO;
583 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
585 switch (NextTCPState) {
589 Timeout = SMTP_C_SendTimeouts[Msg->State];
590 if (Msg->State == eDATABody) {
591 /* if we're sending a huge message,
594 Timeout += StrLength(Msg->msgtext) / 512;
598 Timeout = SMTP_C_ReadTimeouts[Msg->State];
599 if (Msg->State == eDATATerminateBody) {
601 * some mailservers take a nap before accepting
602 * the message content inspection and such.
604 Timeout += StrLength(Msg->msgtext) / 512;
614 case eTerminateConnection:
618 SetNextTimeout(&Msg->IO, Timeout);
620 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
622 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
623 SmtpOutMsg *Msg = IO->Data;
626 rc = ReadHandlers[Msg->State](Msg);
630 SMTPSetTimeout(rc, Msg);
634 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
636 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
637 SmtpOutMsg *Msg = IO->Data;
640 rc = SendHandlers[Msg->State](Msg);
641 SMTPSetTimeout(rc, Msg);
646 /*****************************************************************************/
647 /* SMTP CLIENT ERROR CATCHERS */
648 /*****************************************************************************/
649 eNextState SMTP_C_Terminate(AsyncIO *IO)
651 SmtpOutMsg *Msg = IO->Data;
653 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
654 FinalizeMessageSend(Msg);
657 eNextState SMTP_C_Timeout(AsyncIO *IO)
659 SmtpOutMsg *Msg = IO->Data;
661 Msg->MyQEntry->Status = 4;
662 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
663 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
664 if (Msg->State > eRCPT)
667 return FailOneAttempt(IO);
669 eNextState SMTP_C_ConnFail(AsyncIO *IO)
671 SmtpOutMsg *Msg = IO->Data;
673 Msg->MyQEntry->Status = 4;
674 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
675 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[Msg->State]));
676 return FailOneAttempt(IO);
678 eNextState SMTP_C_DNSFail(AsyncIO *IO)
680 SmtpOutMsg *Msg = IO->Data;
681 Msg->MyQEntry->Status = 4;
682 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
683 return FailOneAttempt(IO);
685 eNextState SMTP_C_Shutdown(AsyncIO *IO)
687 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
688 SmtpOutMsg *Msg = IO->Data;
690 Msg->MyQEntry->Status = 3;
691 StrBufPlain(Msg->MyQEntry->StatusMessage,
692 HKEY("server shutdown during message submit."));
693 FinalizeMessageSend(Msg);
699 * @brief lineread Handler;
700 * understands when to read more SMTP lines, and when this is a one-lined reply.
702 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
704 eReadState Finished = eBufferNotEmpty;
706 while (Finished == eBufferNotEmpty) {
707 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
710 case eMustReadMore: /// read new from socket...
713 case eBufferNotEmpty: /* shouldn't happen... */
714 case eReadSuccess: /// done for now...
715 if (StrLength(IO->IOBuf) < 4)
717 if (ChrPtr(IO->IOBuf)[3] == '-')
718 Finished = eBufferNotEmpty;
722 case eReadFail: /// WHUT?
730 CTDL_MODULE_INIT(smtp_eventclient)
732 return "smtpeventclient";