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 /* these are kept in our own space and free'd below */
99 Msg->IO.ConnectMe = NULL;
101 ares_free_data(Msg->AllMX);
102 if (Msg->HostLookup.VParsedDNSReply != NULL)
103 Msg->HostLookup.DNSReplyFree(Msg->HostLookup.VParsedDNSReply);
104 FreeURL(&Msg->Relay);
105 FreeStrBuf(&Msg->msgtext);
106 FreeAsyncIOContents(&Msg->IO);
107 memset (Msg, 0, sizeof(SmtpOutMsg)); /* just to be shure... */
111 eNextState SMTP_C_Shutdown(AsyncIO *IO);
112 eNextState SMTP_C_Timeout(AsyncIO *IO);
113 eNextState SMTP_C_ConnFail(AsyncIO *IO);
114 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO);
115 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO);
116 eNextState SMTP_C_DNSFail(AsyncIO *IO);
117 eNextState SMTP_C_Terminate(AsyncIO *IO);
118 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO);
120 eNextState mx_connect_ip(AsyncIO *IO);
121 eNextState get_one_mx_host_ip(AsyncIO *IO);
123 /******************************************************************************
124 * So, we're finished with sending (regardless of success or failure) *
125 * This Message might be referenced by several Queue-Items, if we're the last,*
126 * we need to free the memory and send bounce messages (on terminal failure) *
127 * else we just free our SMTP-Message struct. *
128 ******************************************************************************/
129 void FinalizeMessageSend(SmtpOutMsg *Msg)
131 int IDestructQueItem;
134 AsyncIO *IO = &Msg->IO;
136 IDestructQueItem = DecreaseQReference(Msg->MyQItem);
138 nRemain = CountActiveQueueEntries(Msg->MyQItem);
140 if ((nRemain > 0) || IDestructQueItem)
141 MsgData = SerializeQueueItem(Msg->MyQItem);
146 * Uncompleted delivery instructions remain, so delete the old
147 * instructions and replace with the updated ones.
149 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
150 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
152 if (IDestructQueItem)
153 smtpq_do_bounce(Msg->MyQItem,Msg->msgtext);
157 struct CtdlMessage *msg;
158 msg = malloc(sizeof(struct CtdlMessage));
159 memset(msg, 0, sizeof(struct CtdlMessage));
160 msg->cm_magic = CTDLMESSAGE_MAGIC;
161 msg->cm_anon_type = MES_NORMAL;
162 msg->cm_format_type = FMT_RFC822;
163 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
164 Msg->MyQItem->QueMsgID =
165 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
166 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
167 CtdlFreeMessage(msg);
170 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
171 &Msg->MyQItem->MessageID,
174 FreeStrBuf(&MsgData);
176 RemoveContext(Msg->IO.CitContext);
177 if (IDestructQueItem)
178 RemoveQItem(Msg->MyQItem);
179 DeleteSmtpOutMsg(Msg);
182 eNextState FailOneAttempt(AsyncIO *IO)
184 SmtpOutMsg *SendMsg = IO->Data;
186 if (SendMsg->MyQEntry->Status == 2)
190 * possible ways here:
191 * - connection timeout
192 * - dns lookup failed
194 StopClientWatchers(IO);
196 if (SendMsg->pCurrRelay != NULL)
197 SendMsg->pCurrRelay = SendMsg->pCurrRelay->Next;
199 if (SendMsg->pCurrRelay == NULL) {
200 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
203 if (SendMsg->pCurrRelay->IsIP) {
204 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
205 return mx_connect_ip(IO);
208 EVS_syslog(LOG_DEBUG, "SMTP: %s resolving next MX Record\n", __FUNCTION__);
209 return get_one_mx_host_ip(IO);
214 void SetConnectStatus(AsyncIO *IO)
216 SmtpOutMsg *SendMsg = IO->Data;
222 if (IO->ConnectMe->IPv6) {
223 src = &IO->ConnectMe->Addr.sin6_addr;
226 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
228 src = &addr->sin_addr.s_addr;
231 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
236 if (SendMsg->mx_host == NULL)
237 SendMsg->mx_host = "<no MX-Record>";
239 EVS_syslog(LOG_DEBUG,
240 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
244 SendMsg->IO.ConnectMe->Port);
246 SendMsg->MyQEntry->Status = 5;
247 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
248 "Timeout while connecting %s [%s]:%d ",
251 SendMsg->IO.ConnectMe->Port);
252 SendMsg->IO.NextState = eConnect;
255 /*****************************************************************************
256 * So we connect our Relay IP here. *
257 *****************************************************************************/
258 eNextState mx_connect_ip(AsyncIO *IO)
260 SmtpOutMsg *SendMsg = IO->Data;
262 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
264 IO->ConnectMe = SendMsg->pCurrRelay;
266 SetConnectStatus(IO);
268 return EvConnectSock(IO,
270 SMTP_C_ReadTimeouts[0],
274 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
276 SmtpOutMsg *SendMsg = IO->Data;
277 struct hostent *hostent;
281 hostent = SendMsg->HostLookup.VParsedDNSReply;
282 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
283 (hostent != NULL) ) {
284 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
285 if (SendMsg->pCurrRelay->IPv6) {
286 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
287 &hostent->h_addr_list[0],
288 sizeof(struct in6_addr));
290 SendMsg->pCurrRelay->Addr.sin6_family = hostent->h_addrtype;
291 SendMsg->pCurrRelay->Addr.sin6_port = htons(DefaultMXPort);
294 struct sockaddr_in *addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
295 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
296 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
297 memcpy(&addr->sin_addr.s_addr,
298 hostent->h_addr_list[0],
301 addr->sin_family = hostent->h_addrtype;
302 addr->sin_port = htons(DefaultMXPort);
305 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
306 return mx_connect_ip(IO);
308 else // TODO: here we need to find out whether there are more mx'es, backup relay, and so on
309 return FailOneAttempt(IO);
312 eNextState get_one_mx_host_ip(AsyncIO *IO)
314 SmtpOutMsg * SendMsg = IO->Data;
316 * here we start with the lookup of one host. it might be...
317 * - the relay host *sigh*
318 * - the direct hostname if there was no mx record
324 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
326 EVS_syslog(LOG_DEBUG,
327 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
329 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
330 SendMsg->pCurrRelay->Host,
331 SendMsg->pCurrRelay->Port);
333 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
334 SendMsg->pCurrRelay->Host,
336 &SendMsg->HostLookup,
337 get_one_mx_host_ip_done))
339 SendMsg->MyQEntry->Status = 5;
340 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
341 "No MX hosts found for <%s>", SendMsg->node);
342 SendMsg->IO.NextState = eTerminateConnection;
343 return IO->NextState;
345 IO->NextState = eReadDNSReply;
346 return IO->NextState;
350 /*****************************************************************************
351 * here we try to find out about the MX records for our recipients. *
352 *****************************************************************************/
353 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
355 SmtpOutMsg * SendMsg = IO->Data;
360 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
361 pp = &SendMsg->Relay;
362 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
365 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
366 (IO->DNS.Query->VParsedDNSReply != NULL))
367 { /* ok, we found mx records. */
368 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
370 SendMsg->CurrMX = SendMsg->AllMX
371 = IO->DNS.Query->VParsedDNSReply;
372 while (SendMsg->CurrMX) {
374 for (i = 0; i < 2; i++) {
377 p = (ParsedURL*) malloc(sizeof(ParsedURL));
378 memset(p, 0, sizeof(ParsedURL));
380 p->Port = DefaultMXPort;
382 p->Host = SendMsg->CurrMX->host;
387 SendMsg->CurrMX = SendMsg->CurrMX->next;
389 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
391 else { /* else fall back to the plain hostname */
393 for (i = 0; i < 2; i++) {
396 p = (ParsedURL*) malloc(sizeof(ParsedURL));
397 memset(p, 0, sizeof(ParsedURL));
399 p->Port = DefaultMXPort;
401 p->Host = SendMsg->node;
406 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
408 *pp = SendMsg->MyQItem->FallBackHost;
409 SendMsg->pCurrRelay = SendMsg->Relay;
410 return get_one_mx_host_ip(IO);
413 eNextState resolve_mx_records(AsyncIO *IO)
415 SmtpOutMsg * SendMsg = IO->Data;
417 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
418 /* start resolving MX records here. */
419 if (!QueueQuery(ns_t_mx,
423 smtp_resolve_mx_record_done))
425 SendMsg->MyQEntry->Status = 5;
426 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
427 "No MX hosts found for <%s>", SendMsg->node);
428 return IO->NextState;
430 SendMsg->IO.NextState = eReadDNSReply;
431 return IO->NextState;
436 /******************************************************************************
437 * so, we're going to start a SMTP delivery. lets get it on. *
438 ******************************************************************************/
440 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
441 MailQEntry *MyQEntry,
444 SmtpOutMsg * SendMsg;
446 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
447 memset(SendMsg, 0, sizeof(SmtpOutMsg));
449 SendMsg->n = MsgCount;
450 SendMsg->MyQEntry = MyQEntry;
451 SendMsg->MyQItem = MyQItem;
452 SendMsg->pCurrRelay = MyQItem->URL;
454 InitIOStruct(&SendMsg->IO,
457 SMTP_C_ReadServerStatus,
459 SMTP_C_DispatchWriteDone,
460 SMTP_C_DispatchReadDone,
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)) {
486 ((CitContext *)SendMsg->IO.CitContext)->cs_host,
488 sizeof(((CitContext *)SendMsg->IO.CitContext)->cs_host));
490 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
491 SendMsg->MyQItem->MessageID,
492 ChrPtr(SendMsg->MyQEntry->Recipient),
493 ((CitContext*)SendMsg->IO.CitContext)->cs_pid);
494 if (SendMsg->pCurrRelay == NULL)
495 QueueEventContext(&SendMsg->IO,
497 else { /* oh... via relay host */
498 if (SendMsg->pCurrRelay->IsIP) {
499 QueueEventContext(&SendMsg->IO,
502 else { /* uneducated admin has chosen to add DNS to the equation... */
503 QueueEventContext(&SendMsg->IO,
509 /* No recipients? well fail then. */
510 if ((SendMsg==NULL) ||
511 (SendMsg->MyQEntry == NULL)) {
512 SendMsg->MyQEntry->Status = 5;
513 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
514 HKEY("Invalid Recipient!"));
516 FinalizeMessageSend(SendMsg);
525 /*****************************************************************************/
526 /* SMTP CLIENT DISPATCHER */
527 /*****************************************************************************/
529 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
531 double Timeout = 0.0;
532 AsyncIO *IO = &pMsg->IO;
534 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
536 switch (NextTCPState) {
540 Timeout = SMTP_C_SendTimeouts[pMsg->State];
541 if (pMsg->State == eDATABody) {
542 /* if we're sending a huge message, we need more time. */
543 Timeout += StrLength(pMsg->msgtext) / 1024;
547 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
548 if (pMsg->State == eDATATerminateBody) {
550 * some mailservers take a nap before accepting the message
551 * content inspection and such.
553 Timeout += StrLength(pMsg->msgtext) / 1024;
563 case eTerminateConnection:
567 SetNextTimeout(&pMsg->IO, Timeout);
569 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
571 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
572 SmtpOutMsg *pMsg = IO->Data;
575 rc = ReadHandlers[pMsg->State](pMsg);
579 SMTPSetTimeout(rc, pMsg);
583 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
585 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
586 SmtpOutMsg *pMsg = IO->Data;
589 rc = SendHandlers[pMsg->State](pMsg);
590 SMTPSetTimeout(rc, pMsg);
595 /*****************************************************************************/
596 /* SMTP CLIENT ERROR CATCHERS */
597 /*****************************************************************************/
598 eNextState SMTP_C_Terminate(AsyncIO *IO)
600 SmtpOutMsg *pMsg = IO->Data;
602 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
603 FinalizeMessageSend(pMsg);
606 eNextState SMTP_C_Timeout(AsyncIO *IO)
608 SmtpOutMsg *pMsg = IO->Data;
610 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
611 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
612 return FailOneAttempt(IO);
614 eNextState SMTP_C_ConnFail(AsyncIO *IO)
616 SmtpOutMsg *pMsg = IO->Data;
618 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
619 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
620 return FailOneAttempt(IO);
622 eNextState SMTP_C_DNSFail(AsyncIO *IO)
624 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
625 return FailOneAttempt(IO);
627 eNextState SMTP_C_Shutdown(AsyncIO *IO)
629 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
630 SmtpOutMsg *pMsg = IO->Data;
632 pMsg->MyQEntry->Status = 3;
633 StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
634 FinalizeMessageSend(pMsg);
640 * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
642 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
644 eReadState Finished = eBufferNotEmpty;
646 while (Finished == eBufferNotEmpty) {
647 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
650 case eMustReadMore: /// read new from socket...
653 case eBufferNotEmpty: /* shouldn't happen... */
654 case eReadSuccess: /// done for now...
655 if (StrLength(IO->IOBuf) < 4)
657 if (ChrPtr(IO->IOBuf)[3] == '-')
658 Finished = eBufferNotEmpty;
662 case eReadFail: /// WHUT?
670 CTDL_MODULE_INIT(smtp_eventclient)
672 return "smtpeventclient";