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-2009 by the citadel.org team
25 * This program is free software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation; either version 3 of the License, or
28 * (at your option) any later version.
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.
35 * You should have received a copy of the GNU General Public License
36 * along with this program; if not, write to the Free Software
37 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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)
98 ares_free_data(Msg->AllMX);
99 if (Msg->HostLookup.VParsedDNSReply != NULL)
100 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
101 FreeURL(&Msg->Relay);
102 FreeStrBuf(&Msg->msgtext);
103 FreeAsyncIOContents(&Msg->IO);
104 memset (Msg, 0, sizeof(SmtpOutMsg)); /* just to be shure... */
108 eNextState SMTP_C_Shutdown(AsyncIO *IO);
109 eNextState SMTP_C_Timeout(AsyncIO *IO);
110 eNextState SMTP_C_ConnFail(AsyncIO *IO);
111 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
112 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
113 eNextState SMTP_C_DNSFail(AsyncIO *IO);
114 eNextState SMTP_C_Terminate(AsyncIO *IO);
115 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
117 eNextState mx_connect_ip(AsyncIO *IO);
118 eNextState get_one_mx_host_ip(AsyncIO *IO);
120 /******************************************************************************
121 * So, we're finished with sending (regardless of success or failure) *
122 * This Message might be referenced by several Queue-Items, if we're the last,*
123 * we need to free the memory and send bounce messages (on terminal failure) *
124 * else we just free our SMTP-Message struct. *
125 ******************************************************************************/
126 void FinalizeMessageSend(SmtpOutMsg *Msg)
128 int IDestructQueItem;
131 AsyncIO *IO = &Msg->IO;
132 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
134 IDestructQueItem = DecreaseQReference(Msg->MyQItem);
136 nRemain = CountActiveQueueEntries(Msg->MyQItem);
138 if ((nRemain > 0) || IDestructQueItem)
139 MsgData = SerializeQueueItem(Msg->MyQItem);
144 * Uncompleted delivery instructions remain, so delete the old
145 * instructions and replace with the updated ones.
147 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
148 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
150 if (IDestructQueItem)
151 smtpq_do_bounce(Msg->MyQItem,Msg->msgtext);
155 struct CtdlMessage *msg;
156 msg = malloc(sizeof(struct CtdlMessage));
157 memset(msg, 0, sizeof(struct CtdlMessage));
158 msg->cm_magic = CTDLMESSAGE_MAGIC;
159 msg->cm_anon_type = MES_NORMAL;
160 msg->cm_format_type = FMT_RFC822;
161 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
162 Msg->MyQItem->QueMsgID =
163 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
164 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
165 CtdlFreeMessage(msg);
168 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
169 &Msg->MyQItem->MessageID,
172 FreeStrBuf(&MsgData);
174 if (IDestructQueItem)
175 RemoveQItem(Msg->MyQItem);
177 RemoveContext(Msg->IO.CitContext);
178 DeleteSmtpOutMsg(Msg);
181 eNextState FailOneAttempt(AsyncIO *IO)
183 SmtpOutMsg *SendMsg = IO->Data;
185 if (SendMsg->MyQEntry->Status == 2)
189 * possible ways here:
190 * - connection timeout
193 StopClientWatchers(IO);
195 if (SendMsg->pCurrRelay != NULL)
196 SendMsg->pCurrRelay = SendMsg->pCurrRelay->Next;
198 if (SendMsg->pCurrRelay == NULL)
200 if (SendMsg->pCurrRelay->IsIP)
201 return mx_connect_ip(IO);
203 return get_one_mx_host_ip(IO);
207 void SetConnectStatus(AsyncIO *IO)
210 SmtpOutMsg *SendMsg = IO->Data;
216 if (IO->ConnectMe->IPv6) {
217 src = &IO->ConnectMe->Addr.sin6_addr;
220 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
222 src = &addr->sin_addr.s_addr;
225 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
230 if (SendMsg->mx_host == NULL)
231 SendMsg->mx_host = "<no MX-Record>";
233 EVS_syslog(LOG_DEBUG,
234 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
238 SendMsg->IO.ConnectMe->Port);
240 SendMsg->MyQEntry->Status = 5;
241 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
242 "Timeout while connecting %s [%s]:%d ",
245 SendMsg->IO.ConnectMe->Port);
246 SendMsg->IO.NextState = eConnect;
249 /*****************************************************************************
250 * So we connect our Relay IP here. *
251 *****************************************************************************/
252 eNextState mx_connect_ip(AsyncIO *IO)
254 SmtpOutMsg *SendMsg = IO->Data;
256 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
258 IO->ConnectMe = SendMsg->pCurrRelay;
259 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
261 SetConnectStatus(IO);
263 return InitEventIO(IO, SendMsg,
265 SMTP_C_ReadTimeouts[0],
269 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
271 SmtpOutMsg *SendMsg = IO->Data;
272 struct hostent *hostent;
276 hostent = SendMsg->HostLookup.VParsedDNSReply;
277 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
278 (hostent != NULL) ) {
279 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
280 if (SendMsg->pCurrRelay->IPv6) {
281 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
282 &hostent->h_addr_list[0],
283 sizeof(struct in6_addr));
285 SendMsg->pCurrRelay->Addr.sin6_family = hostent->h_addrtype;
286 SendMsg->pCurrRelay->Addr.sin6_port = htons(DefaultMXPort);
289 struct sockaddr_in *addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
290 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
291 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
292 memcpy(&addr->sin_addr.s_addr,
293 hostent->h_addr_list[0],
296 addr->sin_family = hostent->h_addrtype;
297 addr->sin_port = htons(DefaultMXPort);
300 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
301 return mx_connect_ip(IO);
303 else // TODO: here we need to find out whether there are more mx'es, backup relay, and so on
304 return FailOneAttempt(IO);
307 eNextState get_one_mx_host_ip(AsyncIO *IO)
309 SmtpOutMsg * SendMsg = IO->Data;
311 * here we start with the lookup of one host. it might be...
312 * - the relay host *sigh*
313 * - the direct hostname if there was no mx record
319 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
321 EVS_syslog(LOG_DEBUG,
322 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
324 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
325 SendMsg->pCurrRelay->Host,
326 SendMsg->pCurrRelay->Port);
328 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
329 SendMsg->pCurrRelay->Host,
331 &SendMsg->HostLookup,
332 get_one_mx_host_ip_done))
334 SendMsg->MyQEntry->Status = 5;
335 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
336 "No MX hosts found for <%s>", SendMsg->node);
337 SendMsg->IO.NextState = eTerminateConnection;
338 return IO->NextState;
340 IO->NextState = eReadDNSReply;
341 return IO->NextState;
345 /*****************************************************************************
346 * here we try to find out about the MX records for our recipients. *
347 *****************************************************************************/
348 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
350 SmtpOutMsg * SendMsg = IO->Data;
355 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
356 pp = &SendMsg->Relay;
357 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
360 if ((IO->DNSQuery->DNSStatus == ARES_SUCCESS) &&
361 (IO->DNSQuery->VParsedDNSReply != NULL))
362 { /* ok, we found mx records. */
363 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
365 SendMsg->CurrMX = SendMsg->AllMX
366 = IO->DNSQuery->VParsedDNSReply;
367 while (SendMsg->CurrMX) {
369 for (i = 0; i < 2; i++) {
372 p = (ParsedURL*) malloc(sizeof(ParsedURL));
373 memset(p, 0, sizeof(ParsedURL));
375 p->Port = DefaultMXPort;
377 p->Host = SendMsg->CurrMX->host;
382 SendMsg->CurrMX = SendMsg->CurrMX->next;
384 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
386 else { /* else fall back to the plain hostname */
388 for (i = 0; i < 2; i++) {
391 p = (ParsedURL*) malloc(sizeof(ParsedURL));
392 memset(p, 0, sizeof(ParsedURL));
394 p->Port = DefaultMXPort;
396 p->Host = SendMsg->node;
401 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
403 *pp = SendMsg->MyQItem->FallBackHost;
404 SendMsg->pCurrRelay = SendMsg->Relay;
405 return get_one_mx_host_ip(IO);
408 eNextState resolve_mx_records(AsyncIO *IO)
410 SmtpOutMsg * SendMsg = IO->Data;
412 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
413 /* start resolving MX records here. */
414 if (!QueueQuery(ns_t_mx,
418 smtp_resolve_mx_record_done))
420 SendMsg->MyQEntry->Status = 5;
421 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
422 "No MX hosts found for <%s>", SendMsg->node);
423 return IO->NextState;
425 SendMsg->IO.NextState = eReadDNSReply;
426 return IO->NextState;
431 /******************************************************************************
432 * so, we're going to start a SMTP delivery. lets get it on. *
433 ******************************************************************************/
435 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
436 MailQEntry *MyQEntry,
439 SmtpOutMsg * SendMsg;
441 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
442 memset(SendMsg, 0, sizeof(SmtpOutMsg));
444 SendMsg->n = MsgCount;
445 SendMsg->MyQEntry = MyQEntry;
446 SendMsg->MyQItem = MyQItem;
447 SendMsg->pCurrRelay = MyQItem->URL;
449 SendMsg->IO.Data = SendMsg;
451 SendMsg->IO.SendDone = SMTP_C_DispatchWriteDone;
452 SendMsg->IO.ReadDone = SMTP_C_DispatchReadDone;
453 SendMsg->IO.Terminate = SMTP_C_Terminate;
454 SendMsg->IO.LineReader = SMTP_C_ReadServerStatus;
455 SendMsg->IO.ConnFail = SMTP_C_ConnFail;
456 SendMsg->IO.DNSFail = SMTP_C_DNSFail;
457 SendMsg->IO.Timeout = SMTP_C_Timeout;
458 SendMsg->IO.ShutdownAbort = SMTP_C_Shutdown;
460 SendMsg->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
461 SendMsg->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
462 SendMsg->IO.IOBuf = NewStrBuf();
464 SendMsg->IO.NextState = eReadMessage;
469 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
470 MailQEntry *MyQEntry,
472 int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
477 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
479 SendMsg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
480 if (KeepMsgText) SendMsg->msgtext = MsgText;
481 else SendMsg->msgtext = NewStrBufDup(MsgText);
483 if (smtp_resolve_recipients(SendMsg)) {
485 SubC = CloneContext (CC);
486 SubC->session_specific_data = (char*) SendMsg;
487 SendMsg->IO.CitContext = SubC;
489 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> \n",
490 SendMsg->MyQItem->MessageID,
491 ChrPtr(SendMsg->MyQEntry->Recipient));
492 if (SendMsg->pCurrRelay == NULL)
493 QueueEventContext(&SendMsg->IO,
495 else { /* oh... via relay host */
496 if (SendMsg->pCurrRelay->IsIP) {
497 QueueEventContext(&SendMsg->IO,
500 else { /* uneducated admin has chosen to add DNS to the equation... */
501 QueueEventContext(&SendMsg->IO,
507 /* No recipients? well fail then. */
508 if ((SendMsg==NULL) ||
509 (SendMsg->MyQEntry == NULL)) {
510 SendMsg->MyQEntry->Status = 5;
511 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
512 HKEY("Invalid Recipient!"));
514 FinalizeMessageSend(SendMsg);
523 /*****************************************************************************/
524 /* SMTP CLIENT DISPATCHER */
525 /*****************************************************************************/
527 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
529 double Timeout = 0.0;
530 AsyncIO *IO = &pMsg->IO;
532 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
534 switch (NextTCPState) {
538 Timeout = SMTP_C_SendTimeouts[pMsg->State];
539 if (pMsg->State == eDATABody) {
540 /* if we're sending a huge message, we need more time. */
541 Timeout += StrLength(pMsg->msgtext) / 1024;
545 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
546 if (pMsg->State == eDATATerminateBody) {
548 * some mailservers take a nap before accepting the message
549 * content inspection and such.
551 Timeout += StrLength(pMsg->msgtext) / 1024;
561 case eTerminateConnection:
565 SetNextTimeout(&pMsg->IO, Timeout);
567 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
569 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
570 SmtpOutMsg *pMsg = IO->Data;
573 rc = ReadHandlers[pMsg->State](pMsg);
577 SMTPSetTimeout(rc, pMsg);
581 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
583 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
584 SmtpOutMsg *pMsg = IO->Data;
587 rc = SendHandlers[pMsg->State](pMsg);
588 SMTPSetTimeout(rc, pMsg);
593 /*****************************************************************************/
594 /* SMTP CLIENT ERROR CATCHERS */
595 /*****************************************************************************/
596 eNextState SMTP_C_Terminate(AsyncIO *IO)
598 SmtpOutMsg *pMsg = IO->Data;
600 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
601 FinalizeMessageSend(pMsg);
604 eNextState SMTP_C_Timeout(AsyncIO *IO)
606 SmtpOutMsg *pMsg = IO->Data;
608 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
609 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
610 return FailOneAttempt(IO);
612 eNextState SMTP_C_ConnFail(AsyncIO *IO)
614 SmtpOutMsg *pMsg = IO->Data;
616 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
617 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
618 return FailOneAttempt(IO);
620 eNextState SMTP_C_DNSFail(AsyncIO *IO)
622 SmtpOutMsg *pMsg = IO->Data;
624 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
625 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
626 return FailOneAttempt(IO);
628 eNextState SMTP_C_Shutdown(AsyncIO *IO)
630 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
631 SmtpOutMsg *pMsg = IO->Data;
633 pMsg->MyQEntry->Status = 3;
634 StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
635 FinalizeMessageSend(pMsg);
641 * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
643 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
645 eReadState Finished = eBufferNotEmpty;
647 while (Finished == eBufferNotEmpty) {
648 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
651 case eMustReadMore: /// read new from socket...
654 case eBufferNotEmpty: /* shouldn't happen... */
655 case eReadSuccess: /// done for now...
656 if (StrLength(IO->IOBuf) < 4)
658 if (ChrPtr(IO->IOBuf)[3] == '-')
659 Finished = eBufferNotEmpty;
663 case eReadFail: /// WHUT?
671 CTDL_MODULE_INIT(smtp_eventclient)
673 return "smtpeventclient";