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_Terminate(AsyncIO *IO);
114 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
116 eNextState mx_connect_ip(AsyncIO *IO);
117 eNextState get_one_mx_host_ip(AsyncIO *IO);
119 /******************************************************************************
120 * So, we're finished with sending (regardless of success or failure) *
121 * This Message might be referenced by several Queue-Items, if we're the last,*
122 * we need to free the memory and send bounce messages (on terminal failure) *
123 * else we just free our SMTP-Message struct. *
124 ******************************************************************************/
125 void FinalizeMessageSend(SmtpOutMsg *Msg)
127 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
129 if (DecreaseQReference(Msg->MyQItem))
134 nRemain = CountActiveQueueEntries(Msg->MyQItem);
136 MsgData = SerializeQueueItem(Msg->MyQItem);
138 * Uncompleted delivery instructions remain, so delete the old
139 * instructions and replace with the updated ones.
141 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
142 smtpq_do_bounce(Msg->MyQItem,
145 struct CtdlMessage *msg;
146 msg = malloc(sizeof(struct CtdlMessage));
147 memset(msg, 0, sizeof(struct CtdlMessage));
148 msg->cm_magic = CTDLMESSAGE_MAGIC;
149 msg->cm_anon_type = MES_NORMAL;
150 msg->cm_format_type = FMT_RFC822;
151 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
152 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
153 CtdlFreeMessage(msg);
156 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->MessageID, 1, "");
157 FreeStrBuf(&MsgData);
160 RemoveQItem(Msg->MyQItem);
163 RemoveContext(Msg->IO.CitContext);
164 DeleteSmtpOutMsg(Msg);
167 eNextState FailOneAttempt(AsyncIO *IO)
169 SmtpOutMsg *SendMsg = IO->Data;
171 * possible ways here:
172 * - connection timeout
175 StopClientWatchers(IO);
177 if (SendMsg->pCurrRelay != NULL)
178 SendMsg->pCurrRelay = SendMsg->pCurrRelay->Next;
180 if (SendMsg->pCurrRelay == NULL)
182 if (SendMsg->pCurrRelay->IsIP)
183 return mx_connect_ip(IO);
185 return get_one_mx_host_ip(IO);
189 void SetConnectStatus(AsyncIO *IO)
192 SmtpOutMsg *SendMsg = IO->Data;
198 if (IO->ConnectMe->IPv6) {
199 src = &IO->ConnectMe->Addr.sin6_addr;
202 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
204 src = &addr->sin_addr.s_addr;
207 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
212 if (SendMsg->mx_host == NULL)
213 SendMsg->mx_host = "<no MX-Record>";
216 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
220 SendMsg->IO.ConnectMe->Port);
222 SendMsg->MyQEntry->Status = 5;
223 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
224 "Timeout while connecting %s [%s]:%d ",
227 SendMsg->IO.ConnectMe->Port);
228 SendMsg->IO.NextState = eConnect;
231 /*****************************************************************************
232 * So we connect our Relay IP here. *
233 *****************************************************************************/
234 eNextState mx_connect_ip(AsyncIO *IO)
236 SmtpOutMsg *SendMsg = IO->Data;
238 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
240 IO->ConnectMe = SendMsg->pCurrRelay;
241 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
243 SetConnectStatus(IO);
245 return InitEventIO(IO, SendMsg,
247 SMTP_C_ReadTimeouts[0],
251 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
253 SmtpOutMsg *SendMsg = IO->Data;
254 struct hostent *hostent;
258 hostent = SendMsg->HostLookup.VParsedDNSReply;
259 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
260 (hostent != NULL) ) {
261 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
262 if (SendMsg->pCurrRelay->IPv6) {
263 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
264 &hostent->h_addr_list[0],
265 sizeof(struct in6_addr));
267 SendMsg->pCurrRelay->Addr.sin6_family = hostent->h_addrtype;
268 SendMsg->pCurrRelay->Addr.sin6_port = htons(DefaultMXPort);
271 struct sockaddr_in *addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
272 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
273 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
274 memcpy(&addr->sin_addr.s_addr,
275 hostent->h_addr_list[0],
278 addr->sin_family = hostent->h_addrtype;
279 addr->sin_port = htons(DefaultMXPort);
282 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
283 return mx_connect_ip(IO);
285 else // TODO: here we need to find out whether there are more mx'es, backup relay, and so on
286 return FailOneAttempt(IO);
289 eNextState get_one_mx_host_ip(AsyncIO *IO)
291 SmtpOutMsg * SendMsg = IO->Data;
293 * here we start with the lookup of one host. it might be...
294 * - the relay host *sigh*
295 * - the direct hostname if there was no mx record
301 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
304 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
306 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
307 SendMsg->pCurrRelay->Host,
308 SendMsg->pCurrRelay->Port);
310 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
311 SendMsg->pCurrRelay->Host,
313 &SendMsg->HostLookup,
314 get_one_mx_host_ip_done))
316 SendMsg->MyQEntry->Status = 5;
317 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
318 "No MX hosts found for <%s>", SendMsg->node);
319 SendMsg->IO.NextState = eTerminateConnection;
320 return IO->NextState;
322 IO->NextState = eReadDNSReply;
323 return IO->NextState;
327 /*****************************************************************************
328 * here we try to find out about the MX records for our recipients. *
329 *****************************************************************************/
330 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
332 SmtpOutMsg * SendMsg = IO->Data;
337 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
338 pp = &SendMsg->Relay;
339 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
342 if ((IO->DNSQuery->DNSStatus == ARES_SUCCESS) &&
343 (IO->DNSQuery->VParsedDNSReply != NULL))
344 { /* ok, we found mx records. */
345 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
347 SendMsg->CurrMX = SendMsg->AllMX
348 = IO->DNSQuery->VParsedDNSReply;
349 while (SendMsg->CurrMX) {
351 for (i = 0; i < 2; i++) {
354 p = (ParsedURL*) malloc(sizeof(ParsedURL));
355 memset(p, 0, sizeof(ParsedURL));
357 p->Port = DefaultMXPort;
359 p->Host = SendMsg->CurrMX->host;
364 SendMsg->CurrMX = SendMsg->CurrMX->next;
366 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
368 else { /* else fall back to the plain hostname */
370 for (i = 0; i < 2; i++) {
373 p = (ParsedURL*) malloc(sizeof(ParsedURL));
374 memset(p, 0, sizeof(ParsedURL));
376 p->Port = DefaultMXPort;
378 p->Host = SendMsg->node;
383 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
385 *pp = SendMsg->MyQItem->FallBackHost;
386 SendMsg->pCurrRelay = SendMsg->Relay;
387 return get_one_mx_host_ip(IO);
390 eNextState resolve_mx_records(AsyncIO *IO)
392 SmtpOutMsg * SendMsg = IO->Data;
394 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
395 /* start resolving MX records here. */
396 if (!QueueQuery(ns_t_mx,
400 smtp_resolve_mx_record_done))
402 SendMsg->MyQEntry->Status = 5;
403 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
404 "No MX hosts found for <%s>", SendMsg->node);
405 return IO->NextState;
407 SendMsg->IO.NextState = eReadDNSReply;
408 return IO->NextState;
413 /******************************************************************************
414 * so, we're going to start a SMTP delivery. lets get it on. *
415 ******************************************************************************/
417 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
418 MailQEntry *MyQEntry,
421 SmtpOutMsg * SendMsg;
423 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
424 memset(SendMsg, 0, sizeof(SmtpOutMsg));
426 SendMsg->n = MsgCount;
427 SendMsg->MyQEntry = MyQEntry;
428 SendMsg->MyQItem = MyQItem;
429 SendMsg->pCurrRelay = MyQItem->URL;
431 SendMsg->IO.Data = SendMsg;
433 SendMsg->IO.SendDone = SMTP_C_DispatchWriteDone;
434 SendMsg->IO.ReadDone = SMTP_C_DispatchReadDone;
435 SendMsg->IO.Terminate = SMTP_C_Terminate;
436 SendMsg->IO.LineReader = SMTP_C_ReadServerStatus;
437 SendMsg->IO.ConnFail = SMTP_C_ConnFail;
438 SendMsg->IO.Timeout = SMTP_C_Timeout;
439 SendMsg->IO.ShutdownAbort = SMTP_C_Shutdown;
441 SendMsg->IO.SendBuf.Buf = NewStrBufPlain(NULL, 1024);
442 SendMsg->IO.RecvBuf.Buf = NewStrBufPlain(NULL, 1024);
443 SendMsg->IO.IOBuf = NewStrBuf();
445 SendMsg->IO.NextState = eReadMessage;
450 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
451 MailQEntry *MyQEntry,
453 int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
458 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
460 SendMsg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
461 if (KeepMsgText) SendMsg->msgtext = MsgText;
462 else SendMsg->msgtext = NewStrBufDup(MsgText);
464 if (smtp_resolve_recipients(SendMsg)) {
466 SubC = CloneContext (CC);
467 SubC->session_specific_data = (char*) SendMsg;
468 SendMsg->IO.CitContext = SubC;
470 if (SendMsg->pCurrRelay == NULL)
471 QueueEventContext(&SendMsg->IO,
473 else { /* oh... via relay host */
474 if (SendMsg->pCurrRelay->IsIP) {
475 QueueEventContext(&SendMsg->IO,
478 else { /* uneducated admin has chosen to add DNS to the equation... */
479 QueueEventContext(&SendMsg->IO,
485 /* No recipients? well fail then. */
486 if ((SendMsg==NULL) ||
487 (SendMsg->MyQEntry == NULL)) {
488 SendMsg->MyQEntry->Status = 5;
489 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
490 HKEY("Invalid Recipient!"));
492 FinalizeMessageSend(SendMsg);
501 /*****************************************************************************/
502 /* SMTP CLIENT DISPATCHER */
503 /*****************************************************************************/
505 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
507 double Timeout = 0.0;
509 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
511 switch (NextTCPState) {
514 Timeout = SMTP_C_SendTimeouts[pMsg->State];
515 if (pMsg->State == eDATABody) {
516 /* if we're sending a huge message, we need more time. */
517 Timeout += StrLength(pMsg->msgtext) / 1024;
521 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
522 if (pMsg->State == eDATATerminateBody) {
524 * some mailservers take a nap before accepting the message
525 * content inspection and such.
527 Timeout += StrLength(pMsg->msgtext) / 1024;
536 case eTerminateConnection:
540 SetNextTimeout(&pMsg->IO, Timeout);
542 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
544 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
545 SmtpOutMsg *pMsg = IO->Data;
548 rc = ReadHandlers[pMsg->State](pMsg);
550 SMTPSetTimeout(rc, pMsg);
553 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
555 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
556 SmtpOutMsg *pMsg = IO->Data;
559 rc = SendHandlers[pMsg->State](pMsg);
560 SMTPSetTimeout(rc, pMsg);
565 /*****************************************************************************/
566 /* SMTP CLIENT ERROR CATCHERS */
567 /*****************************************************************************/
568 eNextState SMTP_C_Terminate(AsyncIO *IO)
570 SmtpOutMsg *pMsg = IO->Data;
572 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
573 FinalizeMessageSend(pMsg);
576 eNextState SMTP_C_Timeout(AsyncIO *IO)
578 SmtpOutMsg *pMsg = IO->Data;
580 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
581 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
582 return FailOneAttempt(IO);
584 eNextState SMTP_C_ConnFail(AsyncIO *IO)
586 SmtpOutMsg *pMsg = IO->Data;
588 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
589 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
590 return FailOneAttempt(IO);
592 eNextState SMTP_C_Shutdown(AsyncIO *IO)
594 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
595 SmtpOutMsg *pMsg = IO->Data;
597 pMsg->MyQEntry->Status = 3;
598 StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
599 FinalizeMessageSend(pMsg);
605 * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
607 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
609 eReadState Finished = eBufferNotEmpty;
611 while (Finished == eBufferNotEmpty) {
612 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
615 case eMustReadMore: /// read new from socket...
618 case eBufferNotEmpty: /* shouldn't happen... */
619 case eReadSuccess: /// done for now...
620 if (StrLength(IO->IOBuf) < 4)
622 if (ChrPtr(IO->IOBuf)[3] == '-')
623 Finished = eBufferNotEmpty;
627 case eReadFail: /// WHUT?
635 CTDL_MODULE_INIT(smtp_eventclient)
637 return "smtpeventclient";