-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod_smtp_delivery_external.c
1921 lines (1702 loc) · 71.2 KB
/
mod_smtp_delivery_external.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* LBBS -- The Lightweight Bulletin Board System
*
* Copyright (C) 2023, Naveen Albert
*
* Naveen Albert <[email protected]>
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief External mail queuing and delivery
*
* \note Supports RFC 7505 Null MX
*
* \author Naveen Albert <[email protected]>
*/
#include "include/bbs.h"
#include <ctype.h>
#include <time.h>
#include <sys/stat.h>
#include <utime.h> /* use utimbuf */
#include <arpa/inet.h>
#include <netdb.h>
#include <arpa/nameser.h>
#ifdef __FreeBSD__
/* Needed for sockaddr_in in resolv.h on FreeBSD */
#include <netinet/in.h>
#endif
#include <resolv.h>
#include "include/module.h"
#include "include/config.h"
#include "include/utils.h"
#include "include/node.h"
#include "include/user.h"
#include "include/stringlist.h"
#include "include/linkedlists.h"
#include "include/oauth.h"
#include "include/base64.h"
#include "include/cli.h"
#include "include/parallel.h"
#include "include/mod_mail.h"
#include "include/net_smtp.h"
#include "include/mod_smtp_client.h"
static int accept_relay_out = 1;
static int minpriv_relay_out = 0;
static int require_starttls_out = 0;
static int queue_outgoing = 1;
static int send_async = 1;
static int always_queue = 0;
static int notify_queue = 0;
static pthread_t queue_thread = 0;
static bbs_rwlock_t queue_lock;
static char queue_dir[256];
static unsigned int queue_interval = 60;
static unsigned int max_retries = 10;
static unsigned int max_age = 86400;
static time_t last_periodic_queue_run = 0;
struct mx_record {
int priority;
RWLIST_ENTRY(mx_record) entry;
char data[];
};
RWLIST_HEAD(mx_records, mx_record);
/*! \brief List of stringlists for static routes */
struct static_relay {
const char *hostname;
struct stringlist routes;
RWLIST_ENTRY(static_relay) entry;
char data[];
};
static RWLIST_HEAD_STATIC(static_relays, static_relay);
/*! \note static_relays should be locked when calling */
static int add_static_relay(const char *hostname, const char *route)
{
struct static_relay *s;
s = calloc(1, sizeof(*s) + strlen(hostname) + 1);
if (ALLOC_FAILURE(s)) {
return -1;
}
strcpy(s->data, hostname); /* Safe */
s->hostname = s->data;
stringlist_init(&s->routes);
stringlist_push_list(&s->routes, route);
RWLIST_INSERT_TAIL(&static_relays, s, entry);
return 0;
}
static void free_static_relay(struct static_relay *s)
{
stringlist_empty_destroy(&s->routes);
free(s);
}
/*!
* \brief Check whether a domain has a defined static route
* \internal
* \param domain
* \return Static routes to use, if defined (override MX lookup)
* \return NULL if no static routes (do MX lookup instead)
*/
static struct stringlist *get_static_routes(const char *domain)
{
char domainbuf[256];
struct stringlist *routes = NULL;
struct static_relay *s, *wildcard = NULL;
/* If it's an IP address, then we need to use that IP address, literally,
* i.e. static routes don't apply. */
if (*domain == '[') {
/* Probably begins a domain literal */
domain++;
if (!strlen_zero(domain)) {
bbs_strncpy_until(domainbuf, domain, sizeof(domainbuf), ']');
domain = domainbuf;
}
}
if (bbs_hostname_is_ipv4(domain)) {
return NULL;
}
RWLIST_RDLOCK(&static_relays);
RWLIST_TRAVERSE(&static_relays, s, entry) {
if (!strcmp(s->hostname, "*")) {
wildcard = s;
} else if (!strcasecmp(s->hostname, domain)) {
break;
}
}
s = s ? s : wildcard; /* The '*' route is special, and should match last. */
if (s) {
/* It's okay to return this directly,
* since once added, routes are not removed until the module unloads. */
routes = &s->routes;
}
RWLIST_UNLOCK(&static_relays);
return routes;
}
/*!
* \brief Fill the results list with the MX results in order of priority
* \param domain
* \param[out] results
* \retval 0 on success
* \retval -1 on failure
* \retval -2 if domain accepts no mail
*/
static int lookup_mx_all(const char *domain, struct stringlist *results)
{
char *hostname, *tmp;
unsigned char answer[PACKETSZ] = "";
char dispbuf[PACKETSZ] = "";
char domainbuf[256];
int res, i;
ns_msg msg;
ns_rr rr;
struct mx_records mxs; /* No need to bother locking this list, nobody else knows about it */
int priority;
struct mx_record *mx;
int added = 0;
if (strlen_zero(domain)) {
bbs_error("Missing domain\n");
return -1;
}
if (*domain == '[') {
/* Probably begins a domain literal */
domain++;
if (!strlen_zero(domain)) {
bbs_strncpy_until(domainbuf, domain, sizeof(domainbuf), ']');
domain = domainbuf;
}
}
if (bbs_hostname_is_ipv4(domain)) { /* IP address? Just send it there */
stringlist_push_tail(results, domain);
return 0;
}
res = res_query(domain, C_IN, T_MX, answer, sizeof(answer));
if (res == -1) {
bbs_error("res_query failed for '%s': %s\n", domain, strerror(errno));
return -1;
}
res = ns_initparse(answer, res, &msg);
if (res < 0) {
bbs_error("Failed to look up MX record: %s\n", strerror(errno));
return -1;
}
res = ns_msg_count(msg, ns_s_an);
if (res < 1) {
bbs_error("No MX records available\n");
return -1;
}
RWLIST_HEAD_INIT(&mxs);
/* Add each record to our sorted list */
for (i = 0; i < res; i++) {
ns_parserr(&msg, ns_s_an, i, &rr);
#pragma GCC diagnostic ignored "-Wdeprecated-declarations" /* ns_sprintrr deprecated */
ns_sprintrr(&msg, &rr, NULL, NULL, dispbuf, sizeof(dispbuf));
#pragma GCC diagnostic pop /* -Wdeprecated-declarations */
bbs_debug(8, "NS answer: %s\n", dispbuf);
/* Parse the result */
hostname = dispbuf;
/* Results will be formatted like so:
* gmail.com. 1H IN MX 30 alt3.gmail-smtp-in.l.google.com.
* gmail.com. 1H IN MX 5 gmail-smtp-in.l.google.com.
* gmail.com. 1H IN MX 20 alt2.gmail-smtp-in.l.google.com.
* gmail.com. 1H IN MX 40 alt4.gmail-smtp-in.l.google.com.
* gmail.com. 1H IN MX 10 alt1.gmail-smtp-in.l.google.com.
*
* If there is no MX record, we'll get something like:
* example.com. 1D IN MX 0 .
* This is actually a special case in RFC 7505, which indicates the domain
* receives no mail. In this case, we should NOT fall back to the A or AAAA record.
* We should immediately abort.
*/
tmp = strstr(hostname, "MX");
if (!tmp) {
bbs_debug(3, "Skipping unexpected MX NS answer: %s\n", dispbuf);
continue;
}
tmp += STRLEN("MX");
ltrim(tmp);
hostname = tmp;
tmp = strsep(&hostname, " ");
priority = atoi(tmp); /* Note that 0 is a valid (and the highest) priority */
tmp = strrchr(hostname, '.');
if (tmp) {
*tmp = '\0'; /* Strip trailing . */
}
if (strlen_zero(hostname)) { /* No MX record */
/* The record was just a ., which means
* the domain accepts no mail. */
RWLIST_REMOVE_ALL(&mxs, entry, free);
RWLIST_HEAD_DESTROY(&mxs);
stringlist_empty(results);
bbs_warning("Domain %s does not accept mail\n", domain);
return -2;
}
/* Insert in order of priority */
mx = calloc(1, sizeof(*mx) + strlen(hostname) + 1);
if (ALLOC_FAILURE(mx)) {
continue;
}
strcpy(mx->data, hostname); /* Safe */
mx->priority = priority;
RWLIST_INSERT_SORTED(&mxs, mx, entry, priority);
added++;
}
if (!added) {
bbs_warning("No MX records available for %s\n", domain);
RWLIST_HEAD_DESTROY(&mxs);
return -1;
}
/* Now that we have it ordered, we don't actually care about the priorities themselves.
* Just return a stringlist to the client, with results ordered by priority. */
/* XXX Technically, the SMTP spec says we should randomly choose between MX servers
* with the same priority.
* While we don't do this currently, the DNS response has them in random order to begin with,
* so that might add some randomness.
*/
while ((mx = RWLIST_REMOVE_HEAD(&mxs, entry))) {
stringlist_push_tail(results, mx->data);
bbs_debug(3, "MX result for %s: server %s has priority %d\n", domain, mx->data, mx->priority);
free(mx);
}
RWLIST_HEAD_DESTROY(&mxs);
return 0;
}
struct smtp_tx_data {
char hostname[256];
char ipaddr[128];
const char *prot;
const char *stage;
};
static void smtp_tx_data_reset(struct smtp_tx_data *tx)
{
tx->hostname[0] = '\0';
tx->ipaddr[0] = '\0';
tx->prot = NULL;
tx->stage = NULL;
}
#ifdef DEBUG_MAIL_DATA
#define debug_data(srcfd, offset, writelen) __debug_data(srcfd, offset, writelen, __LINE__)
static int __debug_data(int srcfd, off_t offset, size_t writelen, int lineno)
{
/* Some built in dumping is included,
* since most connections probably use STARTTLS,
* making it more difficult to use tcpdump / tcpflow to debug. */
/* WARNING: This could malloc a lot of data. Do not define DEBUG_MAIL_DATA in production!
* Only compile with it when actively debugging a delivery issue. */
char *debugbuf;
if (lseek(srcfd, offset, SEEK_SET) == -1) {
bbs_error("lseek failed: %s\n", strerror(errno));
return -1;
}
debugbuf = malloc(writelen + 1); /* NUL terminate for bbs_str_contains_bare_lf */
if (ALLOC_SUCCESS(debugbuf)) {
ssize_t rres = bbs_timed_read(srcfd, debugbuf, writelen, 50);
if (rres > 0) {
int bare_lf;
debugbuf[writelen] = '\0'; /* NUL terminate for bbs_str_contains_bare_lf */
bare_lf = bbs_str_contains_bare_lf(debugbuf);
if (bare_lf) {
bbs_warning("Line %d: message contains %d bare LF%s and may be rejected by receiving MTA\n", lineno, bare_lf, ESS(bare_lf));
bbs_debug(7, "Dumping %ld-byte body:\n", rres);
bbs_dump_mem((const unsigned char*) debugbuf, (size_t) rres);
free(debugbuf);
return 1;
}
} else if (rres < 0) {
bbs_error("read failed: %s\n", strerror(errno));
}
free(debugbuf);
}
return 0;
}
#endif
/*!
* \brief Attempt to send an external message to another mail transfer agent or message submission agent
* \param smtp SMTP session. Generally, this will be NULL except for relayed messages, which are typically the only time this is needed.
* \param hostname Hostname of mail server
* \param port Port of mail server
* \param secure Whether to use Implicit TLS (typically for MSAs on port 465). If 0, STARTTLS will be attempted (but not required unless require_starttls_out = yes)
* \param username SMTP MSA username
* \param password SMTP MSA password
* \param sender The MAIL FROM for the message
* \param recipient A single recipient for RCPT TO
* \param recipients A list of recipients for RCPT TO. Either recipient or recipients must be specified.
* \param prepend Data to prepend
* \param prependlen Length of prepend
* \param datafd A file descriptor containing the message data (used instead of data/datalen)
* \param offset sendfile offset for message (sent data will begin here)
* \param writelen Number of bytes to send
* \param[out] buf Buffer in which to temporarily store SMTP responses
* \param len Size of buf.
* \retval -1 on temporary error, 1 on permanent error, 0 on success
*/
static int try_send(struct smtp_session *smtp, struct smtp_tx_data *tx, const char *hostname, int port, int secure, const char *username, const char *password, const char *sender, const char *recipient, struct stringlist *recipients,
const char *prepend, size_t prependlen, int datafd, off_t offset, size_t writelen, char *buf, size_t len)
{
int res = -1;
ssize_t wrote = 0;
struct bbs_smtp_client smtpclient;
off_t send_offset;
char sendercopy[64];
char *user, *domain, *saslstr = NULL;
#define SMTP_EOM "\r\n.\r\n"
bbs_assert(datafd != -1);
bbs_assert(writelen > 0);
/* RFC 5322 3.4.1 allows us to use IP addresses in SMTP as well (domain literal form). They just need to be enclosed in square brackets. */
safe_strncpy(sendercopy, sender, sizeof(sendercopy));
/* Properly parse, since if a name is present, in addition to the email address, we must exclude the name in the MAIL FROM */
if (bbs_parse_email_address(sendercopy, NULL, &user, &domain)) {
bbs_error("Invalid email address: %s\n", sender);
return -1;
}
if (!strlen_zero(user) && strlen_zero(domain)) {
/* Can't pass NULL domain to bbs_hostname_is_ipv4 */
bbs_error("Invalid email address (user=%s, empty domain)\n", user);
return -1;
}
#ifdef DEBUG_MAIL_DATA
/* Dump the DATA of the transaction to the CLI for debugging purposes. */
if (prepend && prependlen) {
bbs_dump_mem((const unsigned char*) prepend, prependlen);
}
if (debug_data(datafd, offset, writelen)) {
/* Proactively reject the message ourselves,
* before even establishing a connection to another MTA,
* which would make us look bad. */
if (strstr(hostname, "me.com") || strstr(hostname, "icloud.com")) {
snprintf(buf, len, "Bare <LF> detected (in DATA command)");
return 1; /* Return permanent failure */
}
}
bbs_dump_mem((const unsigned char*) SMTP_EOM, STRLEN(SMTP_EOM));
#endif
tx->prot = "x-tcp";
if (bbs_smtp_client_connect(&smtpclient, smtp_hostname(), hostname, port, secure, buf, len)) {
/* Unfortunately, we can't try an alternate port as there is no provision
* for letting other SMTP MTAs know that they should try some port besides 25.
* So if your ISP blocks incoming traffic on port 25 or you can't use port 25
* for whatever reason, you're kind of out luck: you won't be able to receive
* mail from the outside world. */
snprintf(buf, len, "Connection refused");
return -1;
}
smtp_tx_data_reset(tx);
bbs_get_fd_ip(smtpclient.client.fd, tx->ipaddr, sizeof(tx->ipaddr));
safe_strncpy(tx->hostname, hostname, sizeof(tx->hostname));
bbs_debug(3, "Attempting delivery of %lu-byte message from %s -> %s via %s\n", writelen, sender, recipient, hostname);
SMTP_CLIENT_EXPECT_FINAL(&smtpclient, MIN_MS(5), "220"); /* RFC 5321 4.5.3.2.1 (though for final 220, not any of them) */
res = bbs_smtp_client_handshake(&smtpclient, require_starttls_out);
if (res) {
goto cleanup;
}
tx->prot = "smtp";
if (!secure) {
if (smtpclient.caps & SMTP_CAPABILITY_STARTTLS) {
if (bbs_smtp_client_starttls(&smtpclient)) {
res = -1;
goto cleanup; /* Abort if we were told STARTTLS was available but failed to negotiate. */
}
} else if (require_starttls_out) {
bbs_warning("SMTP server %s does not support STARTTLS, but encryption is mandatory. Delivery failed.\n", hostname);
snprintf(buf, len, "STARTTLS not supported");
res = 1;
goto cleanup;
} else if (!bbs_hostname_is_ipv4(hostname) || bbs_ip_is_public_ipv4(hostname)) { /* Don't emit this warning for non-public IPs */
bbs_warning("SMTP server %s does not support STARTTLS. This message will not be transmitted securely!\n", hostname);
}
}
if (smtpclient.maxsendsize && (int) (prependlen + writelen) > smtpclient.maxsendsize) {
/* We know the message we're trying to send is larger than the max message size the server will accept.
* Just abort now. */
bbs_warning("Total message size (%lu) is larger than server accepts (%d)\n", prependlen + writelen, smtpclient.maxsendsize);
snprintf(buf, len, "Message too large (%lu bytes, maximum is %d)", prependlen + writelen, smtpclient.maxsendsize);
res = 1;
goto cleanup;
}
if (username && password) {
if (STARTS_WITH(password, "oauth:")) { /* OAuth authentication */
char token[512];
char decoded[568];
int decodedlen, encodedlen;
char *encoded;
const char *oauthprofile = password + STRLEN("oauth:");
if (!(smtpclient.caps & SMTP_CAPABILITY_AUTH_XOAUTH2)) {
bbs_warning("SMTP server does not support XOAUTH2\n");
snprintf(buf, len, "XOAUTH2 not supported");
res = -1;
goto cleanup;
} else if (!smtp || !smtp_node(smtp) || !bbs_user_is_registered(smtp_node(smtp)->user)) {
bbs_warning("Cannot look up OAuth tokens without an authenticated SMTP session\n");
res = -1;
goto cleanup;
}
/* Typically, smtp is NULL, except for relayed mail.
* This means this functionality here only works for relayed mail (from MailScript RELAY rule).
* The reason we need it in this case is to ensure that the oauth: profile specified by the user
* is one that the user is actually authorized to use. */
res = bbs_get_oauth_token(smtp_node(smtp)->user, oauthprofile, token, sizeof(token));
if (res) {
bbs_warning("OAuth token '%s' does not exist for user %d\n", oauthprofile, smtp_node(smtp)->user->id);
res = -1;
goto cleanup;
}
/* https://developers.google.com/gmail/imap/xoauth2-protocol#smtp_protocol_exchange */
decodedlen = snprintf(decoded, sizeof(decoded), "user=%s%cauth=Bearer %s%c%c", username, 0x01, token, 0x01, 0x01);
encoded = base64_encode(decoded, decodedlen, &encodedlen);
if (!encoded) {
bbs_error("Base64 encoding failed\n");
res = -1;
goto cleanup;
}
bbs_smtp_client_send(&smtpclient, "AUTH XOAUTH2 %s\r\n", encoded);
free(encoded);
res = bbs_tcp_client_expect(&smtpclient.client, "\r\n", 1, SEC_MS(5), "235");
if (res) {
/* If we get 334 here, that means we failed: https://developers.google.com/gmail/imap/xoauth2-protocol#smtp_protocol_exchange
* We should send an empty reply to get the error message. */
if (STARTS_WITH(buf, "334")) {
bbs_smtp_client_send(&smtpclient, "\r\n");
SMTP_EXPECT(&smtpclient, SEC_MS(5), "235"); /* We're not actually going to get a 235, but send the error to the console and abort */
bbs_warning("Huh? It worked?\n"); /* Shouldn't happen */
} else {
bbs_warning("Expected '%s', got: %s\n", "235", buf);
goto cleanup;
}
}
} else if (smtpclient.caps & SMTP_CAPABILITY_AUTH_LOGIN) {
saslstr = bbs_sasl_encode(username, username, password);
if (!saslstr) {
res = -1;
goto cleanup;
}
bbs_smtp_client_send(&smtpclient, "AUTH PLAIN\r\n"); /* AUTH PLAIN is preferred to the deprecated AUTH LOGIN */
SMTP_EXPECT(&smtpclient, SEC_MS(10), "334");
bbs_smtp_client_send(&smtpclient, "%s\r\n", saslstr);
SMTP_EXPECT(&smtpclient, SEC_MS(10), "235");
} else {
bbs_warning("No mutual login methods available\n");
res = -1;
goto cleanup;
}
}
tx->prot = "smtp";
tx->stage = "MAIL FROM";
if (!strlen_zero(user)) {
if (bbs_hostname_is_ipv4(domain)) {
bbs_smtp_client_send(&smtpclient, "MAIL FROM:<%s@[%s]>\r\n", user, domain); /* Domain literal for IP address */
} else {
bbs_smtp_client_send(&smtpclient, "MAIL FROM:<%s@%s>\r\n", user, domain); /* sender lacks <>, but recipient has them */
}
} else {
/* For non-delivery / postmaster sending */
bbs_smtp_client_send(&smtpclient, "MAIL FROM:<>\r\n");
}
SMTP_CLIENT_EXPECT_FINAL(&smtpclient, MIN_MS(5), "250"); /* RFC 5321 4.5.3.2.2 */
tx->stage = "RCPT FROM";
if (recipient) {
if (*recipient == '<') {
bbs_smtp_client_send(&smtpclient, "RCPT TO:%s\r\n", recipient);
} else {
bbs_warning("Queue file recipient did not contain <>\n"); /* Support broken queue files, but make some noise */
bbs_smtp_client_send(&smtpclient, "RCPT TO:<%s>\r\n", recipient);
}
SMTP_CLIENT_EXPECT_FINAL(&smtpclient, MIN_MS(5), "250"); /* RFC 5321 4.5.3.2.3 */
} else if (recipients) {
char *r;
while ((r = stringlist_pop(recipients))) {
bbs_smtp_client_send(&smtpclient, "RCPT TO:%s\r\n", r);
SMTP_CLIENT_EXPECT_FINAL(&smtpclient, MIN_MS(5), "250"); /* RFC 5321 4.5.3.2.3 */
free(r);
}
} else {
bbs_error("No recipients specified\n");
goto cleanup;
}
tx->stage = "DATA";
bbs_smtp_client_send(&smtpclient, "DATA\r\n");
SMTP_CLIENT_EXPECT_FINAL(&smtpclient, MIN_MS(2), "354"); /* RFC 5321 4.5.3.2.4 */
if (prepend && prependlen) {
wrote = bbs_write(smtpclient.client.wfd, prepend, (unsigned int) prependlen);
}
/* sendfile will be much more efficient than reading the file ourself, as email body could be quite large, and we don't need to involve userspace. */
send_offset = offset;
res = (int) bbs_sendfile(smtpclient.client.wfd, datafd, &send_offset, writelen);
/* XXX If email doesn't end in CR LF, we need to tack that on. But ONLY if it doesn't already end in CR LF. */
bbs_smtp_client_send(&smtpclient, SMTP_EOM); /* (end of) EOM */
tx->stage = "end of DATA";
if (res != (int) writelen) { /* Failed to write full message */
res = -1;
goto cleanup;
}
wrote += res;
bbs_debug(5, "Sent %lu bytes\n", wrote);
/* RFC 5321 4.5.3.2.6 */
SMTP_CLIENT_EXPECT_FINAL(&smtpclient, MIN_MS(10), "250"); /* Okay, this email is somebody else's problem now. */
bbs_debug(3, "Message successfully delivered to %s\n", recipient);
res = 0;
cleanup:
free_if(saslstr);
if (res > 0) {
bbs_smtp_client_send(&smtpclient, "QUIT\r\n");
}
bbs_smtp_client_destroy(&smtpclient);
/* Check if it's a permanent error, if it's not, return -1 instead of 1 */
if (res > 0) {
res = -1; /* Assume temporary unless we're sure it's not. */
if (STARTS_WITH(buf, "5")) {
bbs_debug(5, "Encountered permanent failure (%s)\n", buf);
res = 1; /* Permanent error. */
}
}
return res;
}
static void smtp_trigger_dsn(enum smtp_delivery_action action, struct smtp_tx_data *restrict tx, struct tm *created, const char *from, const char *to, char *error, int fd, size_t offset, size_t datalen)
{
char *tmp;
char status[15] = ""; /* Status code should be the 2nd word? */
struct smtp_delivery_outcome *f;
if (strlen_zero(from)) {
/* If this was triggered by a non-delivery report,
* then bail out now, since we can't
* reply if there was no MAIL FROM */
return;
}
if (action != DELIVERY_FAILED && !notify_queue) {
return;
} else if (action == DELIVERY_DELIVERED) {
time_t sent;
if (!created) {
bbs_warning("Message has no sent time?\n");
return;
}
sent = mktime(created);
if (sent > time(NULL) - 30) {
return; /* Don't send reports on success UNLESS a message was previously delayed */
}
/* Do send a delivery report, it was likely previous queued and succeeded only on a retry */
}
tmp = strchr(error, ' ');
if (tmp && ++tmp) {
ltrim(tmp);
if (isdigit(*tmp)) {
bbs_strncpy_until(status, error, sizeof(status), ' ');
}
}
f = smtp_delivery_outcome_new(to, tx->hostname, tx->ipaddr, status, error, tx->prot, tx->stage, action, NULL);
if (ALLOC_SUCCESS(f)) {
/*! \todo parameter 1 is the sendinghost: we should store this in the queue file so this information is available to us
* Even better, rather than trying to stuff it into the same file and using an offset, using some kind of out of band
* control file where we can record all the relevant information we'll want to keep. */
smtp_dsn(NULL, created, from, fd, (int) offset, datalen, &f, 1);
smtp_delivery_outcome_free(&f, 1);
}
}
enum mailq_run_type {
QUEUE_RUN_PERIODIC, /*!< Periodic queue run */
QUEUE_RUN_FORCED, /*!< On-demand queue run */
QUEUE_RUN_STAT, /*!< Not a real queue run, just for statistical purposes */
};
/*! \brief A single run of the mail queue */
struct mailq_run {
enum mailq_run_type type;
time_t runstart; /* Time that queue run started */
struct bbs_parallel *parallel; /* Parallel task set, if running in parallel. NULL if serial. */
/* Queue run filters to control what messages are processed */
const char *host_match; /* Domain restriction for queue processing */
const char *host_ends_with; /* Domain or suffix of domain, e.g. com, example.com, sub.example.com, etc. Queued processing will be restricted to matches. */
/* Queue run statistics */
/* processed is a subset of total, delivered + failed + delayed + skipped should = processed */
int total; /* Total number of queued messages considered */
int processed; /* Total number of queued messages processed. */
int delivered; /* Total number of queued messages actually delivered and removed from queue. */
int failed; /* Total number of queued messages failed permanently and removed from queue. */
int delayed; /* Total number of queued messages not yet delivered and remaining in queue. */
int skipped; /* Total number of queued messages skipped since it's too soon to retry delivery. */
/* Misc */
int clifd; /* CLI file descriptor */
bbs_mutex_t lock;
};
static inline void mailq_run_init(struct mailq_run *qrun, enum mailq_run_type type)
{
/* We could individually initialize each element in the struct,
* but as the struct probably has no padding,
* it's probably faster to just zero the whole darn thing. */
memset(qrun, 0, sizeof(struct mailq_run));
qrun->type = type;
bbs_mutex_init(&qrun->lock, NULL);
qrun->runstart = time(NULL);
}
static inline void mailq_run_cleanup(struct mailq_run *qrun)
{
bbs_mutex_destroy(&qrun->lock);
}
#define MAILQ_FILENAME_SIZE 516
/*! \brief A single message in the mail queue */
struct mailq_file {
FILE *fp;
unsigned long size;
size_t metalen;
char *realfrom, *realto;
char *user, *domain;
int retries; /*!< Number of times retried so far */
int newretries; /*!< retrycount + 1 */
struct tm created; /*!< Time message was added to the queue */
struct tm retried; /*!< Time message delivery was last attempted */
time_t createdtime; /*!< time_t of created */
time_t retriedtime; /*!< time_t of retried */
char fullname[MAILQ_FILENAME_SIZE];
char from[1000], recipient[1000], todup[256];
struct mailq_run *qrun; /*!< mailq_run to which this mailq_file belongs */
};
static inline void mailq_file_init(struct mailq_file *mqf, struct mailq_run *qrun)
{
memset(mqf, 0, sizeof(struct mailq_file));
mqf->qrun = qrun;
}
/*! \brief Cleanup callback called for parallel invocations */
static void mailq_file_destroy(void *varg)
{
struct mailq_file *mqf = varg;
/* If the file is still open, close it.
* Normally, we always close the file in process_queue_file,
* so this would only happen if allocating the task itself failed for some reason,
* and we had to abort and call the cleanup function. */
if (mqf->fp) {
fclose(mqf->fp);
}
free(mqf);
}
static void reset_accessed_time(struct mailq_file *restrict mqf)
{
struct utimbuf utb;
/* Since we didn't process this file for queuing,
* we reset the access timestamp to what it was
* before we accessed it. This allows us to accurately
* keep track of when delivery should be attempted next,
* without storing the timestamp explicitly anywhere else. */
/* We have to specify both times explicitly, not just one. */
utb.modtime = mqf->createdtime;
utb.actime = mqf->retriedtime;
if (utime(mqf->fullname, &utb)) {
bbs_error("Failed to set file timestamps for %s: %s\n", mqf->fullname, strerror(errno));
}
}
static int mailq_file_load(struct mailq_file *restrict mqf, const char *dir_name, const char *filename)
{
struct stat st;
const char *retries;
snprintf(mqf->fullname, sizeof(mqf->fullname), "%s/%s", dir_name, filename);
/* Do the stat call before opening the file,
* since opening it will change the file timestamps. */
if (stat(mqf->fullname, &st)) {
bbs_error("stat(%s) failed: %s\n", mqf->fullname, strerror(errno));
return -1;
}
mqf->fp = fopen(mqf->fullname, "rb");
if (!mqf->fp) {
bbs_error("Failed to open %s: %s\n", mqf->fullname, strerror(errno));
return -1;
}
fseek(mqf->fp, 0L, SEEK_END); /* Go to EOF */
mqf->size = (long unsigned) ftell(mqf->fp);
rewind(mqf->fp); /* Be kind, rewind */
if (!fgets(mqf->from, sizeof(mqf->from), mqf->fp) || !fgets(mqf->recipient, sizeof(mqf->recipient), mqf->fp)) {
bbs_error("Failed to read metadata from %s\n", mqf->fullname);
goto cleanup;
}
mqf->metalen = strlen(mqf->from) + strlen(mqf->recipient); /* This already includes the newlines */
retries = strchr(mqf->fullname, '.');
if (!retries++ || strlen_zero(retries)) { /* Shouldn't happen for mail queue files legitimately generated by this module, but somebody else might have dumped stuff in. */
bbs_error("File name '%s' is non-compliant with our filename format\n", mqf->fullname);
goto cleanup;
}
mqf->retries = atoi(retries);
/* If you manually edit the queue files, the line endings will get converted,
* and since the queue files use a combination of LF and CR LF,
* that can mess things up.
* In particular, something like nano will convert everything to LF,
* so bbs_readline will return the entire body as one big blob,
* since the file has no CR LF delimiters at all.
* And because rely on CR LF . CR LF for end of email detection,
* we'll only see LF . CR LF at the end, and delivery will thus fail.
* Do not modify the mail queue files manually for debugging, unless you really know what you are doing,
* and in particular are preserving the mixed line endings. */
bbs_term_line(mqf->from);
bbs_term_line(mqf->recipient);
mqf->realfrom = strchr(mqf->from, '<');
mqf->realto = strchr(mqf->recipient, '<');
/* The actual MAIL FROM can be empty if this is a nondelivery report, so we do not validate that it is non-empty (it may be the empty string). */
if (!mqf->realfrom) {
bbs_error("Mail queue file MAIL FROM missing <>: %s\n", mqf->fullname);
goto cleanup;
} else if (!mqf->realto) {
bbs_error("Mail queue file RCPT TO missing <>: %s\n", mqf->fullname);
goto cleanup;
}
mqf->realfrom++; /* Skip < */
if (strlen_zero(mqf->realfrom)) {
bbs_error("Malformed MAIL FROM: %s\n", mqf->fullname);
goto cleanup;
}
bbs_strterm(mqf->realfrom, '>'); /* try_send will add <> for us, so strip it here to match */
if (bbs_str_count(mqf->realfrom, '<') || bbs_str_count(mqf->realfrom, '>') || bbs_str_count(mqf->realto, '<') != 1 || bbs_str_count(mqf->realto, '>') != 1) {
bbs_error("Sender or recipient address malformed %s -> %s\n", mqf->realfrom, mqf->realto);
goto cleanup;
}
safe_strncpy(mqf->todup, mqf->realto, sizeof(mqf->todup));
if (bbs_parse_email_address(mqf->todup, NULL, &mqf->user, &mqf->domain)) {
bbs_error("Address parsing error\n");
goto cleanup;
}
/* See stat(3) for how stat presents the time.
* st_atime = st_atim.tv_sec
* st_mtime = st_mtim.tv_sec
*
* st_atim and st_mtim themselves are of type struct timespec.
* st_atime and st_mtime (and the tv_sec components) are time_t.
*/
/* These are useful for doing time calculations */
mqf->createdtime = st.st_mtim.tv_sec;
mqf->retriedtime = st.st_atim.tv_sec;
/* These variants are more useful for printing timestamps */
memset(&mqf->created, 0, sizeof(mqf->created));
memset(&mqf->retried, 0, sizeof(mqf->retried));
/* st_mtim is the time of the last modifications.
* We don't modify queue files after they are created,
* (renaming does not update this timestamp)
* so this should be when the file was created,
* i.e. when the message was added to the queue. */
localtime_r(&st.st_mtim.tv_sec, &mqf->created);
/* Now, for when the message was last attempted.
* st_atim is a good candidate for this, since it's
* updated whenever the file is accessed, e.g. opened,
* so it will update every time it's retried for queuing.
* Problem is that if skip_qfile is true, we DIDN'T retry
* delivery (and even if not, for QUEUE_RUN_STAT, we didn't retry anything).
* So, we need to reset st_atim when we've accessed a queue file
* without attempting delivery.
*
* If people manually open a queue file, that will also update
* the timestamp and interfere with this, but otherwise, this covers everything. */
localtime_r(&st.st_atim.tv_sec, &mqf->retried);
return 0;
cleanup:
fclose(mqf->fp);
mqf->fp = NULL;
/* Okay if file timestamps are updated, since an error happened, anyways */
return -1;
}
static int mailq_file_punt(struct mailq_file *mqf)
{
char newname[MAILQ_FILENAME_SIZE + 11];
char tmpbuf[256];
bbs_strncpy_until(tmpbuf, mqf->fullname, sizeof(tmpbuf), '.');
/* Store retry information in the filename itself, so we don't have to modify the file, we can just rename it. Inspired by IMAP. */
snprintf(newname, sizeof(newname), "%s.%d", tmpbuf, mqf->newretries);
if (rename(mqf->fullname, newname)) {
bbs_error("Failed to rename %s to %s\n", mqf->fullname, newname);
return -1;
}
return 0;
}
/*! \brief Attempt to send a message via SMTP using static routes instead of doing an MX lookup */
static int try_static_delivery(struct smtp_session *smtp, struct smtp_tx_data *tx, struct stringlist *static_routes, const char *sender, const char *recipient, int datafd, off_t offset, size_t writelen, char *buf, size_t len)
{
const char *route;
struct stringitem *i = NULL;
int res = -1; /* Make condition true to start */
/* Static routes override doing an MX lookup for this domain.
* We have one or more hostnames (with an optionally specified port) to try. */
while (res < 0 && (route = stringlist_next(static_routes, &i))) {
char hostbuf[256];
const char *colon;
const char *hostname = route;
int port = DEFAULT_SMTP_PORT;
/* If this is a hostname:port, we need to split.
* Otherwise, we can use it directly. This is more efficient,
* since no allocations or copies are performed in this case. */
colon = strchr(route, ':');
if (colon) {
/* There's a port specified. */
bbs_strncpy_until(hostbuf, route, sizeof(hostbuf), ':'); /* Copy just the hostname */
hostname = hostbuf;
colon++;
if (!strlen_zero(colon)) {
port = atoi(colon); /* Parse the port */
if (port < 1) {
bbs_warning("Invalid port in route '%s', defaulting to port %d\n", route, DEFAULT_SMTP_PORT);
port = DEFAULT_SMTP_PORT;
}
}
}
res = try_send(smtp, tx, hostname, port, 0, NULL, NULL, sender, recipient, NULL, NULL, 0, datafd, offset, writelen, buf, len);
}
return res;
}
/*!
* \brief Calculate how long we should wait, at minimum, before retrying delivery of a requeued message
* \param retrycount Count of many times delivery has been attempted so far
* \return Number of seconds that should pass from the last retry before we attempt delivery again
*/
static inline time_t queue_retry_threshold(int retrycount)
{
/* We use ~exponential backoff for queue retry timing,
* as is generally recommended. */
switch (retrycount) {
case 0:
return 0;
/* RFC 5321 4.5.4.1 says the retry interval SHOULD be at least 30 minutes,
* but if the first delivery failed due to a super transient thing,
* it might be good to try a little sooner, at least once or twice.
* This is especially true if the other server has greylisted us,
* in which case the first retry should succeed. */
case 1:
return 60; /* 1 minute */
case 2:
return 360; /* 10 minutes */
case 3:
return 1800; /* 30 minutes */
case 4:
return 3600; /* 1 hour */
case 5:
return 10800; /* 3 hours */
case 6:
return 43200; /* 12 hours */
case 7 ... 10:
/* Per the RFC, the give-up time should be at least 4-5 days.
* At this point, it's already been over 4.5 days. */
default:
/* As we get to longer periods, cap retry interval at 1 day between attempts. */
return 86400; /* 1 day */
}
__builtin_unreachable();
}
static inline int skip_qfile(struct mailq_run *qrun, struct mailq_file *mqf)
{
/* This queue run may have filters applied to it */
/* Yeah, if we have a filter, we're possibly going to open
* all the files in the queue, only to almost immediately close most of them.
* One of our assumptions is the queue isn't going to be super large.
* If it were, it would very much be worth using a single queue "control file"
* with metadata about all the queue files, to avoid unnecessary file I/O. */
if (!strlen_zero(qrun->host_match) && !strlen_zero(mqf->domain) && strcmp(mqf->domain, qrun->host_match)) {
/* Exact match required */
#ifdef DEBUG_QUEUES
bbs_debug(8, "Skipping queue file %s (domain '%s' does not match filter '%s')\n", mqf->fullname, mqf->domain, qrun->host_match);
#endif
return 1;
} else if (!strlen_zero(qrun->host_ends_with) && !strlen_zero(mqf->domain) && !bbs_str_ends_with(mqf->domain, qrun->host_ends_with)) {
/* Domain must end in host_ends_with, to match. */