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 "event_client.h"
92 struct CitContext smtp_queue_CC;
93 pthread_mutex_t ActiveQItemsLock;
94 HashList *ActiveQItems = NULL;
95 HashList *QItemHandlers = NULL;
96 int max_sessions_for_outbound_smtp = 500; /* how many sessions might be active till we stop adding more smtp jobs */
97 int ndelay_count = 50; /* every n queued messages we will sleep... */
98 int delay_msec = 5000; /* this many seconds. */
100 static const long MaxRetry = SMTP_RETRY_INTERVAL * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2;
102 int run_queue_now = 0; /* Set to 1 to ignore SMTP send retry times */
104 void smtp_try_one_queue_entry(OneQueItem *MyQItem,
105 MailQEntry *MyQEntry,
107 /* KeepMsgText allows us to use MsgText as ours. */
110 ParsedURL *RelayUrls);
113 void smtp_evq_cleanup(void)
116 pthread_mutex_lock(&ActiveQItemsLock);
117 DeleteHash(&QItemHandlers);
118 DeleteHash(&ActiveQItems);
119 pthread_mutex_unlock(&ActiveQItemsLock);
120 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
121 /* citthread_mutex_destroy(&ActiveQItemsLock); TODO */
124 int DecreaseQReference(OneQueItem *MyQItem)
126 int IDestructQueItem;
128 pthread_mutex_lock(&ActiveQItemsLock);
129 MyQItem->ActiveDeliveries--;
130 IDestructQueItem = MyQItem->ActiveDeliveries == 0;
131 pthread_mutex_unlock(&ActiveQItemsLock);
132 return IDestructQueItem;
135 void RemoveQItem(OneQueItem *MyQItem)
142 pthread_mutex_lock(&ActiveQItemsLock);
143 It = GetNewHashPos(ActiveQItems, 0);
144 if (GetHashPosFromKey(ActiveQItems, LKEY(MyQItem->MessageID), It))
145 DeleteEntryFromHash(ActiveQItems, It);
149 "SMTP cleanup: unable to find QItem with ID[%ld]",
151 while (GetNextHashPos(ActiveQItems, It, &len, &Key, &VData))
153 "SMTP cleanup: have_: ID[%ld]",
154 ((OneQueItem *)VData)->MessageID);
156 pthread_mutex_unlock(&ActiveQItemsLock);
161 void FreeMailQEntry(void *qv)
165 syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
168 FreeStrBuf(&Q->Recipient);
169 FreeStrBuf(&Q->StatusMessage);
171 memset(Q, 0, sizeof(MailQEntry));
174 void FreeQueItem(OneQueItem **Item)
177 syslog(LOG_DEBUG, "---------------%s--------------", __FUNCTION__);
180 DeleteHash(&(*Item)->MailQEntries);
181 FreeStrBuf(&(*Item)->EnvelopeFrom);
182 FreeStrBuf(&(*Item)->BounceTo);
183 FreeStrBuf(&(*Item)->SenderRoom);
184 FreeURL(&(*Item)->URL);
185 memset(*Item, 0, sizeof(OneQueItem));
189 void HFreeQueItem(void *Item)
191 FreeQueItem((OneQueItem**)&Item);
194 /* inspect recipients with a status of:
195 * - 0 (no delivery yet attempted)
196 * - 3/4 (transient errors
197 * were experienced and it's time to try again)
199 int CheckQEntryActive(MailQEntry *ThisItem)
201 if ((ThisItem->Status == 0) ||
202 (ThisItem->Status == 3) ||
203 (ThisItem->Status == 4))
210 int CheckQEntryIsBounce(MailQEntry *ThisItem)
212 if ((ThisItem->Status == 3) ||
213 (ThisItem->Status == 4) ||
214 (ThisItem->Status == 5))
222 int CountActiveQueueEntries(OneQueItem *MyQItem)
226 long ActiveDeliveries;
230 ActiveDeliveries = 0;
231 It = GetNewHashPos(MyQItem->MailQEntries, 0);
232 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
234 MailQEntry *ThisItem = vQE;
236 if (CheckQEntryActive(ThisItem))
239 ThisItem->Active = 1;
242 ThisItem->Active = 0;
245 return ActiveDeliveries;
248 OneQueItem *DeserializeQueueItem(StrBuf *RawQItem, long QueMsgID)
251 const char *pLine = NULL;
256 Item = (OneQueItem*)malloc(sizeof(OneQueItem));
257 memset(Item, 0, sizeof(OneQueItem));
258 Item->Retry = SMTP_RETRY_INTERVAL;
259 Item->MessageID = -1;
260 Item->QueMsgID = QueMsgID;
263 Line = NewStrBufPlain(NULL, 128);
264 while (pLine != StrBufNOTNULL) {
265 const char *pItemPart = NULL;
268 StrBufExtract_NextToken(Line, RawQItem, &pLine, '\n');
269 if (StrLength(Line) == 0) continue;
270 StrBufExtract_NextToken(Token, Line, &pItemPart, '|');
271 if (GetHash(QItemHandlers, SKEY(Token), &vHandler))
274 H = (QItemHandler) vHandler;
275 H(Item, Line, &pItemPart);
281 if (Item->Retry >= MaxRetry)
284 pthread_mutex_lock(&ActiveQItemsLock);
285 if (GetHash(ActiveQItems,
286 LKEY(Item->MessageID),
289 /* WHOOPS. somebody else is already working on this. */
290 pthread_mutex_unlock(&ActiveQItemsLock);
295 /* mark our claim on this. */
297 LKEY(Item->MessageID),
300 pthread_mutex_unlock(&ActiveQItemsLock);
306 StrBuf *SerializeQueueItem(OneQueItem *MyQItem)
314 QMessage = NewStrBufPlain(NULL, SIZ);
315 StrBufPrintf(QMessage, "Content-type: %s\n", SPOOLMIME);
316 // "attempted|%ld\n" "retry|%ld\n",, (long)time(NULL), (long)retry );
317 StrBufAppendBufPlain(QMessage, HKEY("\nmsgid|"), 0);
318 StrBufAppendPrintf(QMessage, "%ld", MyQItem->MessageID);
320 StrBufAppendBufPlain(QMessage, HKEY("\nsubmitted|"), 0);
321 StrBufAppendPrintf(QMessage, "%ld", MyQItem->Submitted);
323 if (StrLength(MyQItem->BounceTo) > 0) {
324 StrBufAppendBufPlain(QMessage, HKEY("\nbounceto|"), 0);
325 StrBufAppendBuf(QMessage, MyQItem->BounceTo, 0);
328 if (StrLength(MyQItem->EnvelopeFrom) > 0) {
329 StrBufAppendBufPlain(QMessage, HKEY("\nenvelope_from|"), 0);
330 StrBufAppendBuf(QMessage, MyQItem->EnvelopeFrom, 0);
333 if (StrLength(MyQItem->SenderRoom) > 0) {
334 StrBufAppendBufPlain(QMessage, HKEY("\nsource_room|"), 0);
335 StrBufAppendBuf(QMessage, MyQItem->SenderRoom, 0);
338 StrBufAppendBufPlain(QMessage, HKEY("\nretry|"), 0);
339 StrBufAppendPrintf(QMessage, "%ld",
342 StrBufAppendBufPlain(QMessage, HKEY("\nattempted|"), 0);
343 StrBufAppendPrintf(QMessage, "%ld",
344 ctdl_ev_now() + MyQItem->Retry);
346 It = GetNewHashPos(MyQItem->MailQEntries, 0);
347 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
349 MailQEntry *ThisItem = vQE;
351 StrBufAppendBufPlain(QMessage, HKEY("\nremote|"), 0);
352 StrBufAppendBuf(QMessage, ThisItem->Recipient, 0);
353 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
354 StrBufAppendPrintf(QMessage, "%d", ThisItem->Status);
355 StrBufAppendBufPlain(QMessage, HKEY("|"), 0);
356 StrBufAppendBuf(QMessage, ThisItem->StatusMessage, 0);
359 StrBufAppendBufPlain(QMessage, HKEY("\n"), 0);
367 void NewMailQEntry(OneQueItem *Item)
369 Item->Current = (MailQEntry*) malloc(sizeof(MailQEntry));
370 memset(Item->Current, 0, sizeof(MailQEntry));
372 if (Item->MailQEntries == NULL)
373 Item->MailQEntries = NewHash(1, Flathash);
374 Item->Current->StatusMessage = NewStrBuf();
375 Item->Current->n = GetCount(Item->MailQEntries);
376 Put(Item->MailQEntries,
377 IKEY(Item->Current->n),
382 void QItem_Handle_MsgID(OneQueItem *Item, StrBuf *Line, const char **Pos)
384 Item->MessageID = StrBufExtractNext_long(Line, Pos, '|');
387 void QItem_Handle_EnvelopeFrom(OneQueItem *Item, StrBuf *Line, const char **Pos)
389 if (Item->EnvelopeFrom == NULL)
390 Item->EnvelopeFrom = NewStrBufPlain(NULL, StrLength(Line));
391 StrBufExtract_NextToken(Item->EnvelopeFrom, Line, Pos, '|');
394 void QItem_Handle_BounceTo(OneQueItem *Item, StrBuf *Line, const char **Pos)
396 if (Item->BounceTo == NULL)
397 Item->BounceTo = NewStrBufPlain(NULL, StrLength(Line));
398 StrBufExtract_NextToken(Item->BounceTo, Line, Pos, '|');
401 void QItem_Handle_SenderRoom(OneQueItem *Item, StrBuf *Line, const char **Pos)
403 if (Item->SenderRoom == NULL)
404 Item->SenderRoom = NewStrBufPlain(NULL, StrLength(Line));
405 StrBufExtract_NextToken(Item->SenderRoom, Line, Pos, '|');
408 void QItem_Handle_Recipient(OneQueItem *Item, StrBuf *Line, const char **Pos)
410 if (Item->Current == NULL)
412 if (Item->Current->Recipient == NULL)
413 Item->Current->Recipient=NewStrBufPlain(NULL, StrLength(Line));
414 StrBufExtract_NextToken(Item->Current->Recipient, Line, Pos, '|');
415 Item->Current->Status = StrBufExtractNext_int(Line, Pos, '|');
416 StrBufExtract_NextToken(Item->Current->StatusMessage, Line, Pos, '|');
417 Item->Current = NULL; // TODO: is this always right?
421 void QItem_Handle_retry(OneQueItem *Item, StrBuf *Line, const char **Pos)
424 StrBufExtractNext_int(Line, Pos, '|');
425 if (Item->Retry == 0)
426 Item->Retry = SMTP_RETRY_INTERVAL;
432 void QItem_Handle_Submitted(OneQueItem *Item, StrBuf *Line, const char **Pos)
434 Item->Submitted = atol(*Pos);
438 void QItem_Handle_Attempted(OneQueItem *Item, StrBuf *Line, const char **Pos)
440 Item->ReattemptWhen = StrBufExtractNext_int(Line, Pos, '|');
446 * this one has to have the context for loading the message via the redirect buffer...
448 StrBuf *smtp_load_msg(OneQueItem *MyQItem, int n)
453 CCC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
454 CtdlOutputMsg(MyQItem->MessageID,
455 MT_RFC822, HEADERS_ALL,
457 (ESC_DOT|SUPPRESS_ENV_TO) );
459 SendMsg = CCC->redirect_buffer;
460 CCC->redirect_buffer = NULL;
461 if ((StrLength(SendMsg) > 0) &&
462 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] != '\n') {
464 "SMTP client[%d]: Possible problem: message did not "
465 "correctly terminate. (expecting 0x10, got 0x%02x)\n",
466 MsgCount, //yes uncool, but best choice here...
467 ChrPtr(SendMsg)[StrLength(SendMsg) - 1] );
468 StrBufAppendBufPlain(SendMsg, HKEY("\r\n"), 0);
476 * smtp_do_bounce() is caled by smtp_do_procmsg() to scan a set of delivery
477 * instructions for "5" codes (permanent fatal errors) and produce/deliver
478 * a "bounce" message (delivery status notification).
480 void smtpq_do_bounce(OneQueItem *MyQItem, StrBuf *OMsgTxt)
484 struct CtdlMessage *bmsg = NULL;
488 struct recptypes *valid;
496 int first_attempt = 0;
497 int successful_bounce = 0;
501 syslog(LOG_DEBUG, "smtp_do_bounce() called\n");
503 if (MyQItem->SendBounceMail == 0)
508 if ( (now - MyQItem->Submitted) > SMTP_GIVE_UP ) {
512 if (MyQItem->Retry == SMTP_RETRY_INTERVAL) {
517 * Now go through the instructions checking for stuff.
519 Msg = NewStrBufPlain(NULL, 1024);
520 It = GetNewHashPos(MyQItem->MailQEntries, 0);
521 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
523 MailQEntry *ThisItem = vQE;
524 if ((ThisItem->Active && (ThisItem->Status == 5)) || /* failed now? */
525 ((give_up == 1) && (ThisItem->Status != 2)) ||
526 ((first_attempt == 1) && (ThisItem->Status != 2)))
527 /* giving up after failed attempts... */
531 StrBufAppendBuf(Msg, ThisItem->Recipient, 0);
532 StrBufAppendBufPlain(Msg, HKEY(": "), 0);
533 StrBufAppendBuf(Msg, ThisItem->StatusMessage, 0);
534 StrBufAppendBufPlain(Msg, HKEY("\r\n"), 0);
539 /* Deliver the bounce if there's anything worth mentioning */
540 syslog(LOG_DEBUG, "num_bounces = %d\n", num_bounces);
542 if (num_bounces == 0) {
547 boundary = NewStrBufPlain(HKEY("=_Citadel_Multipart_"));
548 StrBufAppendPrintf(boundary,
554 /* Start building our bounce message; go shopping for memory first. */
555 BounceMB = NewStrBufPlain(
557 1024 + /* mime stuff.... */
558 StrLength(Msg) + /* the bounce information... */
559 StrLength(OMsgTxt)); /* the original message */
560 if (BounceMB == NULL) {
561 FreeStrBuf(&boundary);
562 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
567 bmsg = (struct CtdlMessage *) malloc(sizeof(struct CtdlMessage));
569 FreeStrBuf(&boundary);
570 FreeStrBuf(&BounceMB);
571 syslog(LOG_ERR, "Failed to alloc() bounce message.\n");
575 memset(bmsg, 0, sizeof(struct CtdlMessage));
578 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: multipart/mixed; boundary=\""), 0);
579 StrBufAppendBuf(BounceMB, boundary, 0);
580 StrBufAppendBufPlain(BounceMB, HKEY("\"\r\n"), 0);
581 StrBufAppendBufPlain(BounceMB, HKEY("MIME-Version: 1.0\r\n"), 0);
582 StrBufAppendBufPlain(BounceMB, HKEY("X-Mailer: " CITADEL "\r\n"), 0);
583 StrBufAppendBufPlain(BounceMB, HKEY("\r\nThis is a multipart message in MIME format.\r\n\r\n"), 0);
584 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
585 StrBufAppendBuf(BounceMB, boundary, 0);
586 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
587 StrBufAppendBufPlain(BounceMB, HKEY("Content-type: text/plain\r\n\r\n"), 0);
590 StrBufAppendBufPlain(
593 "A message you sent could not be delivered "
594 "to some or all of its recipients\n"
595 "due to prolonged unavailability "
596 "of its destination(s).\n"
597 "Giving up on the following addresses:\n\n"
600 StrBufAppendBufPlain(
603 "A message you sent could not be delivered "
604 "to some or all of its recipients.\n"
605 "The following addresses "
606 "were undeliverable:\n\n"
609 StrBufAppendBuf(BounceMB, Msg, 0);
612 if (StrLength(MyQItem->SenderRoom) > 0)
614 StrBufAppendBufPlain(
616 HKEY("The message was originaly posted in: "), 0);
617 StrBufAppendBuf(BounceMB, MyQItem->SenderRoom, 0);
618 StrBufAppendBufPlain(
623 /* Attach the original message */
624 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
625 StrBufAppendBuf(BounceMB, boundary, 0);
626 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
627 StrBufAppendBufPlain(BounceMB,
628 HKEY("Content-type: message/rfc822\r\n"), 0);
629 StrBufAppendBufPlain(BounceMB,
630 HKEY("Content-Transfer-Encoding: 7bit\r\n"), 0);
631 StrBufAppendBufPlain(BounceMB,
632 HKEY("Content-Disposition: inline\r\n"), 0);
633 StrBufAppendBufPlain(BounceMB, HKEY("\r\n"), 0);
634 StrBufAppendBuf(BounceMB, OMsgTxt, 0);
636 /* Close the multipart MIME scope */
637 StrBufAppendBufPlain(BounceMB, HKEY("--"), 0);
638 StrBufAppendBuf(BounceMB, boundary, 0);
639 StrBufAppendBufPlain(BounceMB, HKEY("--\r\n"), 0);
641 bmsg->cm_magic = CTDLMESSAGE_MAGIC;
642 bmsg->cm_anon_type = MES_NORMAL;
643 bmsg->cm_format_type = FMT_RFC822;
645 bmsg->cm_fields['O'] = strdup(MAILROOM);
646 bmsg->cm_fields['A'] = strdup("Citadel");
647 bmsg->cm_fields['N'] = strdup(config.c_nodename);
648 bmsg->cm_fields['U'] = strdup("Delivery Status Notification (Failure)");
649 bmsg->cm_fields['M'] = SmashStrBuf(&BounceMB);
651 /* First try the user who sent the message */
652 if (StrLength(MyQItem->BounceTo) == 0)
653 syslog(LOG_ERR, "No bounce address specified\n");
655 syslog(LOG_DEBUG, "bounce to user? <%s>\n",
656 ChrPtr(MyQItem->BounceTo));
658 /* Can we deliver the bounce to the original sender? */
659 valid = validate_recipients(ChrPtr(MyQItem->BounceTo), NULL, 0);
660 if ((valid != NULL) && (valid->num_error == 0)) {
661 CtdlSubmitMsg(bmsg, valid, "", QP_EADDR);
662 successful_bounce = 1;
665 /* If not, post it in the Aide> room */
666 if (successful_bounce == 0) {
667 CtdlSubmitMsg(bmsg, NULL, config.c_aideroom, QP_EADDR);
670 /* Free up the memory we used */
671 free_recipients(valid);
672 FreeStrBuf(&boundary);
673 CtdlFreeMessage(bmsg);
674 syslog(LOG_DEBUG, "Done processing bounces\n");
680 * Called by smtp_do_queue() to handle an individual message.
682 void smtp_do_procmsg(long msgnum, void *userdata) {
683 int mynumsessions = num_sessions;
684 struct CtdlMessage *msg = NULL;
694 ParsedURL *RelayUrls = NULL;
698 if (mynumsessions > max_sessions_for_outbound_smtp) {
700 "SMTP Queue: skipping because of num jobs %d > %d max_sessions_for_outbound_smtp",
702 max_sessions_for_outbound_smtp);
705 syslog(LOG_DEBUG, "SMTP Queue: smtp_do_procmsg(%ld)\n", msgnum);
706 ///strcpy(envelope_from, "");
708 msg = CtdlFetchMessage(msgnum, 1);
710 syslog(LOG_ERR, "SMTP Queue: tried %ld but no such message!\n",
715 pch = instr = msg->cm_fields['M'];
717 /* Strip out the headers (no not amd any other non-instruction) line */
718 while (pch != NULL) {
719 pch = strchr(pch, '\n');
720 if ((pch != NULL) && (*(pch + 1) == '\n')) {
725 PlainQItem = NewStrBufPlain(instr, -1);
726 CtdlFreeMessage(msg);
727 MyQItem = DeserializeQueueItem(PlainQItem, msgnum);
728 FreeStrBuf(&PlainQItem);
730 if (MyQItem == NULL) {
732 "SMTP Queue: Msg No %ld: already in progress!\n",
734 return; /* s.b. else is already processing... */
738 * Postpone delivery if we've already tried recently.
740 if ((MyQItem->ReattemptWhen != 0) &&
741 (time(NULL) < MyQItem->ReattemptWhen) &&
742 (run_queue_now == 0))
744 syslog(LOG_DEBUG, "SMTP client: Retry time not yet reached.\n");
746 It = GetNewHashPos(MyQItem->MailQEntries, 0);
747 pthread_mutex_lock(&ActiveQItemsLock);
749 if (GetHashPosFromKey(ActiveQItems,
750 LKEY(MyQItem->MessageID),
753 DeleteEntryFromHash(ActiveQItems, It);
756 pthread_mutex_unlock(&ActiveQItemsLock);
757 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
763 * Bail out if there's no actual message associated with this
765 if (MyQItem->MessageID < 0L) {
766 syslog(LOG_ERR, "SMTP Queue: no 'msgid' directive found!\n");
767 It = GetNewHashPos(MyQItem->MailQEntries, 0);
768 pthread_mutex_lock(&ActiveQItemsLock);
770 if (GetHashPosFromKey(ActiveQItems,
771 LKEY(MyQItem->MessageID),
774 DeleteEntryFromHash(ActiveQItems, It);
777 pthread_mutex_unlock(&ActiveQItemsLock);
779 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
785 ParsedURL **Url = &MyQItem->URL;
786 nRelays = get_hosts(mxbuf, "smarthost");
790 const char *Pos = NULL;
791 All = NewStrBufPlain(mxbuf, -1);
792 One = NewStrBufPlain(NULL, StrLength(All) + 1);
794 while ((Pos != StrBufNOTNULL) &&
798 StrBufExtract_NextToken(One, All, &Pos, '|');
799 if (!ParseURL(Url, One, 25))
801 "Failed to parse: %s\n",
804 ///if (!Url->IsIP)) // todo dupe me fork ipv6
812 Url = &MyQItem->FallBackHost;
813 nRelays = get_hosts(mxbuf, "fallbackhost");
817 const char *Pos = NULL;
818 All = NewStrBufPlain(mxbuf, -1);
819 One = NewStrBufPlain(NULL, StrLength(All) + 1);
821 while ((Pos != StrBufNOTNULL) &&
825 StrBufExtract_NextToken(One, All, &Pos, '|');
826 if (!ParseURL(Url, One, 25))
828 "Failed to parse: %s\n",
838 It = GetNewHashPos(MyQItem->MailQEntries, 0);
839 while (GetNextHashPos(MyQItem->MailQEntries, It, &len, &Key, &vQE))
841 MailQEntry *ThisItem = vQE;
842 syslog(LOG_DEBUG, "SMTP Queue: Task: <%s> %d\n",
843 ChrPtr(ThisItem->Recipient),
848 MyQItem->ActiveDeliveries = CountActiveQueueEntries(MyQItem);
850 /* failsafe against overload:
851 * will we exceed the limit set?
853 if ((MyQItem->ActiveDeliveries + mynumsessions > max_sessions_for_outbound_smtp) &&
854 /* if yes, did we reach more than half of the quota? */
855 ((mynumsessions * 2) > max_sessions_for_outbound_smtp) &&
856 /* if... would we ever fit into half of the quota?? */
857 (((MyQItem->ActiveDeliveries * 2) < max_sessions_for_outbound_smtp)))
859 /* abort delivery for another time. */
861 "SMTP Queue: skipping because of num jobs %d + %ld > %d max_sessions_for_outbound_smtp",
863 MyQItem->ActiveDeliveries,
864 max_sessions_for_outbound_smtp);
866 FreeQueItem(&MyQItem);
872 if (MyQItem->ActiveDeliveries > 0)
876 int m = MyQItem->ActiveDeliveries;
878 Msg = smtp_load_msg(MyQItem, n);
879 It = GetNewHashPos(MyQItem->MailQEntries, 0);
881 (GetNextHashPos(MyQItem->MailQEntries,
882 It, &len, &Key, &vQE)))
884 MailQEntry *ThisItem = vQE;
886 if (ThisItem->Active == 1)
888 int KeepBuffers = (i == m);
891 if (nActivated % ndelay_count == 0)
894 if (i > 1) n = MsgCount++;
896 "SMTPQ: Trying <%ld> <%s> %d / %d \n",
898 ChrPtr(ThisItem->Recipient),
901 smtp_try_one_queue_entry(MyQItem,
908 if (KeepBuffers) HaveBuffers = 1;
917 It = GetNewHashPos(MyQItem->MailQEntries, 0);
918 pthread_mutex_lock(&ActiveQItemsLock);
920 if (GetHashPosFromKey(ActiveQItems,
921 LKEY(MyQItem->MessageID),
924 DeleteEntryFromHash(ActiveQItems, It);
933 "SMTP cleanup: unable to find "
934 "QItem with ID[%ld]",
936 while (GetNextHashPos(ActiveQItems,
943 "SMTP cleanup: have: ID[%ld]",
944 ((OneQueItem *)VData)->MessageID);
949 pthread_mutex_unlock(&ActiveQItemsLock);
951 ////FreeQueItem(&MyQItem); TODO: DeleteEntryFromHash frees this?
953 // TODO: bounce & delete?
958 // TODO : free RelayUrls
965 * smtp_queue_thread()
967 * Run through the queue sending out messages.
969 void smtp_do_queue(void) {
970 static int is_running = 0;
971 int num_processed = 0;
974 return; /* Concurrency check - only one can run */
977 pthread_setspecific(MyConKey, (void *)&smtp_queue_CC);
978 syslog(LOG_INFO, "SMTP client: processing outbound queue");
980 if (CtdlGetRoom(&CC->room, SMTP_SPOOLOUT_ROOM) != 0) {
981 syslog(LOG_ERR, "Cannot find room <%s>", SMTP_SPOOLOUT_ROOM);
984 num_processed = CtdlForEachMessage(MSGS_ALL,
993 "SMTP client: queue run completed; %d messages processed",
1003 * Initialize the SMTP outbound queue
1005 void smtp_init_spoolout(void) {
1006 struct ctdlroom qrbuf;
1009 * Create the room. This will silently fail if the room already
1010 * exists, and that's perfectly ok, because we want it to exist.
1012 CtdlCreateRoom(SMTP_SPOOLOUT_ROOM, 3, "", 0, 1, 0, VIEW_QUEUE);
1015 * Make sure it's set to be a "system room" so it doesn't show up
1016 * in the <K>nown rooms list for Aides.
1018 if (CtdlGetRoomLock(&qrbuf, SMTP_SPOOLOUT_ROOM) == 0) {
1019 qrbuf.QRflags2 |= QR2_SYSTEM;
1020 CtdlPutRoomLock(&qrbuf);
1027 /*****************************************************************************/
1028 /* SMTP UTILITY COMMANDS */
1029 /*****************************************************************************/
1031 void cmd_smtp(char *argbuf) {
1038 if (CtdlAccessCheck(ac_aide)) return;
1040 extract_token(cmd, argbuf, 0, '|', sizeof cmd);
1042 if (!strcasecmp(cmd, "mx")) {
1043 extract_token(node, argbuf, 1, '|', sizeof node);
1044 num_mxhosts = getmx(buf, node);
1045 cprintf("%d %d MX hosts listed for %s\n",
1046 LISTING_FOLLOWS, num_mxhosts, node);
1047 for (i=0; i<num_mxhosts; ++i) {
1048 extract_token(node, buf, i, '|', sizeof node);
1049 cprintf("%s\n", node);
1055 else if (!strcasecmp(cmd, "runqueue")) {
1057 cprintf("%d All outbound SMTP will be retried now.\n", CIT_OK);
1062 cprintf("%d Invalid command.\n", ERROR + ILLEGAL_VALUE);
1068 CTDL_MODULE_INIT(smtp_queu)
1074 pstr = getenv("CITSERVER_n_session_max");
1075 if ((pstr != NULL) && (*pstr != '\0'))
1076 max_sessions_for_outbound_smtp = atol(pstr); /* how many sessions might be active till we stop adding more smtp jobs */
1078 pstr = getenv("CITSERVER_smtp_n_delay_count");
1079 if ((pstr != NULL) && (*pstr != '\0'))
1080 ndelay_count = atol(pstr); /* every n queued messages we will sleep... */
1082 pstr = getenv("CITSERVER_smtp_delay");
1083 if ((pstr != NULL) && (*pstr != '\0'))
1084 delay_msec = atol(pstr) * 1000; /* this many seconds. */
1089 CtdlFillSystemContext(&smtp_queue_CC, "SMTP_Send");
1090 ActiveQItems = NewHash(1, lFlathash);
1091 pthread_mutex_init(&ActiveQItemsLock, NULL);
1093 QItemHandlers = NewHash(0, NULL);
1095 Put(QItemHandlers, HKEY("msgid"), QItem_Handle_MsgID, reference_free_handler);
1096 Put(QItemHandlers, HKEY("envelope_from"), QItem_Handle_EnvelopeFrom, reference_free_handler);
1097 Put(QItemHandlers, HKEY("retry"), QItem_Handle_retry, reference_free_handler);
1098 Put(QItemHandlers, HKEY("attempted"), QItem_Handle_Attempted, reference_free_handler);
1099 Put(QItemHandlers, HKEY("remote"), QItem_Handle_Recipient, reference_free_handler);
1100 Put(QItemHandlers, HKEY("bounceto"), QItem_Handle_BounceTo, reference_free_handler);
1101 Put(QItemHandlers, HKEY("source_room"), QItem_Handle_SenderRoom, reference_free_handler);
1102 Put(QItemHandlers, HKEY("submitted"), QItem_Handle_Submitted, reference_free_handler);
1103 smtp_init_spoolout();
1105 CtdlRegisterEVCleanupHook(smtp_evq_cleanup);
1107 CtdlRegisterProtoHook(cmd_smtp, "SMTP", "SMTP utility commands");
1108 CtdlRegisterSessionHook(smtp_do_queue, EVT_TIMER);
1111 /* return our Subversion id for the Log */
1112 return "smtpeventclient";