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 int IDestructQueItem;
131 AsyncIO *IO = &Msg->IO;
133 IDestructQueItem = DecreaseQReference(Msg->MyQItem);
135 nRemain = CountActiveQueueEntries(Msg->MyQItem);
137 if ((nRemain > 0) || IDestructQueItem)
138 MsgData = SerializeQueueItem(Msg->MyQItem);
143 * Uncompleted delivery instructions remain, so delete the old
144 * instructions and replace with the updated ones.
146 EVS_syslog(LOG_DEBUG, "SMTPQD: %ld", Msg->MyQItem->QueMsgID);
147 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM, &Msg->MyQItem->QueMsgID, 1, "");
149 if (IDestructQueItem)
150 smtpq_do_bounce(Msg->MyQItem,Msg->msgtext);
154 struct CtdlMessage *msg;
155 msg = malloc(sizeof(struct CtdlMessage));
156 memset(msg, 0, sizeof(struct CtdlMessage));
157 msg->cm_magic = CTDLMESSAGE_MAGIC;
158 msg->cm_anon_type = MES_NORMAL;
159 msg->cm_format_type = FMT_RFC822;
160 msg->cm_fields['M'] = SmashStrBuf(&MsgData);
161 Msg->MyQItem->QueMsgID =
162 CtdlSubmitMsg(msg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
163 EVS_syslog(LOG_DEBUG, "SMTPQ: %ld", Msg->MyQItem->QueMsgID);
164 CtdlFreeMessage(msg);
167 CtdlDeleteMessages(SMTP_SPOOLOUT_ROOM,
168 &Msg->MyQItem->MessageID,
171 FreeStrBuf(&MsgData);
173 RemoveContext(Msg->IO.CitContext);
174 if (IDestructQueItem)
175 RemoveQItem(Msg->MyQItem);
176 DeleteSmtpOutMsg(Msg);
179 eNextState FailOneAttempt(AsyncIO *IO)
181 SmtpOutMsg *SendMsg = IO->Data;
183 if (SendMsg->MyQEntry->Status == 2)
187 * possible ways here:
188 * - connection timeout
189 * - dns lookup failed
191 StopClientWatchers(IO);
193 if (SendMsg->pCurrRelay != NULL)
194 SendMsg->pCurrRelay = SendMsg->pCurrRelay->Next;
196 if (SendMsg->pCurrRelay == NULL) {
197 EVS_syslog(LOG_DEBUG, "SMTP: %s Aborting\n", __FUNCTION__);
200 if (SendMsg->pCurrRelay->IsIP) {
201 EVS_syslog(LOG_DEBUG, "SMTP: %s connecting IP\n", __FUNCTION__);
202 return mx_connect_ip(IO);
205 EVS_syslog(LOG_DEBUG, "SMTP: %s resolving next MX Record\n", __FUNCTION__);
206 return get_one_mx_host_ip(IO);
211 void SetConnectStatus(AsyncIO *IO)
213 SmtpOutMsg *SendMsg = IO->Data;
219 if (IO->ConnectMe->IPv6) {
220 src = &IO->ConnectMe->Addr.sin6_addr;
223 struct sockaddr_in *addr = (struct sockaddr_in *)&IO->ConnectMe->Addr;
225 src = &addr->sin_addr.s_addr;
228 inet_ntop((IO->ConnectMe->IPv6)?AF_INET6:AF_INET,
233 if (SendMsg->mx_host == NULL)
234 SendMsg->mx_host = "<no MX-Record>";
236 EVS_syslog(LOG_DEBUG,
237 "SMTP client[%ld]: connecting to %s [%s]:%d ...\n",
241 SendMsg->IO.ConnectMe->Port);
243 SendMsg->MyQEntry->Status = 5;
244 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
245 "Timeout while connecting %s [%s]:%d ",
248 SendMsg->IO.ConnectMe->Port);
249 SendMsg->IO.NextState = eConnect;
252 /*****************************************************************************
253 * So we connect our Relay IP here. *
254 *****************************************************************************/
255 eNextState mx_connect_ip(AsyncIO *IO)
257 SmtpOutMsg *SendMsg = IO->Data;
259 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
261 IO->ConnectMe = SendMsg->pCurrRelay;
263 SetConnectStatus(IO);
265 return EvConnectSock(IO,
267 SMTP_C_ReadTimeouts[0],
271 eNextState get_one_mx_host_ip_done(AsyncIO *IO)
273 SmtpOutMsg *SendMsg = IO->Data;
274 struct hostent *hostent;
278 hostent = SendMsg->HostLookup.VParsedDNSReply;
279 if ((SendMsg->HostLookup.DNSStatus == ARES_SUCCESS) &&
280 (hostent != NULL) ) {
281 memset(&SendMsg->pCurrRelay->Addr, 0, sizeof(struct in6_addr));
282 if (SendMsg->pCurrRelay->IPv6) {
283 memcpy(&SendMsg->pCurrRelay->Addr.sin6_addr.s6_addr,
284 &hostent->h_addr_list[0],
285 sizeof(struct in6_addr));
287 SendMsg->pCurrRelay->Addr.sin6_family = hostent->h_addrtype;
288 SendMsg->pCurrRelay->Addr.sin6_port = htons(DefaultMXPort);
291 struct sockaddr_in *addr = (struct sockaddr_in*) &SendMsg->pCurrRelay->Addr;
292 /* Bypass the ns lookup result like this: IO->Addr.sin_addr.s_addr = inet_addr("127.0.0.1"); */
293 // addr->sin_addr.s_addr = htonl((uint32_t)&hostent->h_addr_list[0]);
294 memcpy(&addr->sin_addr.s_addr,
295 hostent->h_addr_list[0],
298 addr->sin_family = hostent->h_addrtype;
299 addr->sin_port = htons(DefaultMXPort);
302 SendMsg->mx_host = SendMsg->pCurrRelay->Host;
303 return mx_connect_ip(IO);
305 else // TODO: here we need to find out whether there are more mx'es, backup relay, and so on
306 return FailOneAttempt(IO);
309 eNextState get_one_mx_host_ip(AsyncIO *IO)
311 SmtpOutMsg * SendMsg = IO->Data;
313 * here we start with the lookup of one host. it might be...
314 * - the relay host *sigh*
315 * - the direct hostname if there was no mx record
321 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
323 EVS_syslog(LOG_DEBUG,
324 "SMTP client[%ld]: looking up %s-Record %s : %d ...\n",
326 (SendMsg->pCurrRelay->IPv6)? "aaaa": "a",
327 SendMsg->pCurrRelay->Host,
328 SendMsg->pCurrRelay->Port);
330 if (!QueueQuery((SendMsg->pCurrRelay->IPv6)? ns_t_aaaa : ns_t_a,
331 SendMsg->pCurrRelay->Host,
333 &SendMsg->HostLookup,
334 get_one_mx_host_ip_done))
336 SendMsg->MyQEntry->Status = 5;
337 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
338 "No MX hosts found for <%s>", SendMsg->node);
339 SendMsg->IO.NextState = eTerminateConnection;
340 return IO->NextState;
342 IO->NextState = eReadDNSReply;
343 return IO->NextState;
347 /*****************************************************************************
348 * here we try to find out about the MX records for our recipients. *
349 *****************************************************************************/
350 eNextState smtp_resolve_mx_record_done(AsyncIO *IO)
352 SmtpOutMsg * SendMsg = IO->Data;
357 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
358 pp = &SendMsg->Relay;
359 while ((pp != NULL) && (*pp != NULL) && ((*pp)->Next != NULL))
362 if ((IO->DNS.Query->DNSStatus == ARES_SUCCESS) &&
363 (IO->DNS.Query->VParsedDNSReply != NULL))
364 { /* ok, we found mx records. */
365 SendMsg->IO.ErrMsg = SendMsg->MyQEntry->StatusMessage;
367 SendMsg->CurrMX = SendMsg->AllMX
368 = IO->DNS.Query->VParsedDNSReply;
369 while (SendMsg->CurrMX) {
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->CurrMX->host;
384 SendMsg->CurrMX = SendMsg->CurrMX->next;
386 SendMsg->CXFlags = SendMsg->CXFlags & F_HAVE_MX;
388 else { /* else fall back to the plain hostname */
390 for (i = 0; i < 2; i++) {
393 p = (ParsedURL*) malloc(sizeof(ParsedURL));
394 memset(p, 0, sizeof(ParsedURL));
396 p->Port = DefaultMXPort;
398 p->Host = SendMsg->node;
403 SendMsg->CXFlags = SendMsg->CXFlags & F_DIRECT;
405 *pp = SendMsg->MyQItem->FallBackHost;
406 SendMsg->pCurrRelay = SendMsg->Relay;
407 return get_one_mx_host_ip(IO);
410 eNextState resolve_mx_records(AsyncIO *IO)
412 SmtpOutMsg * SendMsg = IO->Data;
414 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
415 /* start resolving MX records here. */
416 if (!QueueQuery(ns_t_mx,
420 smtp_resolve_mx_record_done))
422 SendMsg->MyQEntry->Status = 5;
423 StrBufPrintf(SendMsg->MyQEntry->StatusMessage,
424 "No MX hosts found for <%s>", SendMsg->node);
425 return IO->NextState;
427 SendMsg->IO.NextState = eReadDNSReply;
428 return IO->NextState;
433 /******************************************************************************
434 * so, we're going to start a SMTP delivery. lets get it on. *
435 ******************************************************************************/
437 SmtpOutMsg *new_smtp_outmsg(OneQueItem *MyQItem,
438 MailQEntry *MyQEntry,
441 SmtpOutMsg * SendMsg;
443 SendMsg = (SmtpOutMsg *) malloc(sizeof(SmtpOutMsg));
444 memset(SendMsg, 0, sizeof(SmtpOutMsg));
446 SendMsg->n = MsgCount;
447 SendMsg->MyQEntry = MyQEntry;
448 SendMsg->MyQItem = MyQItem;
449 SendMsg->pCurrRelay = MyQItem->URL;
451 InitIOStruct(&SendMsg->IO,
454 SMTP_C_ReadServerStatus,
456 SMTP_C_DispatchWriteDone,
457 SMTP_C_DispatchReadDone,
466 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
467 MailQEntry *MyQEntry,
469 int KeepMsgText, /* KeepMsgText allows us to use MsgText as ours. */
474 syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
476 SendMsg = new_smtp_outmsg(MyQItem, MyQEntry, MsgCount);
477 if (KeepMsgText) SendMsg->msgtext = MsgText;
478 else SendMsg->msgtext = NewStrBufDup(MsgText);
480 if (smtp_resolve_recipients(SendMsg)) {
483 ((CitContext *)SendMsg->IO.CitContext)->cs_host,
485 sizeof(((CitContext *)SendMsg->IO.CitContext)->cs_host));
487 syslog(LOG_DEBUG, "SMTP Starting: [%ld] <%s> CC <%d> \n",
488 SendMsg->MyQItem->MessageID,
489 ChrPtr(SendMsg->MyQEntry->Recipient),
490 ((CitContext*)SendMsg->IO.CitContext)->cs_pid);
491 if (SendMsg->pCurrRelay == NULL)
492 QueueEventContext(&SendMsg->IO,
494 else { /* oh... via relay host */
495 if (SendMsg->pCurrRelay->IsIP) {
496 QueueEventContext(&SendMsg->IO,
499 else { /* uneducated admin has chosen to add DNS to the equation... */
500 QueueEventContext(&SendMsg->IO,
506 /* No recipients? well fail then. */
507 if ((SendMsg==NULL) ||
508 (SendMsg->MyQEntry == NULL)) {
509 SendMsg->MyQEntry->Status = 5;
510 StrBufPlain(SendMsg->MyQEntry->StatusMessage,
511 HKEY("Invalid Recipient!"));
513 FinalizeMessageSend(SendMsg);
522 /*****************************************************************************/
523 /* SMTP CLIENT DISPATCHER */
524 /*****************************************************************************/
526 void SMTPSetTimeout(eNextState NextTCPState, SmtpOutMsg *pMsg)
528 double Timeout = 0.0;
529 AsyncIO *IO = &pMsg->IO;
531 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
533 switch (NextTCPState) {
537 Timeout = SMTP_C_SendTimeouts[pMsg->State];
538 if (pMsg->State == eDATABody) {
539 /* if we're sending a huge message, we need more time. */
540 Timeout += StrLength(pMsg->msgtext) / 1024;
544 Timeout = SMTP_C_ReadTimeouts[pMsg->State];
545 if (pMsg->State == eDATATerminateBody) {
547 * some mailservers take a nap before accepting the message
548 * content inspection and such.
550 Timeout += StrLength(pMsg->msgtext) / 1024;
560 case eTerminateConnection:
564 SetNextTimeout(&pMsg->IO, Timeout);
566 eNextState SMTP_C_DispatchReadDone(AsyncIO *IO)
568 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
569 SmtpOutMsg *pMsg = IO->Data;
572 rc = ReadHandlers[pMsg->State](pMsg);
576 SMTPSetTimeout(rc, pMsg);
580 eNextState SMTP_C_DispatchWriteDone(AsyncIO *IO)
582 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
583 SmtpOutMsg *pMsg = IO->Data;
586 rc = SendHandlers[pMsg->State](pMsg);
587 SMTPSetTimeout(rc, pMsg);
592 /*****************************************************************************/
593 /* SMTP CLIENT ERROR CATCHERS */
594 /*****************************************************************************/
595 eNextState SMTP_C_Terminate(AsyncIO *IO)
597 SmtpOutMsg *pMsg = IO->Data;
599 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
600 FinalizeMessageSend(pMsg);
603 eNextState SMTP_C_Timeout(AsyncIO *IO)
605 SmtpOutMsg *pMsg = IO->Data;
607 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
608 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
609 return FailOneAttempt(IO);
611 eNextState SMTP_C_ConnFail(AsyncIO *IO)
613 SmtpOutMsg *pMsg = IO->Data;
615 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
616 StrBufPlain(IO->ErrMsg, CKEY(ReadErrors[pMsg->State]));
617 return FailOneAttempt(IO);
619 eNextState SMTP_C_DNSFail(AsyncIO *IO)
621 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
622 return FailOneAttempt(IO);
624 eNextState SMTP_C_Shutdown(AsyncIO *IO)
626 EVS_syslog(LOG_DEBUG, "SMTP: %s\n", __FUNCTION__);
627 SmtpOutMsg *pMsg = IO->Data;
629 pMsg->MyQEntry->Status = 3;
630 StrBufPlain(pMsg->MyQEntry->StatusMessage, HKEY("server shutdown during message submit."));
631 FinalizeMessageSend(pMsg);
637 * @brief lineread Handler; understands when to read more SMTP lines, and when this is a one-lined reply.
639 eReadState SMTP_C_ReadServerStatus(AsyncIO *IO)
641 eReadState Finished = eBufferNotEmpty;
643 while (Finished == eBufferNotEmpty) {
644 Finished = StrBufChunkSipLine(IO->IOBuf, &IO->RecvBuf);
647 case eMustReadMore: /// read new from socket...
650 case eBufferNotEmpty: /* shouldn't happen... */
651 case eReadSuccess: /// done for now...
652 if (StrLength(IO->IOBuf) < 4)
654 if (ChrPtr(IO->IOBuf)[3] == '-')
655 Finished = eBufferNotEmpty;
659 case eReadFail: /// WHUT?
667 CTDL_MODULE_INIT(smtp_eventclient)
669 return "smtpeventclient";