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 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
130 if (DecreaseQReference(Msg->MyQItem))
135 nRemain = CountActiveQueueEntries(Msg->MyQItem);
137 MsgData = SerializeQueueItem(Msg->MyQItem);
139 * Uncompleted delivery instructions remain, so delete the old
140 * instructions and replace with the updated ones.
142 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
143 smtpq_do_bounce(Msg->MyQItem,
146 struct CtdlMessage *msg;
147 msg = malloc(sizeof(struct CtdlMessage));
148 memset(msg, 0, sizeof(struct CtdlMessage));
149 msg->cm_magic = CTDLMESSAGE_MAGIC;
150 msg->cm_anon_type = MES_NORMAL;
151 msg->cm_format_type = FMT_RFC822;
152 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
153 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
154 CtdlFreeMessage(msg);
157 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->MessageID, 1, "");
158 FreeStrBuf(&MsgData);
161 RemoveQItem(Msg->MyQItem);
164 RemoveContext(Msg->IO.CitContext);
165 DeleteSmtpOutMsg(Msg);
168 eNextState FailOneAttempt(AsyncIO *IO)
170 SmtpOutMsg *SendMsg = IO->Data;
172 * possible ways here:
173 * - connection timeout
176 StopClientWatchers(IO);
178 if (SendMsg->pCurrRelay != NULL)
179 SendMsg->pCurrRelay = SendMsg->pCurrRelay->Next;
181 if (SendMsg->pCurrRelay == NULL)
183 if (SendMsg->pCurrRelay->IsIP)
184 return mx_connect_ip(IO);
186 return get_one_mx_host_ip(IO);
190 void SetConnectStatus(AsyncIO *IO)
193 SmtpOutMsg *SendMsg = IO->Data;
199 if (IO->ConnectMe->IPv6) {
200 src = &IO->ConnectMe->Addr.sin6_addr;
203 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
205 src = &addr->sin_addr.s_addr;
208 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
213 if (SendMsg->mx_host == NULL)
214 SendMsg->mx_host = "<no MX-Record>";
217 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
221 SendMsg->IO.ConnectMe->Port);
223 SendMsg->MyQEntry->Status = 5;
224 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
225 "Timeout while connecting %s [%s]:%d ",
228 SendMsg->IO.ConnectMe->Port);
229 SendMsg->IO.NextState = eConnect;
232 /*****************************************************************************
233 * So we connect our Relay IP here. *
234 *****************************************************************************/
235 eNextState mx_connect_ip(AsyncIO *IO)
237 SmtpOutMsg *SendMsg = IO->Data;
239 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
241 IO->ConnectMe = SendMsg->pCurrRelay;
242 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
244 SetConnectStatus(IO);
246 return InitEventIO(IO, SendMsg,
248 SMTP_C_ReadTimeouts[0],
252 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
254 SmtpOutMsg *SendMsg = IO->Data;
255 struct hostent *hostent;
259 hostent = SendMsg->HostLookup.VParsedDNSReply;
260 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
261 (hostent != NULL) ) {
262 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
263 if (SendMsg->pCurrRelay->IPv6) {
264 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
265 &hostent->h_addr_list[0],
266 sizeof(struct in6_addr));
268 SendMsg->pCurrRelay->Addr.sin6_family = hostent->h_addrtype;
269 SendMsg->pCurrRelay->Addr.sin6_port = htons(DefaultMXPort);
272 struct sockaddr_in *addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
273 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
274 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
275 memcpy(&addr->sin_addr.s_addr,
276 hostent->h_addr_list[0],
279 addr->sin_family = hostent->h_addrtype;
280 addr->sin_port = htons(DefaultMXPort);
283 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
284 return mx_connect_ip(IO);
286 else // TODO: here we need to find out whether there are more mx'es, backup relay, and so on
287 return FailOneAttempt(IO);
290 eNextState get_one_mx_host_ip(AsyncIO *IO)
292 SmtpOutMsg * SendMsg = IO->Data;
294 * here we start with the lookup of one host. it might be...
295 * - the relay host *sigh*
296 * - the direct hostname if there was no mx record
302 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
305 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
307 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
308 SendMsg->pCurrRelay->Host,
309 SendMsg->pCurrRelay->Port);
311 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
312 SendMsg->pCurrRelay->Host,
314 &SendMsg->HostLookup,
315 get_one_mx_host_ip_done))
317 SendMsg->MyQEntry->Status = 5;
318 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
319 "No MX hosts found for <%s>", SendMsg->node);
320 SendMsg->IO.NextState = eTerminateConnection;
321 return IO->NextState;
323 IO->NextState = eReadDNSReply;
324 return IO->NextState;
328 /*****************************************************************************
329 * here we try to find out about the MX records for our recipients. *
330 *****************************************************************************/
331 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
333 SmtpOutMsg * SendMsg = IO->Data;
338 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
339 pp = &SendMsg->Relay;
340 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
343 if ((IO->DNSQuery->DNSStatus == ARES_SUCCESS) &&
344 (IO->DNSQuery->VParsedDNSReply != NULL))
345 { /* ok, we found mx records. */
346 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
348 SendMsg->CurrMX = SendMsg->AllMX
349 = IO->DNSQuery->VParsedDNSReply;
350 while (SendMsg->CurrMX) {
352 for (i = 0; i < 2; i++) {
355 p = (ParsedURL*) malloc(sizeof(ParsedURL));
356 memset(p, 0, sizeof(ParsedURL));
358 p->Port = DefaultMXPort;
360 p->Host = SendMsg->CurrMX->host;
365 SendMsg->CurrMX = SendMsg->CurrMX->next;
367 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
369 else { /* else fall back to the plain hostname */
371 for (i = 0; i < 2; i++) {
374 p = (ParsedURL*) malloc(sizeof(ParsedURL));
375 memset(p, 0, sizeof(ParsedURL));
377 p->Port = DefaultMXPort;
379 p->Host = SendMsg->node;
384 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
386 *pp = SendMsg->MyQItem->FallBackHost;
387 SendMsg->pCurrRelay = SendMsg->Relay;
388 return get_one_mx_host_ip(IO);
391 eNextState resolve_mx_records(AsyncIO *IO)
393 SmtpOutMsg * SendMsg = IO->Data;
395 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
396 /* start resolving MX records here. */
397 if (!QueueQuery(ns_t_mx,
401 smtp_resolve_mx_record_done))
403 SendMsg->MyQEntry->Status = 5;
404 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
405 "No MX hosts found for <%s>", SendMsg->node);
406 return IO->NextState;
408 SendMsg->IO.NextState = eReadDNSReply;
409 return IO->NextState;
414 /******************************************************************************
415 * so, we're going to start a SMTP delivery. lets get it on. *
416 ******************************************************************************/
418 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
419 MailQEntry *MyQEntry,
422 SmtpOutMsg * SendMsg;
424 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
425 memset(SendMsg, 0, sizeof(SmtpOutMsg));
427 SendMsg->n = MsgCount;
428 SendMsg->MyQEntry = MyQEntry;
429 SendMsg->MyQItem = MyQItem;
430 SendMsg->pCurrRelay = MyQItem->URL;
432 SendMsg->IO.Data = SendMsg;
434 SendMsg->IO.SendDone = SMTP_C_DispatchWriteDone;
435 SendMsg->IO.ReadDone = SMTP_C_DispatchReadDone;
436 SendMsg->IO.Terminate = SMTP_C_Terminate;
437 SendMsg->IO.LineReader = SMTP_C_ReadServerStatus;
438 SendMsg->IO.ConnFail = SMTP_C_ConnFail;
439 SendMsg->IO.DNSFail = SMTP_C_DNSFail;
440 SendMsg->IO.Timeout = SMTP_C_Timeout;
441 SendMsg->IO.ShutdownAbort = SMTP_C_Shutdown;
443 SendMsg->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
444 SendMsg->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
445 SendMsg->IO.IOBuf = NewStrBuf();
447 SendMsg->IO.NextState = eReadMessage;
452 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
453 MailQEntry *MyQEntry,
455 int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
460 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
462 SendMsg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
463 if (KeepMsgText) SendMsg->msgtext = MsgText;
464 else SendMsg->msgtext = NewStrBufDup(MsgText);
466 if (smtp_resolve_recipients(SendMsg)) {
468 SubC = CloneContext (CC);
469 SubC->session_specific_data = (char*) SendMsg;
470 SendMsg->IO.CitContext = SubC;
472 if (SendMsg->pCurrRelay == NULL)
473 QueueEventContext(&SendMsg->IO,
475 else { /* oh... via relay host */
476 if (SendMsg->pCurrRelay->IsIP) {
477 QueueEventContext(&SendMsg->IO,
480 else { /* uneducated admin has chosen to add DNS to the equation... */
481 QueueEventContext(&SendMsg->IO,
487 /* No recipients? well fail then. */
488 if ((SendMsg==NULL) ||
489 (SendMsg->MyQEntry == NULL)) {
490 SendMsg->MyQEntry->Status = 5;
491 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
492 HKEY("Invalid Recipient!"));
494 FinalizeMessageSend(SendMsg);
503 /*****************************************************************************/
504 /* SMTP CLIENT DISPATCHER */
505 /*****************************************************************************/
507 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
509 double Timeout = 0.0;
511 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
513 switch (NextTCPState) {
516 Timeout = SMTP_C_SendTimeouts[pMsg->State];
517 if (pMsg->State == eDATABody) {
518 /* if we're sending a huge message, we need more time. */
519 Timeout += StrLength(pMsg->msgtext) / 1024;
523 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
524 if (pMsg->State == eDATATerminateBody) {
526 * some mailservers take a nap before accepting the message
527 * content inspection and such.
529 Timeout += StrLength(pMsg->msgtext) / 1024;
538 case eTerminateConnection:
542 SetNextTimeout(&pMsg->IO, Timeout);
544 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
546 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
547 SmtpOutMsg *pMsg = IO->Data;
550 rc = ReadHandlers[pMsg->State](pMsg);
552 SMTPSetTimeout(rc, pMsg);
555 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
557 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
558 SmtpOutMsg *pMsg = IO->Data;
561 rc = SendHandlers[pMsg->State](pMsg);
562 SMTPSetTimeout(rc, pMsg);
567 /*****************************************************************************/
568 /* SMTP CLIENT ERROR CATCHERS */
569 /*****************************************************************************/
570 eNextState SMTP_C_Terminate(AsyncIO *IO)
572 SmtpOutMsg *pMsg = IO->Data;
574 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
575 FinalizeMessageSend(pMsg);
578 eNextState SMTP_C_Timeout(AsyncIO *IO)
580 SmtpOutMsg *pMsg = IO->Data;
582 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
583 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
584 return FailOneAttempt(IO);
586 eNextState SMTP_C_ConnFail(AsyncIO *IO)
588 SmtpOutMsg *pMsg = IO->Data;
590 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
591 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
592 return FailOneAttempt(IO);
594 eNextState SMTP_C_DNSFail(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_Shutdown(AsyncIO *IO)
604 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
605 SmtpOutMsg *pMsg = IO->Data;
607 pMsg->MyQEntry->Status = 3;
608 StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
609 FinalizeMessageSend(pMsg);
615 * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
617 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
619 eReadState Finished = eBufferNotEmpty;
621 while (Finished == eBufferNotEmpty) {
622 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
625 case eMustReadMore: /// read new from socket...
628 case eBufferNotEmpty: /* shouldn't happen... */
629 case eReadSuccess: /// done for now...
630 if (StrLength(IO->IOBuf) < 4)
632 if (ChrPtr(IO->IOBuf)[3] == '-')
633 Finished = eBufferNotEmpty;
637 case eReadFail: /// WHUT?
645 CTDL_MODULE_INIT(smtp_eventclient)
647 return "smtpeventclient";