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-2012 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.
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.
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 "smtpqueue.h"
89 #include "smtp_clienthandlers.h"
90 #include "event_client.h"
93 struct CitContext smtp_queue_CC;
94 pthread_mutex_t ActiveQItemsLock;
95 HashList *ActiveQItems = NULL;
96 HashList *QItemHandlers = NULL;
97 const unsigned short DefaultMXPort = 25;
98 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
99 int ndelay_count = 50; /* every n queued messages we will sleep... */
100 int delay_msec = 5000; /* this many seconds. */
102 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
104 int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
106 void RegisterQItemHandler(const char *Key, long Len, QItemHandler H)
108 QItemHandlerStruct *HS = (QItemHandlerStruct*)malloc(sizeof(QItemHandlerStruct));
110 Put(QItemHandlers, Key, Len, HS, NULL);
115 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
116 MailQEntry *MyQEntry,
118 /* KeepMsgText allows us to use MsgText as ours. */
121 ParsedURL *RelayUrls);
124 void smtp_evq_cleanup(void)
127 pthread_mutex_lock(&ActiveQItemsLock);
128 DeleteHash(&QItemHandlers);
129 DeleteHash(&ActiveQItems);
130 pthread_mutex_unlock(&ActiveQItemsLock);
131 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
132 /* citthread_mutex_destroy(&ActiveQItemsLock); TODO */
135 int DecreaseQReference(OneQueItem *MyQItem)
137 int IDestructQueItem;
139 pthread_mutex_lock(&ActiveQItemsLock);
140 MyQItem->ActiveDeliveries--;
141 IDestructQueItem = MyQItem->ActiveDeliveries == 0;
142 pthread_mutex_unlock(&ActiveQItemsLock);
143 return IDestructQueItem;
146 void DecreaseShutdownDeliveries(OneQueItem *MyQItem)
148 pthread_mutex_lock(&ActiveQItemsLock);
149 MyQItem->NotYetShutdownDeliveries--;
150 pthread_mutex_unlock(&ActiveQItemsLock);
153 int GetShutdownDeliveries(OneQueItem *MyQItem)
157 pthread_mutex_lock(&ActiveQItemsLock);
158 DestructNow = MyQItem->ActiveDeliveries == 0;
159 pthread_mutex_unlock(&ActiveQItemsLock);
162 void RemoveQItem(OneQueItem *MyQItem)
169 pthread_mutex_lock(&ActiveQItemsLock);
170 It = GetNewHashPos(ActiveQItems, 0);
171 if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
172 DeleteEntryFromHash(ActiveQItems, It);
175 SMTPC_syslog(LOG_WARNING,
176 "unable to find QItem with ID[%ld]",
178 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
179 SMTPC_syslog(LOG_WARNING,
181 ((OneQueItem *)VData)->MessageID);
183 pthread_mutex_unlock(&ActiveQItemsLock);
188 void FreeMailQEntry(void *qv)
192 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
195 FreeStrBuf(&Q->Recipient);
196 FreeStrBuf(&Q->StatusMessage);
197 FreeStrBuf(&Q->AllStatusMessages);
198 memset(Q, 0, sizeof(MailQEntry));
201 void FreeQueItem(OneQueItem **Item)
204 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
207 DeleteHash(&(*Item)->MailQEntries);
208 FreeStrBuf(&(*Item)->EnvelopeFrom);
209 FreeStrBuf(&(*Item)->BounceTo);
210 FreeStrBuf(&(*Item)->SenderRoom);
211 FreeURL(&(*Item)->URL);
212 memset(*Item, 0, sizeof(OneQueItem));
216 void HFreeQueItem(void *Item)
218 FreeQueItem((OneQueItem**)&Item);
221 /* inspect recipients with a status of:
222 * - 0 (no delivery yet attempted)
223 * - 3/4 (transient errors
224 * were experienced and it's time to try again)
226 int CheckQEntryActive(MailQEntry *ThisItem)
228 if ((ThisItem->Status == 0) ||
229 (ThisItem->Status == 3) ||
230 (ThisItem->Status == 4))
237 int CheckQEntryIsBounce(MailQEntry *ThisItem)
239 if ((ThisItem->Status == 3) ||
240 (ThisItem->Status == 4) ||
241 (ThisItem->Status == 5))
249 int CountActiveQueueEntries(OneQueItem *MyQItem, int before)
253 long ActiveDeliveries;
257 ActiveDeliveries = 0;
258 It = GetNewHashPos(MyQItem->MailQEntries, 0);
259 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
262 MailQEntry *ThisItem = vQE;
264 if (CheckQEntryActive(ThisItem))
272 ThisItem->Active = Active;
274 ThisItem->StillActive = Active;
277 return ActiveDeliveries;
280 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
283 const char *pLine = NULL;
288 Item = (OneQueItem*)malloc(sizeof(OneQueItem));
289 memset(Item, 0, sizeof(OneQueItem));
290 Item->Retry = SMTP_RETRY_INTERVAL;
291 Item->MessageID = -1;
292 Item->QueMsgID = QueMsgID;
295 Line = NewStrBufPlain(NULL, 128);
296 while (pLine != StrBufNOTNULL) {
297 const char *pItemPart = NULL;
300 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
301 if (StrLength(Line) == 0) continue;
302 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
303 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
305 QItemHandlerStruct *HS;
306 HS = (QItemHandlerStruct*) vHandler;
307 HS->H(Item, Line, &pItemPart);
313 if (Item->Retry >= MaxRetry)
316 pthread_mutex_lock(&ActiveQItemsLock);
317 if (GetHash(ActiveQItems,
318 LKEY(Item->MessageID),
321 /* WHOOPS. somebody else is already working on this. */
322 pthread_mutex_unlock(&ActiveQItemsLock);
327 /* mark our claim on this. */
329 LKEY(Item->MessageID),
332 pthread_mutex_unlock(&ActiveQItemsLock);
338 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
346 QMessage = NewStrBufPlain(NULL, SIZ);
347 StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
348 // "attempted|%ld\n" "retry|%ld\n",, (long)time(NULL), (long)retry );
349 StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
350 StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
352 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
353 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
355 if (StrLength(MyQItem->BounceTo) > 0) {
356 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
357 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
360 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
361 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
362 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
365 if (StrLength(MyQItem->SenderRoom) > 0) {
366 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
367 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
370 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
371 StrBufAppendPrintf(QMessage, "%ld",
374 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
375 StrBufAppendPrintf(QMessage, "%ld",
376 time(NULL) /*ctdl_ev_now()*/ + MyQItem->Retry);
378 It = GetNewHashPos(MyQItem->MailQEntries, 0);
379 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
381 MailQEntry *ThisItem = vQE;
383 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
384 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
385 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
386 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
387 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
388 if (ThisItem->AllStatusMessages != NULL)
389 StrBufAppendBuf(QMessage, ThisItem->AllStatusMessages, 0);
391 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
394 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
402 void NewMailQEntry(OneQueItem *Item)
404 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
405 memset(Item->Current, 0, sizeof(MailQEntry));
407 if (Item->MailQEntries == NULL)
408 Item->MailQEntries = NewHash(1, Flathash);
409 /* alocate big buffer so we won't get problems reallocating later. */
410 Item->Current->StatusMessage = NewStrBufPlain(NULL, SIZ);
411 Item->Current->n = GetCount(Item->MailQEntries);
412 Put(Item->MailQEntries,
413 IKEY(Item->Current->n),
418 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
420 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
423 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
425 if (Item->EnvelopeFrom == NULL)
426 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
427 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
430 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
432 if (Item->BounceTo == NULL)
433 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
434 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
437 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
439 if (Item->SenderRoom == NULL)
440 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
441 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
444 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
446 if (Item->Current == NULL)
448 if (Item->Current->Recipient == NULL)
449 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
450 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
451 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
452 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
453 Item->Current = NULL; // TODO: is this always right?
457 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
460 StrBufExtractNext_int(Line, Pos, '|');
461 if (Item->Retry == 0)
462 Item->Retry = SMTP_RETRY_INTERVAL;
468 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
470 Item->Submitted = atol(*Pos);
474 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
476 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
482 * this one has to have the context for loading the message via the redirect buffer...
484 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n, char **Author, char **Address)
489 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
490 CtdlOutputMsg(MyQItem->MessageID,
491 MT_RFC822, HEADERS_ALL,
493 (ESC_DOT|SUPPRESS_ENV_TO),
497 SendMsg = CCC->redirect_buffer;
498 CCC->redirect_buffer = NULL;
499 if ((StrLength(SendMsg) > 0) &&
500 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
501 SMTPC_syslog(LOG_WARNING,
502 "[%d] Possible problem: message did not "
503 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
504 MsgCount, //yes uncool, but best choice here...
505 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
506 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
514 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
515 * instructions for "5" codes (permanent fatal errors) and produce/deliver
516 * a "bounce" message (delivery status notification).
518 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt, ParsedURL *Relay)
522 struct CtdlMessage *bmsg = NULL;
534 int first_attempt = 0;
535 int successful_bounce = 0;
539 SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
541 if (MyQItem->SendBounceMail == 0)
544 now = time (NULL); //ev_time();
546 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
550 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
555 * Now go through the instructions checking for stuff.
557 Msg = NewStrBufPlain(NULL, 1024);
558 It = GetNewHashPos(MyQItem->MailQEntries, 0);
559 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
561 MailQEntry *ThisItem = vQE;
562 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
563 ((give_up == 1) && (ThisItem->Status != 2)) ||
564 ((first_attempt == 1) && (ThisItem->Status != 2)))
565 /* giving up after failed attempts... */
569 StrBufAppendBufPlain(Msg, HKEY(" "), 0);
570 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
571 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
572 if (ThisItem->AllStatusMessages != NULL)
573 StrBufAppendBuf(Msg, ThisItem->AllStatusMessages, 0);
575 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
576 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
581 /* Deliver the bounce if there's anything worth mentioning */
582 SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
584 if (num_bounces == 0) {
589 if ((StrLength(MyQItem->SenderRoom) == 0) && MyQItem->HaveRelay) {
590 const char *RelayUrlStr = "[not found]";
591 /* one message that relaying is broken is enough; no extra room error message. */
592 StrBuf *RelayDetails = NewStrBuf();
595 RelayUrlStr = ChrPtr(Relay->URL);
597 StrBufPrintf(RelayDetails,
598 "Relaying via %s failed permanently. \n Reason:\n%s\n Revalidate your relay configuration.",
601 CtdlAideMessage(ChrPtr(RelayDetails), "Relaying Failed");
602 FreeStrBuf(&RelayDetails);
605 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
606 StrBufAppendPrintf(boundary,
612 /* Start building our bounce message; go shopping for memory first. */
613 BounceMB = NewStrBufPlain(
615 1024 + /* mime stuff.... */
616 StrLength(Msg) + /* the bounce information... */
617 StrLength(OMsgTxt)); /* the original message */
618 if (BounceMB == NULL) {
619 FreeStrBuf(&boundary);
620 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
625 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
627 FreeStrBuf(&boundary);
628 FreeStrBuf(&BounceMB);
629 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
633 memset(bmsg, 0, sizeof(struct CtdlMessage));
636 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
637 StrBufAppendBuf(BounceMB, boundary, 0);
638 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
639 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
640 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
641 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
642 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
643 StrBufAppendBuf(BounceMB, boundary, 0);
644 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
645 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
648 StrBufAppendBufPlain(
651 "A message you sent could not be delivered "
652 "to some or all of its recipients\n"
653 "due to prolonged unavailability "
654 "of its destination(s).\n"
655 "Giving up on the following addresses:\n\n"
658 StrBufAppendBufPlain(
661 "A message you sent could not be delivered "
662 "to some or all of its recipients.\n"
663 "The following addresses "
664 "were undeliverable:\n\n"
667 StrBufAppendBuf(BounceMB, Msg, 0);
670 if (StrLength(MyQItem->SenderRoom) > 0)
672 StrBufAppendBufPlain(
674 HKEY("The message was originaly posted in: "), 0);
675 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
676 StrBufAppendBufPlain(
681 /* Attach the original message */
682 StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
683 StrBufAppendBuf(BounceMB, boundary, 0);
684 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
685 StrBufAppendBufPlain(BounceMB,
686 HKEY("Content-type: message/rfc822\r\n"), 0);
687 StrBufAppendBufPlain(BounceMB,
688 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
689 StrBufAppendBufPlain(BounceMB,
690 HKEY("Content-Disposition: inline\r\n"), 0);
691 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
692 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
694 /* Close the multipart MIME scope */
695 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
696 StrBufAppendBuf(BounceMB, boundary, 0);
697 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
699 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
700 bmsg->cm_anon_type = MES_NORMAL;
701 bmsg->cm_format_type = FMT_RFC822;
703 CM_SetField(bmsg, eOriginalRoom, HKEY(MAILROOM));
704 CM_SetField(bmsg, eAuthor, HKEY("Citadel"));
705 CM_SetField(bmsg, eNodeName, CFG_KEY(c_nodename));
706 CM_SetField(bmsg, eMsgSubject, HKEY("Delivery Status Notification (Failure)"));
707 CM_SetAsFieldSB(bmsg, eMesageText, &BounceMB);
709 /* First try the user who sent the message */
710 if (StrLength(MyQItem->BounceTo) == 0) {
711 SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
714 SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
715 ChrPtr(MyQItem->BounceTo));
718 /* Can we deliver the bounce to the original sender? */
719 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
720 if ((valid != NULL) && (valid->num_error == 0)) {
721 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
722 successful_bounce = 1;
725 /* If not, post it in the Aide> room */
726 if (successful_bounce == 0) {
727 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
730 /* Free up the memory we used */
731 free_recipients(valid);
732 FreeStrBuf(&boundary);
734 SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
737 ParsedURL *LoadRelayUrls(OneQueItem *MyQItem,
742 ParsedURL *RelayUrls = NULL;
744 ParsedURL **Url = &MyQItem->URL;
746 nRelays = get_hosts(mxbuf, "fallbackhost");
750 const char *Pos = NULL;
751 All = NewStrBufPlain(mxbuf, -1);
752 One = NewStrBufPlain(NULL, StrLength(All) + 1);
754 while ((Pos != StrBufNOTNULL) &&
758 StrBufExtract_NextToken(One, All, &Pos, '|');
759 if (!ParseURL(Url, One, DefaultMXPort)) {
760 SMTPC_syslog(LOG_DEBUG,
761 "Failed to parse: %s\n",
766 MyQItem->HaveRelay = 1;
772 nRelays = get_hosts(mxbuf, "smarthost");
777 const char *Pos = NULL;
778 All = NewStrBufPlain(mxbuf, -1);
779 One = NewStrBufPlain(NULL, StrLength(All) + 1);
781 while ((Pos != StrBufNOTNULL) &&
785 StrBufExtract_NextToken(One, All, &Pos, '|');
786 User = strchr(ChrPtr(One), ' ');
788 if (!strcmp(User + 1, Author) ||
789 !strcmp(User + 1, Address))
790 StrBufCutAt(One, 0, User);
792 MyQItem->HaveRelay = 1;
796 if (!ParseURL(Url, One, DefaultMXPort)) {
797 SMTPC_syslog(LOG_DEBUG,
798 "Failed to parse: %s\n",
802 ///if (!Url->IsIP)) // todo dupe me fork ipv6
804 MyQItem->HaveRelay = 1;
815 * Called by smtp_do_queue() to handle an individual message.
817 void smtp_do_procmsg(long msgnum, void *userdata) {
819 int mynumsessions = num_sessions;
820 struct CtdlMessage *msg = NULL;
822 char *Address = NULL;
834 if (mynumsessions > max_sessions_for_outbound_smtp) {
835 SMTPC_syslog(LOG_INFO,
836 "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
838 max_sessions_for_outbound_smtp);
841 SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
842 ///strcpy(envelope_from, "");
844 msg = CtdlFetchMessage(msgnum, 1);
846 SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
851 pch = instr = msg->cm_fields[eMesageText];
853 /* Strip out the headers (no not amd any other non-instruction) line */
854 while (pch != NULL) {
855 pch = strchr(pch, '\n');
857 ((*(pch + 1) == '\n') ||
858 (*(pch + 1) == '\r')))
864 PlainQItem = NewStrBufPlain(instr, -1);
866 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
867 FreeStrBuf(&PlainQItem);
869 if (MyQItem == NULL) {
870 SMTPC_syslog(LOG_ERR,
871 "Msg No %ld: already in progress!\n",
873 return; /* s.b. else is already processing... */
877 * Postpone delivery if we've already tried recently.
880 if ((MyQItem->ReattemptWhen != 0) &&
881 (now < MyQItem->ReattemptWhen) &&
882 (run_queue_now == 0))
884 SMTPC_syslog(LOG_DEBUG,
885 "Retry time not yet reached. %ld seconds left.",
886 MyQItem->ReattemptWhen - now);
888 It = GetNewHashPos(MyQItem->MailQEntries, 0);
889 pthread_mutex_lock(&ActiveQItemsLock);
891 if (GetHashPosFromKey(ActiveQItems,
892 LKEY(MyQItem->MessageID),
895 DeleteEntryFromHash(ActiveQItems, It);
898 pthread_mutex_unlock(&ActiveQItemsLock);
899 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
905 * Bail out if there's no actual message associated with this
907 if (MyQItem->MessageID < 0L) {
908 SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
909 It = GetNewHashPos(MyQItem->MailQEntries, 0);
910 pthread_mutex_lock(&ActiveQItemsLock);
912 if (GetHashPosFromKey(ActiveQItems,
913 LKEY(MyQItem->MessageID),
916 DeleteEntryFromHash(ActiveQItems, It);
919 pthread_mutex_unlock(&ActiveQItemsLock);
921 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
926 It = GetNewHashPos(MyQItem->MailQEntries, 0);
927 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
929 MailQEntry *ThisItem = vQE;
930 SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
931 ChrPtr(ThisItem->Recipient),
936 MyQItem->NotYetShutdownDeliveries =
937 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem, 1);
939 /* failsafe against overload:
940 * will we exceed the limit set?
942 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
943 /* if yes, did we reach more than half of the quota? */
944 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
945 /* if... would we ever fit into half of the quota?? */
946 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
948 /* abort delivery for another time. */
949 SMTPC_syslog(LOG_INFO,
950 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
952 MyQItem->ActiveDeliveries,
953 max_sessions_for_outbound_smtp);
955 It = GetNewHashPos(MyQItem->MailQEntries, 0);
956 pthread_mutex_lock(&ActiveQItemsLock);
958 if (GetHashPosFromKey(ActiveQItems,
959 LKEY(MyQItem->MessageID),
962 DeleteEntryFromHash(ActiveQItems, It);
965 pthread_mutex_unlock(&ActiveQItemsLock);
971 if (MyQItem->ActiveDeliveries > 0)
973 ParsedURL *RelayUrls = NULL;
976 int m = MyQItem->ActiveDeliveries;
979 It = GetNewHashPos(MyQItem->MailQEntries, 0);
981 Msg = smtp_load_msg(MyQItem, n, &Author, &Address);
982 RelayUrls = LoadRelayUrls(MyQItem, Author, Address);
983 if ((RelayUrls == NULL) && MyQItem->HaveRelay) {
986 (GetNextHashPos(MyQItem->MailQEntries,
987 It, &len, &Key, &vQE)))
989 int KeepBuffers = (i == m);
990 MailQEntry *ThisItem = vQE;
991 StrBufPrintf(ThisItem->StatusMessage,
992 "No relay configured matching %s / %s",
993 (Author != NULL)? Author : "",
994 (Address != NULL)? Address : "");
995 ThisItem->Status = 5;
999 if (i > 1) n = MsgCount++;
1001 "SMTPC: giving up on <%ld> <%s> %d / %d \n",
1003 ChrPtr(ThisItem->Recipient),
1006 (*((int*) userdata)) ++;
1007 smtp_try_one_queue_entry(MyQItem,
1014 if (KeepBuffers) HaveBuffers++;
1018 if (Author != NULL) free (Author);
1019 if (Address != NULL) free (Address);
1024 if (Author != NULL) free (Author);
1025 if (Address != NULL) free (Address);
1028 (GetNextHashPos(MyQItem->MailQEntries,
1029 It, &len, &Key, &vQE)))
1031 MailQEntry *ThisItem = vQE;
1033 if (ThisItem->Active == 1)
1035 int KeepBuffers = (i == m);
1038 if (nActivated % ndelay_count == 0)
1041 if (i > 1) n = MsgCount++;
1043 "SMTPC: Trying <%ld> <%s> %d / %d \n",
1045 ChrPtr(ThisItem->Recipient),
1048 (*((int*) userdata)) ++;
1049 smtp_try_one_queue_entry(MyQItem,
1056 if (KeepBuffers) HaveBuffers++;
1065 It = GetNewHashPos(MyQItem->MailQEntries, 0);
1066 pthread_mutex_lock(&ActiveQItemsLock);
1068 if (GetHashPosFromKey(ActiveQItems,
1069 LKEY(MyQItem->MessageID),
1072 DeleteEntryFromHash(ActiveQItems, It);
1080 SMTPC_syslog(LOG_WARNING,
1081 "unable to find QItem with ID[%ld]",
1082 MyQItem->MessageID);
1083 while (GetNextHashPos(ActiveQItems,
1089 SMTPC_syslog(LOG_WARNING,
1091 ((OneQueItem *)VData)->MessageID);
1096 pthread_mutex_unlock(&ActiveQItemsLock);
1098 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
1100 // TODO: bounce & delete?
1105 // TODO : free RelayUrls
1112 * smtp_queue_thread()
1114 * Run through the queue sending out messages.
1116 void smtp_do_queue(void) {
1117 int num_processed = 0;
1118 int num_activated = 0;
1120 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
1121 SMTPCM_syslog(LOG_INFO, "processing outbound queue");
1123 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
1124 SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
1127 num_processed = CtdlForEachMessage(MSGS_ALL,
1135 SMTPC_syslog(LOG_INFO,
1136 "queue run completed; %d messages processed %d activated",
1137 num_processed, num_activated);
1144 * Initialize the SMTP outbound queue
1146 void smtp_init_spoolout(void) {
1147 struct ctdlroom qrbuf;
1150 * Create the room. This will silently fail if the room already
1151 * exists, and that's perfectly ok, because we want it to exist.
1153 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1156 * Make sure it's set to be a "system room" so it doesn't show up
1157 * in the <K>nown rooms list for Aides.
1159 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1160 qrbuf.QRflags2 |= QR2_SYSTEM;
1161 CtdlPutRoomLock(&qrbuf);
1168 /*****************************************************************************/
1169 /* SMTP UTILITY COMMANDS */
1170 /*****************************************************************************/
1172 void cmd_smtp(char *argbuf) {
1179 if (CtdlAccessCheck(ac_aide)) return;
1181 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1183 if (!strcasecmp(cmd, "mx")) {
1184 extract_token(node, argbuf, 1, '|', sizeof node);
1185 num_mxhosts = getmx(buf, node);
1186 cprintf("%d %d MX hosts listed for %s\n",
1187 LISTING_FOLLOWS, num_mxhosts, node);
1188 for (i=0; i<num_mxhosts; ++i) {
1189 extract_token(node, buf, i, '|', sizeof node);
1190 cprintf("%s\n", node);
1196 else if (!strcasecmp(cmd, "runqueue")) {
1198 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1203 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1208 int smtp_aftersave(struct CtdlMessage *msg,
1211 /* For internet mail, generate delivery instructions.
1212 * Yes, this is recursive. Deal with it. Infinite recursion does
1213 * not happen because the delivery instructions message does not
1214 * contain a recipient.
1216 if ((recps != NULL) && (recps->num_internet > 0)) {
1217 struct CtdlMessage *imsg = NULL;
1218 char recipient[SIZ];
1219 CitContext *CCC = MyContext();
1220 StrBuf *SpoolMsg = NewStrBuf();
1224 MSGM_syslog(LOG_DEBUG, "Generating delivery instructions\n");
1226 StrBufPrintf(SpoolMsg,
1227 "Content-type: "SPOOLMIME"\n"
1232 msg->cm_fields[eVltMsgNum],
1236 if (recps->envelope_from != NULL) {
1237 StrBufAppendBufPlain(SpoolMsg, HKEY("envelope_from|"), 0);
1238 StrBufAppendBufPlain(SpoolMsg, recps->envelope_from, -1, 0);
1239 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
1241 if (recps->sending_room != NULL) {
1242 StrBufAppendBufPlain(SpoolMsg, HKEY("source_room|"), 0);
1243 StrBufAppendBufPlain(SpoolMsg, recps->sending_room, -1, 0);
1244 StrBufAppendBufPlain(SpoolMsg, HKEY("\n"), 0);
1247 nTokens = num_tokens(recps->recp_internet, '|');
1248 for (i = 0; i < nTokens; i++) {
1250 len = extract_token(recipient, recps->recp_internet, i, '|', sizeof recipient);
1252 StrBufAppendBufPlain(SpoolMsg, HKEY("remote|"), 0);
1253 StrBufAppendBufPlain(SpoolMsg, recipient, len, 0);
1254 StrBufAppendBufPlain(SpoolMsg, HKEY("|0||\n"), 0);
1258 imsg = malloc(sizeof(struct CtdlMessage));
1259 memset(imsg, 0, sizeof(struct CtdlMessage));
1260 imsg->cm_magic = CTDLMESSAGE_MAGIC;
1261 imsg->cm_anon_type = MES_NORMAL;
1262 imsg->cm_format_type = FMT_RFC822;
1263 CM_SetField(imsg, eMsgSubject, HKEY("QMSG"));
1264 CM_SetField(imsg, eAuthor, HKEY("Citadel"));
1265 CM_SetField(imsg, eJournal, HKEY("do not journal"));
1266 CM_SetAsFieldSB(imsg, eMesageText, &SpoolMsg);
1267 CtdlSubmitMsg(imsg, NULL, SMTP_SPOOLOUT_ROOM, QP_EADDR);
1273 CTDL_MODULE_INIT(smtp_queu)
1279 pstr = getenv("CITSERVER_n_session_max");
1280 if ((pstr != NULL) && (*pstr != '\0'))
1281 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1283 pstr = getenv("CITSERVER_smtp_n_delay_count");
1284 if ((pstr != NULL) && (*pstr != '\0'))
1285 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1287 pstr = getenv("CITSERVER_smtp_delay");
1288 if ((pstr != NULL) && (*pstr != '\0'))
1289 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1291 CtdlRegisterMessageHook(smtp_aftersave, EVT_AFTERSAVE);
1293 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1294 ActiveQItems = NewHash(1, lFlathash);
1295 pthread_mutex_init(&ActiveQItemsLock, NULL);
1297 QItemHandlers = NewHash(0, NULL);
1299 RegisterQItemHandler(HKEY("msgid"), QItem_Handle_MsgID);
1300 RegisterQItemHandler(HKEY("envelope_from"), QItem_Handle_EnvelopeFrom);
1301 RegisterQItemHandler(HKEY("retry"), QItem_Handle_retry);
1302 RegisterQItemHandler(HKEY("attempted"), QItem_Handle_Attempted);
1303 RegisterQItemHandler(HKEY("remote"), QItem_Handle_Recipient);
1304 RegisterQItemHandler(HKEY("bounceto"), QItem_Handle_BounceTo);
1305 RegisterQItemHandler(HKEY("source_room"), QItem_Handle_SenderRoom);
1306 RegisterQItemHandler(HKEY("submitted"), QItem_Handle_Submitted);
1308 smtp_init_spoolout();
1310 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1312 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1313 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER, PRIO_SEND + 10);
1316 /* return our Subversion id for the Log */
1317 return "smtpeventclient";