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,
209 "SMTP: %s resolving next MX Record\n",
211 return get_one_mx_host_ip(IO);
216 void SetConnectStatus(AsyncIO *IO)
218 SmtpOutMsg *SendMsg = IO->Data;
224 if (IO->ConnectMe->IPv6) {
225 src = &IO->ConnectMe->Addr.sin6_addr;
228 struct sockaddr_in *addr;
230 addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
231 src = &addr->sin_addr.s_addr;
234 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
239 if (SendMsg->mx_host == NULL)
240 SendMsg->mx_host = "<no MX-Record>";
242 EVS_syslog(LOG_DEBUG,
243 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
247 SendMsg->IO.ConnectMe->Port);
249 SendMsg->MyQEntry->Status = 5;
250 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
251 "Timeout while connecting %s [%s]:%d ",
254 SendMsg->IO.ConnectMe->Port);
255 SendMsg->IO.NextState = eConnect;
258 /*****************************************************************************
259 * So we connect our Relay IP here. *
260 *****************************************************************************/
261 eNextState mx_connect_ip(AsyncIO *IO)
263 SmtpOutMsg *SendMsg = IO->Data;
265 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
267 IO->ConnectMe = SendMsg->pCurrRelay;
269 SetConnectStatus(IO);
271 return EvConnectSock(IO,
273 SMTP_C_ReadTimeouts[0],
277 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
279 SmtpOutMsg *SendMsg = IO->Data;
280 struct hostent *hostent;
284 hostent = SendMsg->HostLookup.VParsedDNSReply;
285 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
286 (hostent != NULL) ) {
287 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
288 if (SendMsg->pCurrRelay->IPv6) {
289 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
290 &hostent->h_addr_list[0],
291 sizeof(struct in6_addr));
293 SendMsg->pCurrRelay->Addr.sin6_family =
295 SendMsg->pCurrRelay->Addr.sin6_port =
296 htons(DefaultMXPort);
299 struct sockaddr_in *addr;
301 * Bypass the ns lookup result like this:
302 * IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1");
303 * addr->sin_addr.s_addr =
304 * htonl((uint32_t)&hostent->h_addr_list[0]);
307 addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
309 memcpy(&addr->sin_addr.s_addr,
310 hostent->h_addr_list[0],
313 addr->sin_family = hostent->h_addrtype;
314 addr->sin_port = htons(DefaultMXPort);
316 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
317 return mx_connect_ip(IO);
320 return FailOneAttempt(IO);
323 eNextState get_one_mx_host_ip(AsyncIO *IO)
325 SmtpOutMsg * SendMsg = IO->Data;
327 * here we start with the lookup of one host. it might be...
328 * - the relay host *sigh*
329 * - the direct hostname if there was no mx record
333 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
335 EVS_syslog(LOG_DEBUG,
336 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
338 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
339 SendMsg->pCurrRelay->Host,
340 SendMsg->pCurrRelay->Port);
342 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
343 SendMsg->pCurrRelay->Host,
345 &SendMsg->HostLookup,
346 get_one_mx_host_ip_done))
348 SendMsg->MyQEntry->Status = 5;
349 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
350 "No MX hosts found for <%s>", SendMsg->node);
351 SendMsg->IO.NextState = eTerminateConnection;
352 return IO->NextState;
354 IO->NextState = eReadDNSReply;
355 return IO->NextState;
359 /*****************************************************************************
360 * here we try to find out about the MX records for our recipients. *
361 *****************************************************************************/
362 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
364 SmtpOutMsg * SendMsg = IO->Data;
369 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
370 pp = &SendMsg->Relay;
371 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
374 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
375 (IO->DNS.Query->VParsedDNSReply != NULL))
376 { /* ok, we found mx records. */
377 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
381 = IO->DNS.Query->VParsedDNSReply;
382 while (SendMsg->CurrMX) {
384 for (i = 0; i < 2; i++) {
387 p = (ParsedURL*) malloc(sizeof(ParsedURL));
388 memset(p, 0, sizeof(ParsedURL));
390 p->Port = DefaultMXPort;
392 p->Host = SendMsg->CurrMX->host;
397 SendMsg->CurrMX = SendMsg->CurrMX->next;
399 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
401 else { /* else fall back to the plain hostname */
403 for (i = 0; i < 2; i++) {
406 p = (ParsedURL*) malloc(sizeof(ParsedURL));
407 memset(p, 0, sizeof(ParsedURL));
409 p->Port = DefaultMXPort;
411 p->Host = SendMsg->node;
416 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
418 *pp = SendMsg->MyQItem->FallBackHost;
419 SendMsg->pCurrRelay = SendMsg->Relay;
420 return get_one_mx_host_ip(IO);
423 eNextState resolve_mx_records(AsyncIO *IO)
425 SmtpOutMsg * SendMsg = IO->Data;
427 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
428 /* start resolving MX records here. */
429 if (!QueueQuery(ns_t_mx,
433 smtp_resolve_mx_record_done))
435 SendMsg->MyQEntry->Status = 5;
436 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
437 "No MX hosts found for <%s>", SendMsg->node);
438 return IO->NextState;
440 SendMsg->IO.NextState = eReadDNSReply;
441 return IO->NextState;
446 /******************************************************************************
447 * so, we're going to start a SMTP delivery. lets get it on. *
448 ******************************************************************************/
450 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
451 MailQEntry *MyQEntry,
454 SmtpOutMsg * SendMsg;
456 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
457 memset(SendMsg, 0, sizeof(SmtpOutMsg));
459 SendMsg->n = MsgCount;
460 SendMsg->MyQEntry = MyQEntry;
461 SendMsg->MyQItem = MyQItem;
462 SendMsg->pCurrRelay = MyQItem->URL;
464 InitIOStruct(&SendMsg->IO,
467 SMTP_C_ReadServerStatus,
469 SMTP_C_DispatchWriteDone,
470 SMTP_C_DispatchReadDone,
479 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
480 MailQEntry *MyQEntry,
482 /*KeepMsgText allows us to use MsgText as ours.*/
488 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
490 SendMsg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
491 if (KeepMsgText) SendMsg->msgtext = MsgText;
492 else SendMsg->msgtext = NewStrBufDup(MsgText);
494 if (smtp_resolve_recipients(SendMsg)) {
497 ((CitContext *)SendMsg->IO.CitContext)->cs_host,
499 sizeof(((CitContext *)
500 SendMsg->IO.CitContext)->cs_host));
502 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
503 SendMsg->MyQItem->MessageID,
504 ChrPtr(SendMsg->MyQEntry->Recipient),
505 ((CitContext*)SendMsg->IO.CitContext)->cs_pid);
506 if (SendMsg->pCurrRelay == NULL)
507 QueueEventContext(&SendMsg->IO,
509 else { /* oh... via relay host */
510 if (SendMsg->pCurrRelay->IsIP) {
511 QueueEventContext(&SendMsg->IO,
515 /* uneducated admin has chosen to
516 add DNS to the equation... */
517 QueueEventContext(&SendMsg->IO,
523 /* No recipients? well fail then. */
524 if ((SendMsg==NULL) ||
525 (SendMsg->MyQEntry == NULL)) {
526 SendMsg->MyQEntry->Status = 5;
527 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
528 HKEY("Invalid Recipient!"));
530 FinalizeMessageSend(SendMsg);
539 /*****************************************************************************/
540 /* SMTP CLIENT DISPATCHER */
541 /*****************************************************************************/
543 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
545 double Timeout = 0.0;
546 AsyncIO *IO = &pMsg->IO;
548 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
550 switch (NextTCPState) {
554 Timeout = SMTP_C_SendTimeouts[pMsg->State];
555 if (pMsg->State == eDATABody) {
556 /* if we're sending a huge message,
559 Timeout += StrLength(pMsg->msgtext) / 1024;
563 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
564 if (pMsg->State == eDATATerminateBody) {
566 * some mailservers take a nap before accepting
567 * the message content inspection and such.
569 Timeout += StrLength(pMsg->msgtext) / 1024;
579 case eTerminateConnection:
583 SetNextTimeout(&pMsg->IO, Timeout);
585 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
587 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
588 SmtpOutMsg *pMsg = IO->Data;
591 rc = ReadHandlers[pMsg->State](pMsg);
595 SMTPSetTimeout(rc, pMsg);
599 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
601 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
602 SmtpOutMsg *pMsg = IO->Data;
605 rc = SendHandlers[pMsg->State](pMsg);
606 SMTPSetTimeout(rc, pMsg);
611 /*****************************************************************************/
612 /* SMTP CLIENT ERROR CATCHERS */
613 /*****************************************************************************/
614 eNextState SMTP_C_Terminate(AsyncIO *IO)
616 SmtpOutMsg *pMsg = IO->Data;
618 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
619 FinalizeMessageSend(pMsg);
622 eNextState SMTP_C_Timeout(AsyncIO *IO)
624 SmtpOutMsg *pMsg = IO->Data;
626 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
627 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
628 return FailOneAttempt(IO);
630 eNextState SMTP_C_ConnFail(AsyncIO *IO)
632 SmtpOutMsg *pMsg = IO->Data;
634 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
635 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
636 return FailOneAttempt(IO);
638 eNextState SMTP_C_DNSFail(AsyncIO *IO)
640 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
641 return FailOneAttempt(IO);
643 eNextState SMTP_C_Shutdown(AsyncIO *IO)
645 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
646 SmtpOutMsg *pMsg = IO->Data;
648 pMsg->MyQEntry->Status = 3;
649 StrBufPlain(pMsg->MyQEntry->StatusMessage,
650 HKEY("server shutdown during message submit."));
651 FinalizeMessageSend(pMsg);
657 * @brief lineread Handler;
658 * understands when to read more SMTP lines, and when this is a one-lined reply.
660 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
662 eReadState Finished = eBufferNotEmpty;
664 while (Finished == eBufferNotEmpty) {
665 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
668 case eMustReadMore: /// read new from socket...
671 case eBufferNotEmpty: /* shouldn't happen... */
672 case eReadSuccess: /// done for now...
673 if (StrLength(IO->IOBuf) < 4)
675 if (ChrPtr(IO->IOBuf)[3] == '-')
676 Finished = eBufferNotEmpty;
680 case eReadFail: /// WHUT?
688 CTDL_MODULE_INIT(smtp_eventclient)
690 return "smtpeventclient";