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 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
98 int ndelay_count = 50; /* every n queued messages we will sleep... */
99 int delay_msec = 5000; /* this many seconds. */
101 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
103 int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
105 void RegisterQItemHandler(const char *Key, long Len, QItemHandler H)
107 QItemHandlerStruct *HS = (QItemHandlerStruct*)malloc(sizeof(QItemHandlerStruct));
109 Put(QItemHandlers, Key, Len, HS, NULL);
114 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
115 MailQEntry *MyQEntry,
117 /* KeepMsgText allows us to use MsgText as ours. */
120 ParsedURL *RelayUrls);
123 void smtp_evq_cleanup(void)
126 pthread_mutex_lock(&ActiveQItemsLock);
127 DeleteHash(&QItemHandlers);
128 DeleteHash(&ActiveQItems);
129 pthread_mutex_unlock(&ActiveQItemsLock);
130 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
131 /* citthread_mutex_destroy(&ActiveQItemsLock); TODO */
134 int DecreaseQReference(OneQueItem *MyQItem)
136 int IDestructQueItem;
138 pthread_mutex_lock(&ActiveQItemsLock);
139 MyQItem->ActiveDeliveries--;
140 IDestructQueItem = MyQItem->ActiveDeliveries == 0;
141 pthread_mutex_unlock(&ActiveQItemsLock);
142 return IDestructQueItem;
145 void DecreaseShutdownDeliveries(OneQueItem *MyQItem)
147 pthread_mutex_lock(&ActiveQItemsLock);
148 MyQItem->NotYetShutdownDeliveries--;
149 pthread_mutex_unlock(&ActiveQItemsLock);
152 int GetShutdownDeliveries(OneQueItem *MyQItem)
156 pthread_mutex_lock(&ActiveQItemsLock);
157 DestructNow = MyQItem->ActiveDeliveries == 0;
158 pthread_mutex_unlock(&ActiveQItemsLock);
161 void RemoveQItem(OneQueItem *MyQItem)
168 pthread_mutex_lock(&ActiveQItemsLock);
169 It = GetNewHashPos(ActiveQItems, 0);
170 if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
171 DeleteEntryFromHash(ActiveQItems, It);
174 SMTPC_syslog(LOG_WARNING,
175 "unable to find QItem with ID[%ld]",
177 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
178 SMTPC_syslog(LOG_WARNING,
180 ((OneQueItem *)VData)->MessageID);
182 pthread_mutex_unlock(&ActiveQItemsLock);
187 void FreeMailQEntry(void *qv)
191 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
194 FreeStrBuf(&Q->Recipient);
195 FreeStrBuf(&Q->StatusMessage);
197 memset(Q, 0, sizeof(MailQEntry));
200 void FreeQueItem(OneQueItem **Item)
203 SMTPC_syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
206 DeleteHash(&(*Item)->MailQEntries);
207 FreeStrBuf(&(*Item)->EnvelopeFrom);
208 FreeStrBuf(&(*Item)->BounceTo);
209 FreeStrBuf(&(*Item)->SenderRoom);
210 FreeURL(&(*Item)->URL);
211 memset(*Item, 0, sizeof(OneQueItem));
215 void HFreeQueItem(void *Item)
217 FreeQueItem((OneQueItem**)&Item);
220 /* inspect recipients with a status of:
221 * - 0 (no delivery yet attempted)
222 * - 3/4 (transient errors
223 * were experienced and it's time to try again)
225 int CheckQEntryActive(MailQEntry *ThisItem)
227 if ((ThisItem->Status == 0) ||
228 (ThisItem->Status == 3) ||
229 (ThisItem->Status == 4))
236 int CheckQEntryIsBounce(MailQEntry *ThisItem)
238 if ((ThisItem->Status == 3) ||
239 (ThisItem->Status == 4) ||
240 (ThisItem->Status == 5))
248 int CountActiveQueueEntries(OneQueItem *MyQItem)
252 long ActiveDeliveries;
256 ActiveDeliveries = 0;
257 It = GetNewHashPos(MyQItem->MailQEntries, 0);
258 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
260 MailQEntry *ThisItem = vQE;
262 if (CheckQEntryActive(ThisItem))
265 ThisItem->Active = 1;
268 ThisItem->Active = 0;
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 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
385 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
393 void NewMailQEntry(OneQueItem *Item)
395 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
396 memset(Item->Current, 0, sizeof(MailQEntry));
398 if (Item->MailQEntries == NULL)
399 Item->MailQEntries = NewHash(1, Flathash);
400 Item->Current->StatusMessage = NewStrBuf();
401 Item->Current->n = GetCount(Item->MailQEntries);
402 Put(Item->MailQEntries,
403 IKEY(Item->Current->n),
408 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
410 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
413 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
415 if (Item->EnvelopeFrom == NULL)
416 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
417 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
420 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
422 if (Item->BounceTo == NULL)
423 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
424 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
427 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
429 if (Item->SenderRoom == NULL)
430 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
431 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
434 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
436 if (Item->Current == NULL)
438 if (Item->Current->Recipient == NULL)
439 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
440 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
441 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
442 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
443 Item->Current = NULL; // TODO: is this always right?
447 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
450 StrBufExtractNext_int(Line, Pos, '|');
451 if (Item->Retry == 0)
452 Item->Retry = SMTP_RETRY_INTERVAL;
458 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
460 Item->Submitted = atol(*Pos);
464 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
466 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
472 * this one has to have the context for loading the message via the redirect buffer...
474 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
479 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
480 CtdlOutputMsg(MyQItem->MessageID,
481 MT_RFC822, HEADERS_ALL,
483 (ESC_DOT|SUPPRESS_ENV_TO) );
485 SendMsg = CCC->redirect_buffer;
486 CCC->redirect_buffer = NULL;
487 if ((StrLength(SendMsg) > 0) &&
488 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
489 SMTPC_syslog(LOG_WARNING,
490 "[%d] Possible problem: message did not "
491 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
492 MsgCount, //yes uncool, but best choice here...
493 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
494 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
502 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
503 * instructions for "5" codes (permanent fatal errors) and produce/deliver
504 * a "bounce" message (delivery status notification).
506 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
510 struct CtdlMessage *bmsg = NULL;
514 struct recptypes *valid;
522 int first_attempt = 0;
523 int successful_bounce = 0;
527 SMTPCM_syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
529 if (MyQItem->SendBounceMail == 0)
532 now = time (NULL); //ev_time();
534 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
538 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
543 * Now go through the instructions checking for stuff.
545 Msg = NewStrBufPlain(NULL, 1024);
546 It = GetNewHashPos(MyQItem->MailQEntries, 0);
547 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
549 MailQEntry *ThisItem = vQE;
550 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
551 ((give_up == 1) && (ThisItem->Status != 2)) ||
552 ((first_attempt == 1) && (ThisItem->Status != 2)))
553 /* giving up after failed attempts... */
557 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
558 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
559 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
560 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
565 /* Deliver the bounce if there's anything worth mentioning */
566 SMTPC_syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
568 if (num_bounces == 0) {
573 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
574 StrBufAppendPrintf(boundary,
580 /* Start building our bounce message; go shopping for memory first. */
581 BounceMB = NewStrBufPlain(
583 1024 + /* mime stuff.... */
584 StrLength(Msg) + /* the bounce information... */
585 StrLength(OMsgTxt)); /* the original message */
586 if (BounceMB == NULL) {
587 FreeStrBuf(&boundary);
588 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
593 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
595 FreeStrBuf(&boundary);
596 FreeStrBuf(&BounceMB);
597 SMTPCM_syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
601 memset(bmsg, 0, sizeof(struct CtdlMessage));
604 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
605 StrBufAppendBuf(BounceMB, boundary, 0);
606 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
607 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
608 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
609 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
610 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
611 StrBufAppendBuf(BounceMB, boundary, 0);
612 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
613 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
616 StrBufAppendBufPlain(
619 "A message you sent could not be delivered "
620 "to some or all of its recipients\n"
621 "due to prolonged unavailability "
622 "of its destination(s).\n"
623 "Giving up on the following addresses:\n\n"
626 StrBufAppendBufPlain(
629 "A message you sent could not be delivered "
630 "to some or all of its recipients.\n"
631 "The following addresses "
632 "were undeliverable:\n\n"
635 StrBufAppendBuf(BounceMB, Msg, 0);
638 if (StrLength(MyQItem->SenderRoom) > 0)
640 StrBufAppendBufPlain(
642 HKEY("The message was originaly posted in: "), 0);
643 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
644 StrBufAppendBufPlain(
649 /* Attach the original message */
650 StrBufAppendBufPlain(BounceMB, HKEY("\r\n--"), 0);
651 StrBufAppendBuf(BounceMB, boundary, 0);
652 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
653 StrBufAppendBufPlain(BounceMB,
654 HKEY("Content-type: message/rfc822\r\n"), 0);
655 StrBufAppendBufPlain(BounceMB,
656 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
657 StrBufAppendBufPlain(BounceMB,
658 HKEY("Content-Disposition: inline\r\n"), 0);
659 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
660 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
662 /* Close the multipart MIME scope */
663 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
664 StrBufAppendBuf(BounceMB, boundary, 0);
665 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
667 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
668 bmsg->cm_anon_type = MES_NORMAL;
669 bmsg->cm_format_type = FMT_RFC822;
671 bmsg->cm_fields['O'] = strdup(MAILROOM);
672 bmsg->cm_fields['A'] = strdup("Citadel");
673 bmsg->cm_fields['N'] = strdup(config.c_nodename);
674 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
675 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
677 /* First try the user who sent the message */
678 if (StrLength(MyQItem->BounceTo) == 0) {
679 SMTPCM_syslog(LOG_ERR, "No bounce address specified\n");
682 SMTPC_syslog(LOG_DEBUG, "bounce to user? <%s>\n",
683 ChrPtr(MyQItem->BounceTo));
686 /* Can we deliver the bounce to the original sender? */
687 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
688 if ((valid != NULL) && (valid->num_error == 0)) {
689 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
690 successful_bounce = 1;
693 /* If not, post it in the Aide> room */
694 if (successful_bounce == 0) {
695 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
698 /* Free up the memory we used */
699 free_recipients(valid);
700 FreeStrBuf(&boundary);
701 CtdlFreeMessage(bmsg);
702 SMTPCM_syslog(LOG_DEBUG, "Done processing bounces\n");
708 * Called by smtp_do_queue() to handle an individual message.
710 void smtp_do_procmsg(long msgnum, void *userdata) {
712 int mynumsessions = num_sessions;
713 struct CtdlMessage *msg = NULL;
723 ParsedURL *RelayUrls = NULL;
727 if (mynumsessions > max_sessions_for_outbound_smtp) {
728 SMTPC_syslog(LOG_DEBUG,
729 "skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
731 max_sessions_for_outbound_smtp);
734 SMTPC_syslog(LOG_DEBUG, "smtp_do_procmsg(%ld)\n", msgnum);
735 ///strcpy(envelope_from, "");
737 msg = CtdlFetchMessage(msgnum, 1);
739 SMTPC_syslog(LOG_ERR, "tried %ld but no such message!\n",
744 pch = instr = msg->cm_fields['M'];
746 /* Strip out the headers (no not amd any other non-instruction) line */
747 while (pch != NULL) {
748 pch = strchr(pch, '\n');
749 if ((pch != NULL) && (*(pch + 1) == '\n')) {
754 PlainQItem = NewStrBufPlain(instr, -1);
755 CtdlFreeMessage(msg);
756 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
757 FreeStrBuf(&PlainQItem);
759 if (MyQItem == NULL) {
760 SMTPC_syslog(LOG_ERR,
761 "Msg No %ld: already in progress!\n",
763 return; /* s.b. else is already processing... */
767 * Postpone delivery if we've already tried recently.
770 if ((MyQItem->ReattemptWhen != 0) &&
771 (now < MyQItem->ReattemptWhen) &&
772 (run_queue_now == 0))
774 SMTPC_syslog(LOG_DEBUG,
775 "Retry time not yet reached. %ld seconds left.",
776 MyQItem->ReattemptWhen - now);
778 It = GetNewHashPos(MyQItem->MailQEntries, 0);
779 pthread_mutex_lock(&ActiveQItemsLock);
781 if (GetHashPosFromKey(ActiveQItems,
782 LKEY(MyQItem->MessageID),
785 DeleteEntryFromHash(ActiveQItems, It);
788 pthread_mutex_unlock(&ActiveQItemsLock);
789 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
795 * Bail out if there's no actual message associated with this
797 if (MyQItem->MessageID < 0L) {
798 SMTPCM_syslog(LOG_ERR, "no 'msgid' directive found!\n");
799 It = GetNewHashPos(MyQItem->MailQEntries, 0);
800 pthread_mutex_lock(&ActiveQItemsLock);
802 if (GetHashPosFromKey(ActiveQItems,
803 LKEY(MyQItem->MessageID),
806 DeleteEntryFromHash(ActiveQItems, It);
809 pthread_mutex_unlock(&ActiveQItemsLock);
811 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
817 ParsedURL **Url = &MyQItem->URL;
818 nRelays = get_hosts(mxbuf, "smarthost");
822 const char *Pos = NULL;
823 All = NewStrBufPlain(mxbuf, -1);
824 One = NewStrBufPlain(NULL, StrLength(All) + 1);
826 while ((Pos != StrBufNOTNULL) &&
830 StrBufExtract_NextToken(One, All, &Pos, '|');
831 if (!ParseURL(Url, One, 25)) {
832 SMTPC_syslog(LOG_DEBUG,
833 "Failed to parse: %s\n",
837 ///if (!Url->IsIP)) // todo dupe me fork ipv6
845 Url = &MyQItem->FallBackHost;
846 nRelays = get_hosts(mxbuf, "fallbackhost");
850 const char *Pos = NULL;
851 All = NewStrBufPlain(mxbuf, -1);
852 One = NewStrBufPlain(NULL, StrLength(All) + 1);
854 while ((Pos != StrBufNOTNULL) &&
858 StrBufExtract_NextToken(One, All, &Pos, '|');
859 if (!ParseURL(Url, One, 25)) {
860 SMTPC_syslog(LOG_DEBUG,
861 "Failed to parse: %s\n",
872 It = GetNewHashPos(MyQItem->MailQEntries, 0);
873 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
875 MailQEntry *ThisItem = vQE;
876 SMTPC_syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
877 ChrPtr(ThisItem->Recipient),
882 MyQItem->NotYetShutdownDeliveries =
883 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
885 /* failsafe against overload:
886 * will we exceed the limit set?
888 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
889 /* if yes, did we reach more than half of the quota? */
890 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
891 /* if... would we ever fit into half of the quota?? */
892 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
894 /* abort delivery for another time. */
895 SMTPC_syslog(LOG_DEBUG,
896 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
898 MyQItem->ActiveDeliveries,
899 max_sessions_for_outbound_smtp);
901 FreeQueItem(&MyQItem);
907 if (MyQItem->ActiveDeliveries > 0)
911 int m = MyQItem->ActiveDeliveries;
913 Msg = smtp_load_msg(MyQItem, n);
914 It = GetNewHashPos(MyQItem->MailQEntries, 0);
916 (GetNextHashPos(MyQItem->MailQEntries,
917 It, &len, &Key, &vQE)))
919 MailQEntry *ThisItem = vQE;
921 if (ThisItem->Active == 1)
923 int KeepBuffers = (i == m);
926 if (nActivated % ndelay_count == 0)
929 if (i > 1) n = MsgCount++;
931 "SMTPC: Trying <%ld> <%s> %d / %d \n",
933 ChrPtr(ThisItem->Recipient),
936 (*((int*) userdata)) ++;
937 smtp_try_one_queue_entry(MyQItem,
944 if (KeepBuffers) HaveBuffers = 1;
953 It = GetNewHashPos(MyQItem->MailQEntries, 0);
954 pthread_mutex_lock(&ActiveQItemsLock);
956 if (GetHashPosFromKey(ActiveQItems,
957 LKEY(MyQItem->MessageID),
960 DeleteEntryFromHash(ActiveQItems, It);
968 SMTPC_syslog(LOG_WARNING,
969 "unable to find QItem with ID[%ld]",
971 while (GetNextHashPos(ActiveQItems,
977 SMTPC_syslog(LOG_WARNING,
979 ((OneQueItem *)VData)->MessageID);
984 pthread_mutex_unlock(&ActiveQItemsLock);
986 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
988 // TODO: bounce & delete?
993 // TODO : free RelayUrls
1000 * smtp_queue_thread()
1002 * Run through the queue sending out messages.
1004 void smtp_do_queue(void) {
1005 static int is_running = 0;
1006 int num_processed = 0;
1007 int num_activated = 0;
1010 return; /* Concurrency check - only one can run */
1013 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
1014 SMTPCM_syslog(LOG_INFO, "processing outbound queue");
1016 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
1017 SMTPC_syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
1020 num_processed = CtdlForEachMessage(MSGS_ALL,
1028 SMTPC_syslog(LOG_INFO,
1029 "queue run completed; %d messages processed %d activated",
1030 num_processed, num_activated);
1039 * Initialize the SMTP outbound queue
1041 void smtp_init_spoolout(void) {
1042 struct ctdlroom qrbuf;
1045 * Create the room. This will silently fail if the room already
1046 * exists, and that's perfectly ok, because we want it to exist.
1048 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1051 * Make sure it's set to be a "system room" so it doesn't show up
1052 * in the <K>nown rooms list for Aides.
1054 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1055 qrbuf.QRflags2 |= QR2_SYSTEM;
1056 CtdlPutRoomLock(&qrbuf);
1063 /*****************************************************************************/
1064 /* SMTP UTILITY COMMANDS */
1065 /*****************************************************************************/
1067 void cmd_smtp(char *argbuf) {
1074 if (CtdlAccessCheck(ac_aide)) return;
1076 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1078 if (!strcasecmp(cmd, "mx")) {
1079 extract_token(node, argbuf, 1, '|', sizeof node);
1080 num_mxhosts = getmx(buf, node);
1081 cprintf("%d %d MX hosts listed for %s\n",
1082 LISTING_FOLLOWS, num_mxhosts, node);
1083 for (i=0; i<num_mxhosts; ++i) {
1084 extract_token(node, buf, i, '|', sizeof node);
1085 cprintf("%s\n", node);
1091 else if (!strcasecmp(cmd, "runqueue")) {
1093 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1098 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1104 CTDL_MODULE_INIT(smtp_queu)
1110 pstr = getenv("CITSERVER_n_session_max");
1111 if ((pstr != NULL) && (*pstr != '\0'))
1112 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1114 pstr = getenv("CITSERVER_smtp_n_delay_count");
1115 if ((pstr != NULL) && (*pstr != '\0'))
1116 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1118 pstr = getenv("CITSERVER_smtp_delay");
1119 if ((pstr != NULL) && (*pstr != '\0'))
1120 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1125 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1126 ActiveQItems = NewHash(1, lFlathash);
1127 pthread_mutex_init(&ActiveQItemsLock, NULL);
1129 QItemHandlers = NewHash(0, NULL);
1131 RegisterQItemHandler(HKEY("msgid"), QItem_Handle_MsgID);
1132 RegisterQItemHandler(HKEY("envelope_from"), QItem_Handle_EnvelopeFrom);
1133 RegisterQItemHandler(HKEY("retry"), QItem_Handle_retry);
1134 RegisterQItemHandler(HKEY("attempted"), QItem_Handle_Attempted);
1135 RegisterQItemHandler(HKEY("remote"), QItem_Handle_Recipient);
1136 RegisterQItemHandler(HKEY("bounceto"), QItem_Handle_BounceTo);
1137 RegisterQItemHandler(HKEY("source_room"), QItem_Handle_SenderRoom);
1138 RegisterQItemHandler(HKEY("submitted"), QItem_Handle_Submitted);
1140 smtp_init_spoolout();
1142 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1144 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1145 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
1148 /* return our Subversion id for the Log */
1149 return "smtpeventclient";