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 AsyncIO *IO = &Msg->IO;
129 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
131 if (DecreaseQReference(Msg->MyQItem))
136 nRemain = CountActiveQueueEntries(Msg->MyQItem);
138 MsgData = SerializeQueueItem(Msg->MyQItem);
140 * Uncompleted delivery instructions remain, so delete the old
141 * instructions and replace with the updated ones.
143 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
144 smtpq_do_bounce(Msg->MyQItem,
147 struct CtdlMessage *msg;
148 msg = malloc(sizeof(struct CtdlMessage));
149 memset(msg, 0, sizeof(struct CtdlMessage));
150 msg->cm_magic = CTDLMESSAGE_MAGIC;
151 msg->cm_anon_type = MES_NORMAL;
152 msg->cm_format_type = FMT_RFC822;
153 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
154 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
155 CtdlFreeMessage(msg);
158 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->MessageID, 1, "");
159 FreeStrBuf(&MsgData);
162 RemoveQItem(Msg->MyQItem);
165 RemoveContext(Msg->IO.CitContext);
166 DeleteSmtpOutMsg(Msg);
169 eNextState FailOneAttempt(AsyncIO *IO)
171 SmtpOutMsg *SendMsg = IO->Data;
173 if (SendMsg->MyQEntry->Status == 2)
177 * possible ways here:
178 * - connection timeout
181 StopClientWatchers(IO);
183 if (SendMsg->pCurrRelay != NULL)
184 SendMsg->pCurrRelay = SendMsg->pCurrRelay->Next;
186 if (SendMsg->pCurrRelay == NULL)
188 if (SendMsg->pCurrRelay->IsIP)
189 return mx_connect_ip(IO);
191 return get_one_mx_host_ip(IO);
195 void SetConnectStatus(AsyncIO *IO)
198 SmtpOutMsg *SendMsg = IO->Data;
204 if (IO->ConnectMe->IPv6) {
205 src = &IO->ConnectMe->Addr.sin6_addr;
208 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
210 src = &addr->sin_addr.s_addr;
213 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
218 if (SendMsg->mx_host == NULL)
219 SendMsg->mx_host = "<no MX-Record>";
222 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
226 SendMsg->IO.ConnectMe->Port);
228 SendMsg->MyQEntry->Status = 5;
229 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
230 "Timeout while connecting %s [%s]:%d ",
233 SendMsg->IO.ConnectMe->Port);
234 SendMsg->IO.NextState = eConnect;
237 /*****************************************************************************
238 * So we connect our Relay IP here. *
239 *****************************************************************************/
240 eNextState mx_connect_ip(AsyncIO *IO)
242 SmtpOutMsg *SendMsg = IO->Data;
244 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
246 IO->ConnectMe = SendMsg->pCurrRelay;
247 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
249 SetConnectStatus(IO);
251 return InitEventIO(IO, SendMsg,
253 SMTP_C_ReadTimeouts[0],
257 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
259 SmtpOutMsg *SendMsg = IO->Data;
260 struct hostent *hostent;
264 hostent = SendMsg->HostLookup.VParsedDNSReply;
265 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
266 (hostent != NULL) ) {
267 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
268 if (SendMsg->pCurrRelay->IPv6) {
269 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
270 &hostent->h_addr_list[0],
271 sizeof(struct in6_addr));
273 SendMsg->pCurrRelay->Addr.sin6_family = hostent->h_addrtype;
274 SendMsg->pCurrRelay->Addr.sin6_port = htons(DefaultMXPort);
277 struct sockaddr_in *addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
278 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
279 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
280 memcpy(&addr->sin_addr.s_addr,
281 hostent->h_addr_list[0],
284 addr->sin_family = hostent->h_addrtype;
285 addr->sin_port = htons(DefaultMXPort);
288 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
289 return mx_connect_ip(IO);
291 else // TODO: here we need to find out whether there are more mx'es, backup relay, and so on
292 return FailOneAttempt(IO);
295 eNextState get_one_mx_host_ip(AsyncIO *IO)
297 SmtpOutMsg * SendMsg = IO->Data;
299 * here we start with the lookup of one host. it might be...
300 * - the relay host *sigh*
301 * - the direct hostname if there was no mx record
307 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
310 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
312 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
313 SendMsg->pCurrRelay->Host,
314 SendMsg->pCurrRelay->Port);
316 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
317 SendMsg->pCurrRelay->Host,
319 &SendMsg->HostLookup,
320 get_one_mx_host_ip_done))
322 SendMsg->MyQEntry->Status = 5;
323 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
324 "No MX hosts found for <%s>", SendMsg->node);
325 SendMsg->IO.NextState = eTerminateConnection;
326 return IO->NextState;
328 IO->NextState = eReadDNSReply;
329 return IO->NextState;
333 /*****************************************************************************
334 * here we try to find out about the MX records for our recipients. *
335 *****************************************************************************/
336 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
338 SmtpOutMsg * SendMsg = IO->Data;
343 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
344 pp = &SendMsg->Relay;
345 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
348 if ((IO->DNSQuery->DNSStatus == ARES_SUCCESS) &&
349 (IO->DNSQuery->VParsedDNSReply != NULL))
350 { /* ok, we found mx records. */
351 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
353 SendMsg->CurrMX = SendMsg->AllMX
354 = IO->DNSQuery->VParsedDNSReply;
355 while (SendMsg->CurrMX) {
357 for (i = 0; i < 2; i++) {
360 p = (ParsedURL*) malloc(sizeof(ParsedURL));
361 memset(p, 0, sizeof(ParsedURL));
363 p->Port = DefaultMXPort;
365 p->Host = SendMsg->CurrMX->host;
370 SendMsg->CurrMX = SendMsg->CurrMX->next;
372 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
374 else { /* else fall back to the plain hostname */
376 for (i = 0; i < 2; i++) {
379 p = (ParsedURL*) malloc(sizeof(ParsedURL));
380 memset(p, 0, sizeof(ParsedURL));
382 p->Port = DefaultMXPort;
384 p->Host = SendMsg->node;
389 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
391 *pp = SendMsg->MyQItem->FallBackHost;
392 SendMsg->pCurrRelay = SendMsg->Relay;
393 return get_one_mx_host_ip(IO);
396 eNextState resolve_mx_records(AsyncIO *IO)
398 SmtpOutMsg * SendMsg = IO->Data;
400 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
401 /* start resolving MX records here. */
402 if (!QueueQuery(ns_t_mx,
406 smtp_resolve_mx_record_done))
408 SendMsg->MyQEntry->Status = 5;
409 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
410 "No MX hosts found for <%s>", SendMsg->node);
411 return IO->NextState;
413 SendMsg->IO.NextState = eReadDNSReply;
414 return IO->NextState;
419 /******************************************************************************
420 * so, we're going to start a SMTP delivery. lets get it on. *
421 ******************************************************************************/
423 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
424 MailQEntry *MyQEntry,
427 SmtpOutMsg * SendMsg;
429 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
430 memset(SendMsg, 0, sizeof(SmtpOutMsg));
432 SendMsg->n = MsgCount;
433 SendMsg->MyQEntry = MyQEntry;
434 SendMsg->MyQItem = MyQItem;
435 SendMsg->pCurrRelay = MyQItem->URL;
437 SendMsg->IO.Data = SendMsg;
439 SendMsg->IO.SendDone = SMTP_C_DispatchWriteDone;
440 SendMsg->IO.ReadDone = SMTP_C_DispatchReadDone;
441 SendMsg->IO.Terminate = SMTP_C_Terminate;
442 SendMsg->IO.LineReader = SMTP_C_ReadServerStatus;
443 SendMsg->IO.ConnFail = SMTP_C_ConnFail;
444 SendMsg->IO.DNSFail = SMTP_C_DNSFail;
445 SendMsg->IO.Timeout = SMTP_C_Timeout;
446 SendMsg->IO.ShutdownAbort = SMTP_C_Shutdown;
448 SendMsg->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
449 SendMsg->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
450 SendMsg->IO.IOBuf = NewStrBuf();
452 SendMsg->IO.NextState = eReadMessage;
457 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
458 MailQEntry *MyQEntry,
460 int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
465 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
467 SendMsg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
468 if (KeepMsgText) SendMsg->msgtext = MsgText;
469 else SendMsg->msgtext = NewStrBufDup(MsgText);
471 if (smtp_resolve_recipients(SendMsg)) {
473 SubC = CloneContext (CC);
474 SubC->session_specific_data = (char*) SendMsg;
475 SendMsg->IO.CitContext = SubC;
477 if (SendMsg->pCurrRelay == NULL)
478 QueueEventContext(&SendMsg->IO,
480 else { /* oh... via relay host */
481 if (SendMsg->pCurrRelay->IsIP) {
482 QueueEventContext(&SendMsg->IO,
485 else { /* uneducated admin has chosen to add DNS to the equation... */
486 QueueEventContext(&SendMsg->IO,
492 /* No recipients? well fail then. */
493 if ((SendMsg==NULL) ||
494 (SendMsg->MyQEntry == NULL)) {
495 SendMsg->MyQEntry->Status = 5;
496 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
497 HKEY("Invalid Recipient!"));
499 FinalizeMessageSend(SendMsg);
508 /*****************************************************************************/
509 /* SMTP CLIENT DISPATCHER */
510 /*****************************************************************************/
512 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
514 double Timeout = 0.0;
515 AsyncIO *IO = &pMsg->IO;
517 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
519 switch (NextTCPState) {
523 Timeout = SMTP_C_SendTimeouts[pMsg->State];
524 if (pMsg->State == eDATABody) {
525 /* if we're sending a huge message, we need more time. */
526 Timeout += StrLength(pMsg->msgtext) / 1024;
530 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
531 if (pMsg->State == eDATATerminateBody) {
533 * some mailservers take a nap before accepting the message
534 * content inspection and such.
536 Timeout += StrLength(pMsg->msgtext) / 1024;
546 case eTerminateConnection:
550 SetNextTimeout(&pMsg->IO, Timeout);
552 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
554 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
555 SmtpOutMsg *pMsg = IO->Data;
558 rc = ReadHandlers[pMsg->State](pMsg);
560 SMTPSetTimeout(rc, pMsg);
563 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
565 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
566 SmtpOutMsg *pMsg = IO->Data;
569 rc = SendHandlers[pMsg->State](pMsg);
570 SMTPSetTimeout(rc, pMsg);
575 /*****************************************************************************/
576 /* SMTP CLIENT ERROR CATCHERS */
577 /*****************************************************************************/
578 eNextState SMTP_C_Terminate(AsyncIO *IO)
580 SmtpOutMsg *pMsg = IO->Data;
582 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
583 FinalizeMessageSend(pMsg);
586 eNextState SMTP_C_Timeout(AsyncIO *IO)
588 SmtpOutMsg *pMsg = IO->Data;
590 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
591 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
592 return FailOneAttempt(IO);
594 eNextState SMTP_C_ConnFail(AsyncIO *IO)
596 SmtpOutMsg *pMsg = IO->Data;
598 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
599 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
600 return FailOneAttempt(IO);
602 eNextState SMTP_C_DNSFail(AsyncIO *IO)
604 SmtpOutMsg *pMsg = IO->Data;
606 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
607 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
608 return FailOneAttempt(IO);
610 eNextState SMTP_C_Shutdown(AsyncIO *IO)
612 EV_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
613 SmtpOutMsg *pMsg = IO->Data;
615 pMsg->MyQEntry->Status = 3;
616 StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
617 FinalizeMessageSend(pMsg);
623 * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
625 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
627 eReadState Finished = eBufferNotEmpty;
629 while (Finished == eBufferNotEmpty) {
630 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
633 case eMustReadMore: /// read new from socket...
636 case eBufferNotEmpty: /* shouldn't happen... */
637 case eReadSuccess: /// done for now...
638 if (StrLength(IO->IOBuf) < 4)
640 if (ChrPtr(IO->IOBuf)[3] == '-')
641 Finished = eBufferNotEmpty;
645 case eReadFail: /// WHUT?
653 CTDL_MODULE_INIT(smtp_eventclient)
655 return "smtpeventclient";