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-2015 by the citadel.org team
25 * This program is open source software; you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License version 3.
28 * This program is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU General Public License for more details.
43 #include <sys/types.h>
46 #if TIME_WITH_SYS_TIME
47 # include <sys/time.h>
51 # include <sys/time.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
63 #include <libcitadel.h>
66 #include "citserver.h"
73 #include "internet_addressing.h"
76 #include "clientsocket.h"
77 #include "locate_host.h"
78 #include "citadel_dirs.h"
80 #include "ctdl_module.h"
82 #include "smtpqueue.h"
83 #include "smtp_clienthandlers.h"
84 #include "event_client.h"
87 struct CitContext smtp_queue_CC;
88 pthread_mutex_t ActiveQItemsLock;
89 HashList *ActiveQItems = NULL;
90 HashList *QItemHandlers = NULL;
91 const unsigned short DefaultMXPort = 25;
92 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
93 int ndelay_count = 50; /* every n queued messages we will sleep... */
94 int delay_msec = 5000; /* this many seconds. */
96 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
98 int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
100 void RegisterQItemHandler(const char *Key, long Len, QItemHandler H)
102 QItemHandlerStruct *HS = (QItemHandlerStruct*)malloc(sizeof(QItemHandlerStruct));
104 Put(QItemHandlers, Key, Len, HS, NULL);
109 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
110 MailQEntry *MyQEntry,
112 /* KeepMsgText allows us to use MsgText as ours. */
115 ParsedURL *RelayUrls);
118 void smtp_evq_cleanup(void)
121 pthread_mutex_lock(&ActiveQItemsLock);
122 DeleteHash(&QItemHandlers);
123 DeleteHash(&ActiveQItems);
124 pthread_mutex_unlock(&ActiveQItemsLock);
125 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
126 /* citthread_mutex_destroy(&ActiveQItemsLock); TODO */
129 int DecreaseQReference(OneQueItem *MyQItem)
131 int IDestructQueItem;
133 pthread_mutex_lock(&ActiveQItemsLock);
134 MyQItem->ActiveDeliveries--;
135 IDestructQueItem = MyQItem->ActiveDeliveries == 0;
136 pthread_mutex_unlock(&ActiveQItemsLock);
137 return IDestructQueItem;
140 void DecreaseShutdownDeliveries(OneQueItem *MyQItem)
142 pthread_mutex_lock(&ActiveQItemsLock);
143 MyQItem->NotYetShutdownDeliveries--;
144 pthread_mutex_unlock(&ActiveQItemsLock);
147 int GetShutdownDeliveries(OneQueItem *MyQItem)
151 pthread_mutex_lock(&ActiveQItemsLock);
152 DestructNow = MyQItem->ActiveDeliveries == 0;
153 pthread_mutex_unlock(&ActiveQItemsLock);
156 void RemoveQItem(OneQueItem *MyQItem)
163 pthread_mutex_lock(&ActiveQItemsLock);
164 It = GetNewHashPos(ActiveQItems, 0);
165 if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
166 DeleteEntryFromHash(ActiveQItems, It);
169 SMTPC_syslog(LOG_WARNING,
170 "unable to find QItem with ID[%ld]",
172 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
173 SMTPC_syslog(LOG_WARNING,
175 ((OneQueItem *)VData)->MessageID);
177 pthread_mutex_unlock(&ActiveQItemsLock);
182 void FreeMailQEntry(void *qv)
186 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
189 FreeStrBuf(&Q->Recipient);
190 FreeStrBuf(&Q->StatusMessage);
191 FreeStrBuf(&Q->AllStatusMessages);
192 memset(Q, 0, sizeof(MailQEntry));
195 void FreeQueItem(OneQueItem **Item)
198 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
201 DeleteHash(&(*Item)->MailQEntries);
202 FreeStrBuf(&(*Item)->EnvelopeFrom);
203 FreeStrBuf(&(*Item)->BounceTo);
204 FreeStrBuf(&(*Item)->SenderRoom);
205 FreeURL(&(*Item)->URL);
206 memset(*Item, 0, sizeof(OneQueItem));
210 void HFreeQueItem(void *Item)
212 FreeQueItem((OneQueItem**)&Item);
215 /* inspect recipients with a status of:
216 * - 0 (no delivery yet attempted)
217 * - 3/4 (transient errors
218 * were experienced and it's time to try again)
220 int CheckQEntryActive(MailQEntry *ThisItem)
222 if ((ThisItem->Status == 0) ||
223 (ThisItem->Status == 3) ||
224 (ThisItem->Status == 4))
231 int CheckQEntryIsBounce(MailQEntry *ThisItem)
233 if ((ThisItem->Status == 3) ||
234 (ThisItem->Status == 4) ||
235 (ThisItem->Status == 5))
243 int CountActiveQueueEntries(OneQueItem *MyQItem, int before)
247 long ActiveDeliveries;
251 ActiveDeliveries = 0;
252 It = GetNewHashPos(MyQItem->MailQEntries, 0);
253 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
256 MailQEntry *ThisItem = vQE;
258 if (CheckQEntryActive(ThisItem))
266 ThisItem->Active = Active;
268 ThisItem->StillActive = Active;
271 return ActiveDeliveries;
274 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
277 const char *pLine = NULL;
282 Item = (OneQueItem*)malloc(sizeof(OneQueItem));
283 memset(Item, 0, sizeof(OneQueItem));
284 Item->Retry = SMTP_RETRY_INTERVAL;
285 Item->MessageID = -1;
286 Item->QueMsgID = QueMsgID;
289 Line = NewStrBufPlain(NULL, 128);
290 while (pLine != StrBufNOTNULL) {
291 const char *pItemPart = NULL;
294 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
295 if (StrLength(Line) == 0) continue;
296 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
297 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
299 QItemHandlerStruct *HS;
300 HS = (QItemHandlerStruct*) vHandler;
301 HS->H(Item, Line, &pItemPart);
307 if (Item->Retry >= MaxRetry)
310 pthread_mutex_lock(&ActiveQItemsLock);
311 if (GetHash(ActiveQItems,
312 LKEY(Item->MessageID),
315 /* WHOOPS. somebody else is already working on this. */
316 pthread_mutex_unlock(&ActiveQItemsLock);
321 /* mark our claim on this. */
323 LKEY(Item->MessageID),
326 pthread_mutex_unlock(&ActiveQItemsLock);
332 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
340 QMessage = NewStrBufPlain(NULL, SIZ);
341 StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
342 // "attempted|%ld\n" "retry|%ld\n",, (long)time(NULL), (long)retry );
343 StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
344 StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
346 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
347 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
349 if (StrLength(MyQItem->BounceTo) > 0) {
350 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
351 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
354 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
355 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
356 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
359 if (StrLength(MyQItem->SenderRoom) > 0) {
360 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
361 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
364 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
365 StrBufAppendPrintf(QMessage, "%ld",
368 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
369 StrBufAppendPrintf(QMessage, "%ld",
370 time(NULL) /*ctdl_ev_now()*/ + MyQItem->Retry);
372 It = GetNewHashPos(MyQItem->MailQEntries, 0);
373 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
375 MailQEntry *ThisItem = vQE;
377 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
378 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
379 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
380 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
381 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
382 if (ThisItem->AllStatusMessages != NULL)
383 StrBufAppendBuf(QMessage, ThisItem->AllStatusMessages, 0);
385 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
388 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
396 void NewMailQEntry(OneQueItem *Item)
398 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
399 memset(Item->Current, 0, sizeof(MailQEntry));
401 if (Item->MailQEntries == NULL)
402 Item->MailQEntries = NewHash(1, Flathash);
403 /* alocate big buffer so we won't get problems reallocating later. */
404 Item->Current->StatusMessage = NewStrBufPlain(NULL, SIZ);
405 Item->Current->n = GetCount(Item->MailQEntries);
406 Put(Item->MailQEntries,
407 IKEY(Item->Current->n),
412 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
414 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
417 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
419 if (Item->EnvelopeFrom == NULL)
420 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
421 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
424 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
426 if (Item->BounceTo == NULL)
427 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
428 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
431 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
433 if (Item->SenderRoom == NULL)
434 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
435 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
438 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
440 if (Item->Current == NULL)
442 if (Item->Current->Recipient == NULL)
443 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
444 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
445 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
446 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
447 Item->Current = NULL; // TODO: is this always right?
451 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
454 StrBufExtractNext_int(Line, Pos, '|');
455 if (Item->Retry == 0)
456 Item->Retry = SMTP_RETRY_INTERVAL;
462 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
464 Item->Submitted = atol(*Pos);
468 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
470 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
476 * this one has to have the context for loading the message via the redirect buffer...
478 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n, char **Author, char **Address)
483 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
484 CtdlOutputMsg(MyQItem->MessageID,
485 MT_RFC822, HEADERS_ALL,
487 (ESC_DOT|SUPPRESS_ENV_TO),
492 SendMsg = CCC->redirect_buffer;
493 CCC->redirect_buffer = NULL;
494 if ((StrLength(SendMsg) > 0) &&
495 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
496 SMTPC_syslog(LOG_WARNING,
497 "[%d] Possible problem: message did not "
498 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
499 MsgCount, //yes uncool, but best choice here...
500 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
501 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
509 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
510 * instructions for "5" codes (permanent fatal errors) and produce/deliver
511 * a "bounce" message (delivery status notification).
513 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt, ParsedURL *Relay)
517 struct CtdlMessage *bmsg = NULL;
529 int first_attempt = 0;
530 int successful_bounce = 0;
534 SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
536 if (MyQItem->SendBounceMail == 0)
539 now = time (NULL); //ev_time();
541 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
545 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
550 * Now go through the instructions checking for stuff.
552 Msg = NewStrBufPlain(NULL, 1024);
553 It = GetNewHashPos(MyQItem->MailQEntries, 0);
554 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
556 MailQEntry *ThisItem = vQE;
557 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
558 ((give_up == 1) && (ThisItem->Status != 2)) ||
559 ((first_attempt == 1) && (ThisItem->Status != 2)))
560 /* giving up after failed attempts... */
564 StrBufAppendBufPlain(Msg, HKEY(" "), 0);
565 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
566 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
567 if (ThisItem->AllStatusMessages != NULL)
568 StrBufAppendBuf(Msg, ThisItem->AllStatusMessages, 0);
570 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
571 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
576 /* Deliver the bounce if there's anything worth mentioning */
577 SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
579 if (num_bounces == 0) {
584 if ((StrLength(MyQItem->SenderRoom) == 0) && MyQItem->HaveRelay) {
585 const char *RelayUrlStr = "[not found]";
586 /* one message that relaying is broken is enough; no extra room error message. */
587 StrBuf *RelayDetails = NewStrBuf();
590 RelayUrlStr = ChrPtr(Relay->URL);
592 StrBufPrintf(RelayDetails,
593 "Relaying via %s failed permanently. \n Reason:\n%s\n Revalidate your relay configuration.",
596 CtdlAideMessage(ChrPtr(RelayDetails), "Relaying Failed");
597 FreeStrBuf(&RelayDetails);
600 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
601 StrBufAppendPrintf(boundary,
603 CtdlGetConfigStr("c_fqdn"),
607 /* Start building our bounce message; go shopping for memory first. */
608 BounceMB = NewStrBufPlain(
610 1024 + /* mime stuff.... */
611 StrLength(Msg) + /* the bounce information... */
612 StrLength(OMsgTxt)); /* the original message */
613 if (BounceMB == NULL) {
614 FreeStrBuf(&boundary);
615 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
620 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
622 FreeStrBuf(&boundary);
623 FreeStrBuf(&BounceMB);
624 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
628 memset(bmsg, 0, sizeof(struct CtdlMessage));
631 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
632 StrBufAppendBuf(BounceMB, boundary, 0);
633 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
634 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
635 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
636 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
637 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
638 StrBufAppendBuf(BounceMB, boundary, 0);
639 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
640 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
643 StrBufAppendBufPlain(
646 "A message you sent could not be delivered "
647 "to some or all of its recipients\n"
648 "due to prolonged unavailability "
649 "of its destination(s).\n"
650 "Giving up on the following addresses:\n\n"
653 StrBufAppendBufPlain(
656 "A message you sent could not be delivered "
657 "to some or all of its recipients.\n"
658 "The following addresses "
659 "were undeliverable:\n\n"
662 StrBufAppendBuf(BounceMB, Msg, 0);
665 if (StrLength(MyQItem->SenderRoom) > 0)
667 StrBufAppendBufPlain(
669 HKEY("The message was originaly posted in: "), 0);
670 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
671 StrBufAppendBufPlain(
676 /* Attach the original message */
677 StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
678 StrBufAppendBuf(BounceMB, boundary, 0);
679 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
680 StrBufAppendBufPlain(BounceMB,
681 HKEY("Content-type: message/rfc822\r\n"), 0);
682 StrBufAppendBufPlain(BounceMB,
683 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
684 StrBufAppendBufPlain(BounceMB,
685 HKEY("Content-Disposition: inline\r\n"), 0);
686 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
687 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
689 /* Close the multipart MIME scope */
690 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
691 StrBufAppendBuf(BounceMB, boundary, 0);
692 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
694 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
695 bmsg->cm_anon_type = MES_NORMAL;
696 bmsg->cm_format_type = FMT_RFC822;
698 CM_SetField(bmsg, eOriginalRoom, HKEY(MAILROOM));
699 CM_SetField(bmsg, eAuthor, HKEY("Citadel"));
700 CM_SetField(bmsg, eNodeName, CtdlGetConfigStr("c_nodename"), strlen(CtdlGetConfigStr("c_nodename")));
701 CM_SetField(bmsg, eMsgSubject, HKEY("Delivery Status Notification (Failure)"));
702 CM_SetAsFieldSB(bmsg, eMesageText, &BounceMB);
704 /* First try the user who sent the message */
705 if (StrLength(MyQItem->BounceTo) == 0) {
706 SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
709 SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
710 ChrPtr(MyQItem->BounceTo));
713 /* Can we deliver the bounce to the original sender? */
714 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
715 if ((valid != NULL) && (valid->num_error == 0)) {
716 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
717 successful_bounce = 1;
720 /* If not, post it in the Aide> room */
721 if (successful_bounce == 0) {
722 CtdlSubmitMsg(bmsg, NULL, CtdlGetConfigStr("c_aideroom"), QP_EADDR);
725 /* Free up the memory we used */
726 free_recipients(valid);
727 FreeStrBuf(&boundary);
729 SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
732 ParsedURL *LoadRelayUrls(OneQueItem *MyQItem,
737 ParsedURL *RelayUrls = NULL;
739 ParsedURL **Url = &MyQItem->URL;
741 nRelays = get_hosts(mxbuf, "fallbackhost");
745 const char *Pos = NULL;
746 All = NewStrBufPlain(mxbuf, -1);
747 One = NewStrBufPlain(NULL, StrLength(All) + 1);
749 while ((Pos != StrBufNOTNULL) &&
753 StrBufExtract_NextToken(One, All, &Pos, '|');
754 if (!ParseURL(Url, One, DefaultMXPort)) {
755 SMTPC_syslog(LOG_DEBUG,
756 "Failed to parse: %s\n",
761 MyQItem->HaveRelay = 1;
767 nRelays = get_hosts(mxbuf, "smarthost");
772 const char *Pos = NULL;
773 All = NewStrBufPlain(mxbuf, -1);
774 One = NewStrBufPlain(NULL, StrLength(All) + 1);
776 while ((Pos != StrBufNOTNULL) &&
780 StrBufExtract_NextToken(One, All, &Pos, '|');
781 User = strchr(ChrPtr(One), ' ');
783 if (!strcmp(User + 1, Author) ||
784 !strcmp(User + 1, Address))
785 StrBufCutAt(One, 0, User);
787 MyQItem->HaveRelay = 1;
791 if (!ParseURL(Url, One, DefaultMXPort)) {
792 SMTPC_syslog(LOG_DEBUG,
793 "Failed to parse: %s\n",
797 ///if (!Url->IsIP)) // todo dupe me fork ipv6
799 MyQItem->HaveRelay = 1;
810 * Called by smtp_do_queue() to handle an individual message.
812 void smtp_do_procmsg(long msgnum, void *userdata) {
814 int mynumsessions = num_sessions;
815 struct CtdlMessage *msg = NULL;
817 char *Address = NULL;
829 if (mynumsessions > max_sessions_for_outbound_smtp) {
830 SMTPC_syslog(LOG_INFO,
831 "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
833 max_sessions_for_outbound_smtp);
836 SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
837 ///strcpy(envelope_from, "");
839 msg = CtdlFetchMessage(msgnum, 1);
841 SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
846 pch = instr = msg->cm_fields[eMesageText];
848 /* Strip out the headers (no not amd any other non-instruction) line */
849 while (pch != NULL) {
850 pch = strchr(pch, '\n');
852 ((*(pch + 1) == '\n') ||
853 (*(pch + 1) == '\r')))
859 PlainQItem = NewStrBufPlain(instr, -1);
861 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
862 FreeStrBuf(&PlainQItem);
864 if (MyQItem == NULL) {
865 SMTPC_syslog(LOG_ERR,
866 "Msg No %ld: already in progress!\n",
868 return; /* s.b. else is already processing... */
872 * Postpone delivery if we've already tried recently.
875 if ((MyQItem->ReattemptWhen != 0) &&
876 (now < MyQItem->ReattemptWhen) &&
877 (run_queue_now == 0))
879 SMTPC_syslog(LOG_DEBUG,
880 "Retry time not yet reached. %ld seconds left.",
881 MyQItem->ReattemptWhen - now);
883 It = GetNewHashPos(MyQItem->MailQEntries, 0);
884 pthread_mutex_lock(&ActiveQItemsLock);
886 if (GetHashPosFromKey(ActiveQItems,
887 LKEY(MyQItem->MessageID),
890 DeleteEntryFromHash(ActiveQItems, It);
893 pthread_mutex_unlock(&ActiveQItemsLock);
894 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
900 * Bail out if there's no actual message associated with this
902 if (MyQItem->MessageID < 0L) {
903 SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
904 It = GetNewHashPos(MyQItem->MailQEntries, 0);
905 pthread_mutex_lock(&ActiveQItemsLock);
907 if (GetHashPosFromKey(ActiveQItems,
908 LKEY(MyQItem->MessageID),
911 DeleteEntryFromHash(ActiveQItems, It);
914 pthread_mutex_unlock(&ActiveQItemsLock);
916 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
921 It = GetNewHashPos(MyQItem->MailQEntries, 0);
922 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
924 MailQEntry *ThisItem = vQE;
925 SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
926 ChrPtr(ThisItem->Recipient),
931 MyQItem->NotYetShutdownDeliveries =
932 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem, 1);
934 /* failsafe against overload:
935 * will we exceed the limit set?
937 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
938 /* if yes, did we reach more than half of the quota? */
939 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
940 /* if... would we ever fit into half of the quota?? */
941 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
943 /* abort delivery for another time. */
944 SMTPC_syslog(LOG_INFO,
945 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
947 MyQItem->ActiveDeliveries,
948 max_sessions_for_outbound_smtp);
950 It = GetNewHashPos(MyQItem->MailQEntries, 0);
951 pthread_mutex_lock(&ActiveQItemsLock);
953 if (GetHashPosFromKey(ActiveQItems,
954 LKEY(MyQItem->MessageID),
957 DeleteEntryFromHash(ActiveQItems, It);
960 pthread_mutex_unlock(&ActiveQItemsLock);
966 if (MyQItem->ActiveDeliveries > 0)
968 ParsedURL *RelayUrls = NULL;
971 int m = MyQItem->ActiveDeliveries;
974 It = GetNewHashPos(MyQItem->MailQEntries, 0);
976 Msg = smtp_load_msg(MyQItem, n, &Author, &Address);
977 RelayUrls = LoadRelayUrls(MyQItem, Author, Address);
978 if ((RelayUrls == NULL) && MyQItem->HaveRelay) {
981 (GetNextHashPos(MyQItem->MailQEntries,
982 It, &len, &Key, &vQE)))
984 int KeepBuffers = (i == m);
985 MailQEntry *ThisItem = vQE;
986 StrBufPrintf(ThisItem->StatusMessage,
987 "No relay configured matching %s / %s",
988 (Author != NULL)? Author : "",
989 (Address != NULL)? Address : "");
990 ThisItem->Status = 5;
994 if (i > 1) n = MsgCount++;
996 "SMTPC: giving up on <%ld> <%s> %d / %d \n",
998 ChrPtr(ThisItem->Recipient),
1001 (*((int*) userdata)) ++;
1002 smtp_try_one_queue_entry(MyQItem,
1009 if (KeepBuffers) HaveBuffers++;
1013 if (Author != NULL) free (Author);
1014 if (Address != NULL) free (Address);
1019 if (Author != NULL) free (Author);
1020 if (Address != NULL) free (Address);
1023 (GetNextHashPos(MyQItem->MailQEntries,
1024 It, &len, &Key, &vQE)))
1026 MailQEntry *ThisItem = vQE;
1028 if (ThisItem->Active == 1)
1030 int KeepBuffers = (i == m);
1033 if (nActivated % ndelay_count == 0)
1036 if (i > 1) n = MsgCount++;
1038 "SMTPC: Trying <%ld> <%s> %d / %d \n",
1040 ChrPtr(ThisItem->Recipient),
1043 (*((int*) userdata)) ++;
1044 smtp_try_one_queue_entry(MyQItem,
1051 if (KeepBuffers) HaveBuffers++;
1060 It = GetNewHashPos(MyQItem->MailQEntries, 0);
1061 pthread_mutex_lock(&ActiveQItemsLock);
1063 if (GetHashPosFromKey(ActiveQItems,
1064 LKEY(MyQItem->MessageID),
1067 DeleteEntryFromHash(ActiveQItems, It);
1075 SMTPC_syslog(LOG_WARNING,
1076 "unable to find QItem with ID[%ld]",
1077 MyQItem->MessageID);
1078 while (GetNextHashPos(ActiveQItems,
1084 SMTPC_syslog(LOG_WARNING,
1086 ((OneQueItem *)VData)->MessageID);
1091 pthread_mutex_unlock(&ActiveQItemsLock);
1093 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
1095 // TODO: bounce & delete?
1100 // TODO : free RelayUrls
1107 * smtp_queue_thread()
1109 * Run through the queue sending out messages.
1111 void smtp_do_queue(void) {
1112 int num_processed = 0;
1113 int num_activated = 0;
1115 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
1116 SMTPCM_syslog(LOG_INFO, "processing outbound queue");
1118 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
1119 SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
1122 num_processed = CtdlForEachMessage(MSGS_ALL,
1130 SMTPC_syslog(LOG_INFO,
1131 "queue run completed; %d messages processed %d activated",
1132 num_processed, num_activated);
1139 * Initialize the SMTP outbound queue
1141 void smtp_init_spoolout(void) {
1142 struct ctdlroom qrbuf;
1145 * Create the room. This will silently fail if the room already
1146 * exists, and that's perfectly ok, because we want it to exist.
1148 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1151 * Make sure it's set to be a "system room" so it doesn't show up
1152 * in the <K>nown rooms list for Aides.
1154 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1155 qrbuf.QRflags2 |= QR2_SYSTEM;
1156 CtdlPutRoomLock(&qrbuf);
1163 /*****************************************************************************/
1164 /* SMTP UTILITY COMMANDS */
1165 /*****************************************************************************/
1167 void cmd_smtp(char *argbuf) {
1174 if (CtdlAccessCheck(ac_aide)) return;
1176 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1178 if (!strcasecmp(cmd, "mx")) {
1179 extract_token(node, argbuf, 1, '|', sizeof node);
1180 num_mxhosts = getmx(buf, node);
1181 cprintf("%d %d MX hosts listed for %s\n",
1182 LISTING_FOLLOWS, num_mxhosts, node);
1183 for (i=0; i<num_mxhosts; ++i) {
1184 extract_token(node, buf, i, '|', sizeof node);
1185 cprintf("%s\n", node);
1191 else if (!strcasecmp(cmd, "runqueue")) {
1193 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1198 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1203 int smtp_aftersave(struct CtdlMessage *msg,
1206 /* For internet mail, generate delivery instructions.
1207 * Yes, this is recursive. Deal with it. Infinite recursion does
1208 * not happen because the delivery instructions message does not
1209 * contain a recipient.
1211 if ((recps != NULL) && (recps->num_internet > 0)) {
1212 struct CtdlMessage *imsg = NULL;
1213 char recipient[SIZ];
1214 CitContext *CCC = MyContext();
1215 StrBuf *SpoolMsg = NewStrBuf();
1219 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
1221 StrBufPrintf(SpoolMsg,
1222 "Content-type: "SPOOLMIME"\n"
1227 msg->cm_fields[eVltMsgNum],
1231 if (recps->envelope_from != NULL) {
1232 StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
1233 StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
1234 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
1236 if (recps->sending_room != NULL) {
1237 StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
1238 StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
1239 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
1242 nTokens = num_tokens(recps->recp_internet, '|');
1243 for (i = 0; i < nTokens; i++) {
1245 len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
1247 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
1248 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
1249 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
1253 imsg = malloc(sizeof(struct CtdlMessage));
1254 memset(imsg, 0, sizeof(struct CtdlMessage));
1255 imsg->cm_magic = CTDLMESSAGE_MAGIC;
1256 imsg->cm_anon_type = MES_NORMAL;
1257 imsg->cm_format_type = FMT_RFC822;
1258 CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
1259 CM_SetField(imsg, eAuthor, HKEY("Citadel"));
1260 CM_SetField(imsg, eJournal, HKEY("do not journal"));
1261 CM_SetAsFieldSB(imsg, eMesageText, &SpoolMsg);
1262 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
1268 CTDL_MODULE_INIT(smtp_queu)
1274 pstr = getenv("CITSERVER_n_session_max");
1275 if ((pstr != NULL) && (*pstr != '\0'))
1276 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1278 pstr = getenv("CITSERVER_smtp_n_delay_count");
1279 if ((pstr != NULL) && (*pstr != '\0'))
1280 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1282 pstr = getenv("CITSERVER_smtp_delay");
1283 if ((pstr != NULL) && (*pstr != '\0'))
1284 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1286 CtdlRegisterMessageHook(smtp_aftersave, EVT_AFTERSAVE);
1288 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1289 ActiveQItems = NewHash(1, lFlathash);
1290 pthread_mutex_init(&ActiveQItemsLock, NULL);
1292 QItemHandlers = NewHash(0, NULL);
1294 RegisterQItemHandler(HKEY("msgid"), QItem_Handle_MsgID);
1295 RegisterQItemHandler(HKEY("envelope_from"), QItem_Handle_EnvelopeFrom);
1296 RegisterQItemHandler(HKEY("retry"), QItem_Handle_retry);
1297 RegisterQItemHandler(HKEY("attempted"), QItem_Handle_Attempted);
1298 RegisterQItemHandler(HKEY("remote"), QItem_Handle_Recipient);
1299 RegisterQItemHandler(HKEY("bounceto"), QItem_Handle_BounceTo);
1300 RegisterQItemHandler(HKEY("source_room"), QItem_Handle_SenderRoom);
1301 RegisterQItemHandler(HKEY("submitted"), QItem_Handle_Submitted);
1303 smtp_init_spoolout();
1305 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1307 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1308 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_SEND + 10);
1311 /* return our Subversion id for the Log */
1312 return "smtpeventclient";