-
Notifications
You must be signed in to change notification settings - Fork 2
/
mxtarpit.c
1377 lines (1223 loc) · 30.6 KB
/
mxtarpit.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
/*
* Copyright (c) 2017 Martin Hedenfalk <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/queue.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include <errno.h>
#include <ev.h>
#include <fcntl.h>
#include <netdb.h>
#include <pwd.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <time.h>
#include <unistd.h>
#include <resolv.h> /* b64_pton */
struct mbuf {
char data[1024];
size_t len;
size_t ofs;
};
enum smtp_state {
smtp_sending_banner,
smtp_helo,
smtp_auth_login_username,
smtp_auth_login_password,
smtp_auth_plain,
smtp_data_response,
smtp_data,
smtp_close,
};
struct conn {
int fd;
struct ev_io read_watcher;
struct ev_io write_watcher;
struct ev_timer stutter;
struct ev_timer dnsbl_timer;
struct ev_timer idle_timer;
struct mbuf inbuf;
struct mbuf outbuf;
enum smtp_state state;
ev_tstamp connected_at;
in_addr_t ipv4;
TAILQ_ENTRY(conn) dnsbl_queue;
int is_spam;
int got_data;
int dnsbl_pending;
char addr[64];
char helo[64];
char from[128];
char rcpt[128];
unsigned char auth[64];
unsigned char pass[64];
};
struct domain {
char *name;
char **users;
size_t nusers;
int accept_any_user;
};
struct app_globals {
struct ev_loop *loop;
#define MAX_LISTENERS 16
struct ev_io listeners[MAX_LISTENERS];
size_t num_listeners;
float initial_stutter_interval;
float spam_stutter_interval;
struct {
char *banner;
char *helo;
char *mail;
char *rcpt;
char *data;
char *rset;
char *quit;
char *tempfail;
} resp;
const char *tagsep;
char hostname[256];
struct domain *domains;
size_t ndomains;
int loglevel;
float idle_timeout;
struct passwd *pw;
int allow_mail_from_my_domains:1;
int foreground:1;
struct {
const char *zone;
int fd[2];
pid_t pid;
struct ev_io w;
TAILQ_HEAD(, conn) queue;
} dnsbl;
} app;
static void
fatal(const char *fmt, ...)
{
va_list ap;
fprintf(stderr, "mxtarpit: ");
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
exit(1);
}
static void
logmsg(int prio, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (app.foreground) {
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
if (prio <= LOG_INFO) {
va_end(ap);
va_start(ap, fmt);
vsyslog(prio, fmt, ap);
}
} else if (app.loglevel >= prio) {
vsyslog(prio, fmt, ap);
}
va_end(ap);
}
#define debug(fmt, ...) logmsg(LOG_DEBUG, (fmt), ##__VA_ARGS__)
#define info(fmt, ...) logmsg(LOG_INFO, (fmt), ##__VA_ARGS__)
#define warn(fmt, ...) logmsg(LOG_WARNING, (fmt), ##__VA_ARGS__)
static void
fd_nonblock(int fd)
{
int flags;
flags = fcntl(fd, F_GETFL);
if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
warn("fcntl(O_NONBLOCK): %s", strerror(errno));
}
}
static char *
mklower(char *str)
{
int i;
for (i = 0; str && str[i]; i++) {
str[i] = tolower(str[i]);
}
return str;
}
static int
cmp_domain(const void *a, const void *b)
{
const struct domain *da = a;
const struct domain *db = b;
return strcmp(da->name, db->name);
}
static int
cmp_user(const void *a, const void *b)
{
const char * const *ua = a;
const char * const *ub = b;
return strcmp(*ua, *ub);
}
static struct domain *
find_domain(const char *domainname)
{
struct domain find;
find.name = (char *)domainname;
return bsearch(&find, app.domains, app.ndomains,
sizeof(*app.domains), cmp_domain);
}
static int
is_valid_user(struct domain *d, const char *user)
{
if (d->accept_any_user) {
return 1;
}
return bsearch(&user, d->users, d->nusers,
sizeof(*d->users), cmp_user) != NULL;
}
static void
add_address(char *domainname, char *user)
{
struct domain *d;
int sort_domains = 0;
mklower(domainname);
mklower(user);
d = find_domain(domainname);
if (d == NULL) {
if ((app.ndomains+1) > SIZE_MAX / sizeof(*app.domains)) {
/* Overflow. */
fatal("Too many domains");
}
app.domains = realloc(app.domains,
(app.ndomains+1) *
sizeof(*app.domains));
if (app.domains == NULL) {
fatal("realloc: %s", strerror(errno));
}
d = &app.domains[app.ndomains++];
memset(d, 0, sizeof(*d));
d->name = strdup(domainname);
if (d->name == NULL) {
fatal("strdup: %s", strerror(errno));
}
sort_domains = 1;
}
if (user == NULL || *user == '\0') {
/* Accept any users in domain. */
d->accept_any_user = 1;
free(d->users);
d->users = NULL;
d->nusers = 0;
}
if (!d->accept_any_user) {
if ((d->nusers+1) > SIZE_MAX / sizeof(*d->users)) {
/* Overflow. */
fatal("Too many addresses in domain %s", d->name);
}
d->users = realloc(d->users, (d->nusers + 1) *
sizeof(*d->users));
if (d->users == NULL) {
fatal("realloc: %s", strerror(errno));
}
d->users[d->nusers] = strdup(user);
if (d->users[d->nusers] == NULL) {
fatal("strdup: %s", strerror(errno));
}
d->nusers++;
}
if (sort_domains) {
qsort(app.domains, app.ndomains,
sizeof(*app.domains), cmp_domain);
}
}
static int
load_addresses(const char *addrfile, char *errbuf, size_t errlen)
{
char buf[1024];
FILE *fp;
int ret = 0;
size_t i;
fp = fopen(addrfile, "r");
if (fp == NULL) {
snprintf(errbuf, errlen, "%s", strerror(errno));
return -1;
}
while (fgets(buf, sizeof(buf), fp)) {
size_t n;
char *p = buf;
char *user;
if (buf[strlen(buf) - 1] != '\n') {
snprintf(errbuf, errlen, "Line too long");
ret = -1;
break;
}
p += strspn(buf, " \t\n");
if (*p == '#' || *p == '\0') {
continue;
}
n = strcspn(p, " \t\n");
p[n] = '\0';
user = strsep(&p, "@");
if (!p) {
snprintf(errbuf, errlen, "Invalid address: %s", user);
ret = -1;
break;
}
add_address(p, user);
}
if (ferror(fp)) {
snprintf(errbuf, errlen, "%s", strerror(errno));
ret = -1;
}
fclose(fp);
for (i = 0; i < app.ndomains; i++) {
struct domain *d = &app.domains[i];
qsort(d->users, d->nusers, sizeof(*d->users), cmp_user);
debug("got %zu addresses in domain %s", d->nusers, d->name);
}
return ret;
}
static int
is_helo_fqdn(struct conn *conn, char *args)
{
char *p;
size_t len;
int nlabels;
int digits_only;
len = strcspn(args, " ");
if (len == 0) {
/* Missing hostname. */
debug("%d: missing hostname", conn->fd);
return 0;
}
args[len] = '\0';
/* We're deliberately not parsing address literals. No proper mail
* server should use an address literal. */
mklower(args);
debug("%d: validating FQDN [%s]", conn->fd, args);
for (p = args, len = 0, nlabels = 1, digits_only = 1; *p; p++) {
if (*p == '.') {
if (len < 1 || len > 63) {
debug("%d: label length is %zu", conn->fd, len);
return 0;
}
if (p[1] != '\0') {
/* Don't count the trailing dot. */
nlabels++;
}
} else {
int c = *p;
int letter = (c >= 'a' && c <= 'z');
int digit = (c >= '0' && c <= '9');
if (letter || digit ||
(c == '-' && len > 0 &&
p[1] != '\0' && p[1] != '.')) {
if (!digit) {
digits_only = 0;
}
len++;
} else {
return 0;
}
}
}
if (digits_only) {
debug("%d: tld is digits only", conn->fd);
return 0;
}
return nlabels > 1;
}
static void
conn_is_spam(struct conn *conn)
{
conn->stutter.repeat = app.spam_stutter_interval;
conn->is_spam = 1;
}
static void
check_helo_fqdn(struct conn *conn, char *args)
{
if (args == NULL || !is_helo_fqdn(conn, args)) {
debug("%d: NOT a valid FQDN in HELO/EHLO", conn->fd);
conn_is_spam(conn);
}
snprintf(conn->helo, sizeof(conn->helo), "%s", args ? args : "<empty>");
}
static void
check_address(struct conn *conn, char *addr, char *prefix, int reverse_path,
char *savebuf, size_t savelen)
{
struct domain *d;
char *user;
size_t n;
snprintf(savebuf, savelen, "(invalid)");
mklower(addr);
/* Check prefix (to: or from:). */
while (*prefix) {
if (addr == NULL || *addr++ != *prefix++) {
goto bad_syntax;
}
}
/* Extract <address> part. */
addr += strspn(addr, " ");
if (*addr++ != '<') {
goto bad_syntax;
}
n = strcspn(addr, ">");
if (addr[n] != '>') {
goto bad_syntax;
}
addr[n] = '\0';
snprintf(savebuf, savelen, "%s", addr ? addr : "");
/* Empty Reverse-Path <> is ok. */
if (reverse_path && addr[0] == '\0') {
return;
}
/* Split user part and domain name. */
user = strsep(&addr, "@");
if (addr == NULL) {
goto bad_syntax;
}
/* Skip address checks if not configured. */
if (app.ndomains == 0) {
return;
}
d = find_domain(addr);
if (!d) {
if (reverse_path) {
/* Don't try to validate external addresses. */
return;
}
debug("%d: Invalid domain name [%s]", conn->fd, addr);
conn_is_spam(conn);
return;
} else if (reverse_path && !app.allow_mail_from_my_domains) {
/* No legitimate mail from our domains should ever be sent from
* the real MXs. */
debug("%d: Fake sender from our domain [%s]", conn->fd, addr);
conn_is_spam(conn);
return;
}
/* Ignore trailing tag in user part (user+tag@domain). */
user[strcspn(user, app.tagsep)] = '\0';
if (!is_valid_user(d, user)) {
debug("%d: Invalid recipient [%s@%s]",
conn->fd, user, d->name);
conn_is_spam(conn);
return;
}
return;
bad_syntax:
debug("%d: Bad address syntax", conn->fd);
conn_is_spam(conn);
}
static void
check_sender(struct conn *conn, char *args)
{
return check_address(conn, args, "from:", 1,
conn->from, sizeof(conn->from));
}
static void
check_recipient(struct conn *conn, char *args)
{
return check_address(conn, args, "to:", 0,
conn->rcpt, sizeof(conn->rcpt));
}
static int
conn_vput(struct conn *conn, const char *fmt, va_list ap)
{
struct mbuf *mbuf;
size_t left;
int res;
mbuf = &conn->outbuf;
left = sizeof(mbuf->data) - mbuf->len;
res = vsnprintf(mbuf->data + mbuf->len, left, fmt, ap);
if (res < 0) {
/* Output or encoding error? */
conn->state = smtp_close;
return -1;
} else if ((size_t)res >= left) {
/* Output truncated. */
debug("%d: output truncated", conn->fd);
conn->state = smtp_close;
return -1;
} else {
mbuf->len += res;
return res;
}
}
static void
conn_puts(struct conn *conn, const char *fmt, ...)
{
va_list ap;
int res;
va_start(ap, fmt);
res = conn_vput(conn, fmt, ap);
va_end(ap);
if (res == -1) {
return;
}
debug("%d: -> [%.*s]", conn->fd,
res, conn->outbuf.data + conn->outbuf.len - res);
va_start(ap, fmt);
res = conn_vput(conn, "\r\n", ap);
va_end(ap);
if (res == -1) {
return;
}
if (conn->stutter.repeat > 0) {
debug("%d: stuttering with interval %.2fs",
conn->fd, conn->stutter.repeat);
ev_timer_start(app.loop, &conn->stutter);
} else {
ev_io_start(app.loop, &conn->write_watcher);
}
}
static char *
conn_readline(struct conn *conn, size_t *lenp)
{
char *p = conn->inbuf.data;
size_t i;
for (i = 0; i < conn->inbuf.len; i++) {
if (p[i] == '\r' && i + 1 < conn->inbuf.len && p[i+1] == '\n') {
p[i] = '\0';
*lenp = i + 2;
return p + strspn(p, " ");
}
}
return NULL;
}
static void
conn_close(struct conn *conn)
{
int minutes, seconds;
seconds = (int)(ev_now(app.loop) - conn->connected_at);
minutes = seconds / 60;
seconds -= minutes * 60;
info("%d: %c %s (%s) duration %dm:%ds,"
" mail from: <%s> rcpt to: <%s>",
conn->fd,
conn->is_spam ? 'S' : (conn->rcpt[0] == '\0' ? '?' : 'H'),
conn->addr, conn->helo,
minutes, seconds,
conn->from, conn->rcpt);
close(conn->fd);
conn->fd = -1;
ev_io_stop(app.loop, &conn->read_watcher);
ev_io_stop(app.loop, &conn->write_watcher);
ev_timer_stop(app.loop, &conn->stutter);
ev_timer_stop(app.loop, &conn->dnsbl_timer);
ev_timer_stop(app.loop, &conn->idle_timer);
if (!conn->dnsbl_pending) {
free(conn);
}
}
static void
conn_auth_done(struct conn *conn)
{
info("%d: S %s (%s) authenticated as <%s> with password <%s>",
conn->fd, conn->addr, conn->helo, conn->auth, conn->pass);
conn_puts(conn, "235 Authentication success simulated");
conn->state = smtp_helo;
}
static void
conn_auth_plain(struct conn *conn, const char *data)
{
unsigned char plain[128];
int len;
debug("auth plain [%s]", data);
memset(plain, 0, sizeof(plain));
len = b64_pton(data, plain, sizeof(plain) - 1);
if (len > 0) {
char *auth = (char *)plain;
char *pass;
char *nil;
snprintf((char *)conn->auth, sizeof(conn->auth), "%s", auth);
nil = memchr(auth, '\0', len);
if (nil) {
if ((nil - auth) < len) {
pass = nil + 1;
snprintf((char *)conn->pass,
sizeof(conn->pass), "%s", pass);
}
}
}
conn_auth_done(conn);
}
static void
conn_auth(struct conn *conn, char *args)
{
char *method;
/* No legitimate mail server should ever try AUTH. */
conn_is_spam(conn);
method = mklower(strsep(&args, " "));
if (method == NULL) {
conn_puts(conn, "503 Missing authentication mechanism");
} else if (strcmp(method, "login") == 0) {
conn_puts(conn, "334 VXNlcm5hbWU6"); /* Username */
conn->state = smtp_auth_login_username;
} else if (strcmp(method, "plain") == 0) {
if (args) {
conn_auth_plain(conn, args);
} else {
conn_puts(conn, "334 Please continue authenticating");
conn->state = smtp_auth_plain;
}
} else {
conn_puts(conn, "503 Unsupported authentication mechanism");
}
}
static void
conn_process_command(struct conn *conn, char *line)
{
char *cmd, *args = NULL;
cmd = strsep(&line, " ");
if (line) {
line += strspn(line, " ");
if (*line) {
args = line;
}
}
mklower(cmd);
debug("%d: got cmd [%s] args [%s]", conn->fd, cmd, args ? args : "");
if (strcmp(cmd, "helo") == 0) {
check_helo_fqdn(conn, args);
conn_puts(conn, "250 %s %s", app.hostname, app.resp.helo);
} else if (strcmp(cmd, "ehlo") == 0) {
check_helo_fqdn(conn, args);
conn_puts(conn, "250-%s %s", app.hostname, app.resp.helo);
conn_puts(conn, "250-8BITMIME");
conn_puts(conn, "250 AUTH LOGIN PLAIN");
} else if (strcmp(cmd, "auth") == 0) {
conn_auth(conn, args);
} else if (strcmp(cmd, "mail") == 0) {
check_sender(conn, args);
conn_puts(conn, "250 %s", app.resp.mail);
} else if (strcmp(cmd, "rcpt") == 0) {
check_recipient(conn, args);
conn_puts(conn, "250 %s", app.resp.rcpt);
} else if (strcmp(cmd, "data") == 0) {
conn->got_data = 1;
if (conn->from[0] == '\0' || conn->rcpt[0] == '\0') {
/* No sender or recipient. */
conn_is_spam(conn);
}
if (0 && conn->is_spam) {
conn_puts(conn, "354 %s", app.resp.data);
conn->state = smtp_data_response;
} else {
if (!conn->is_spam) {
/* If we get to DATA without any RFC violation
* or other weirdness, disable stuttering, and
* close the connection right after the
* response is flushed. */
conn->stutter.repeat = 0;
conn->state = smtp_close;
}
conn_puts(conn, "451 %s", app.resp.tempfail);
}
} else if (strcmp(cmd, "rset") == 0) {
conn_puts(conn, "250 %s", app.resp.rset);
} else if (strcmp(cmd, "noop") == 0) {
conn_puts(conn, "250 OK");
} else if (strcmp(cmd, "quit") == 0) {
if (!conn->got_data) {
conn_is_spam(conn);
}
conn_puts(conn, "221 %s", app.resp.quit);
conn->state = smtp_close;
} else if (cmd[0] == '\0') {
conn_puts(conn, "500 Bad syntax");
} else {
conn_puts(conn, "502 Command not recognized");
}
}
static int
conn_process_line(struct conn *conn)
{
size_t len;
char *line;
int res;
line = conn_readline(conn, &len);
if (line == NULL) {
/* Wait for more data. */
if (conn->inbuf.len == sizeof(conn->inbuf.data)) {
/* Line too long. */
debug("%d: Line too long", conn);
return -1;
} else {
return 1;
}
}
debug("%d: <- [%s]", conn->fd, line);
switch (conn->state) {
case smtp_helo:
conn_process_command(conn, line);
break;
case smtp_data:
if (strcmp(line, ".") == 0) {
conn_puts(conn, "451 %s", app.resp.tempfail);
conn->state = smtp_helo;
}
break;
case smtp_auth_login_username:
memset(conn->auth, 0, sizeof(conn->auth));
res = b64_pton(line, conn->auth, sizeof(conn->auth) - 1);
if (res == -1) {
debug("%d: invalid base64 encoded username", conn->fd);
conn->auth[0] = '\0';
}
conn_puts(conn, "334 UGFzc3dvcmQ6"); /* Password: */
conn->state = smtp_auth_login_password;
break;
case smtp_auth_login_password:
memset(conn->pass, 0, sizeof(conn->pass));
res = b64_pton(line, conn->pass, sizeof(conn->pass) - 1);
if (res == -1) {
debug("%d: invalid base64 encoded password", conn->fd);
conn->pass[0] = '\0';
}
conn_auth_done(conn);
break;
case smtp_auth_plain:
conn_auth_plain(conn, line);
break;
case smtp_sending_banner:
case smtp_data_response:
case smtp_close:
fatal("unexpected state %d", conn->state);
break;
}
/* Consume the processed line. */
memmove(conn->inbuf.data, conn->inbuf.data + len, conn->inbuf.len - len);
conn->inbuf.len -= len;
return 0;
}
static void
conn_process(struct conn *conn)
{
for (;;) {
switch (conn_process_line(conn)) {
case -1:
conn_close(conn);
return;
case 1:
/* Incomplete line received. */
ev_io_start(app.loop, &conn->read_watcher);
return;
case 0:
/* One line received and processed. */
ev_timer_stop(app.loop, &conn->idle_timer);
break;
}
if (conn->state == smtp_data) {
/* Continue processing all received data. */
ev_timer_again(app.loop, &conn->idle_timer);
} else {
/* Do not read more until response flushed. */
ev_io_stop(app.loop, &conn->read_watcher);
break;
}
}
}
static void
conn_readable(struct ev_loop *loop, struct ev_io *w, int revents)
{
struct conn *conn = w->data;
ssize_t res;
res = read(w->fd, conn->inbuf.data + conn->inbuf.len,
sizeof(conn->inbuf.data) - conn->inbuf.len);
if (res < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return;
}
debug("%d: read: %s", conn->fd, strerror(errno));
return;
} else if (res == 0) {
conn_close(conn);
return;
} else {
conn->inbuf.len += res;
if (conn->state == smtp_sending_banner) {
debug("%d: received data before banner sent", w->fd);
conn_is_spam(conn);
return;
}
}
conn_process(conn);
}
static void
conn_write(struct conn *conn, size_t maxbytes)
{
size_t nbytes;
ssize_t res;
nbytes = conn->outbuf.len - conn->outbuf.ofs;
if (nbytes > maxbytes) {
nbytes = maxbytes;
}
res = write(conn->fd, conn->outbuf.data + conn->outbuf.ofs, nbytes);
if (res < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return;
}
if (errno != EPIPE) {
warn("%d: write: %s", conn->fd, strerror(errno));
}
conn_close(conn);
return;
} else {
conn->outbuf.ofs += res;
}
if (conn->outbuf.len == conn->outbuf.ofs) {
int s = (int)(ev_now(app.loop) - conn->connected_at);
debug("%d: %zu byte in outbuf flushed at %ds",
conn->fd, conn->outbuf.len, s);
ev_timer_stop(app.loop, &conn->stutter);
ev_io_stop(app.loop, &conn->write_watcher);
ev_timer_again(app.loop, &conn->idle_timer);
if (conn->state == smtp_close) {
conn_close(conn);
return;
}
if (conn->state == smtp_sending_banner) {
conn->state = smtp_helo;
} else if (conn->state == smtp_data_response) {
conn->state = smtp_data;
}
conn->outbuf.ofs = 0;
conn->outbuf.len = 0;
conn_process(conn);
}
}
static void
conn_stutter(struct ev_loop *loop, struct ev_timer *w, int revents)
{
struct conn *conn = w->data;
size_t maxbytes = 1;
if (w->repeat == 0) {
maxbytes = SIZE_MAX;
}
conn_write(conn, maxbytes);
}
static void
conn_writable(struct ev_loop *loop, struct ev_io *w, int revents)
{
struct conn *conn = w->data;
conn_write(conn, sizeof(conn->outbuf.data));
}
static void
conn_idle(struct ev_loop *loop, struct ev_timer *w, int revents)
{
struct conn *conn = w->data;
debug("%d: idle timeout", conn->fd);
conn_close(conn);
}
static void
dnsbl_lookup(struct ev_loop *loop, struct ev_timer *w, int revents)
{
struct conn *conn = w->data;
ssize_t res;
if (conn->is_spam) {
/* Skip DNSBL if connection already determined to be spam. */
return;
}
res = write(app.dnsbl.fd[0], &conn->ipv4, sizeof(conn->ipv4));
if (res < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
/* Try again later? */
return;
}
fatal("Failed to dispatch DNSBL query: %s", strerror(errno));
} else if ((size_t)res != sizeof(conn->ipv4)) {
fatal("Failed to dispatch DNSBL query: short write");
} else {
/* Add connection to end of result queue. */
TAILQ_INSERT_TAIL(&app.dnsbl.queue, conn, dnsbl_queue);
/* Make sure queue entry stays valid until result arrives. */
conn->dnsbl_pending = 1;
}
}
static void
conn_accept(struct ev_loop *loop, struct ev_io *w, int revents)
{
struct conn *conn;
struct sockaddr_storage ss;
struct sockaddr *sa = (struct sockaddr *)&ss;
socklen_t salen = sizeof(ss);
int afd;
afd = accept(w->fd, sa, &salen);
if (afd == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return;
} else if (errno == EMFILE || errno == ENFILE) {
/* See comment in libev manual. */
}
debug("%d: accept: %s", w->fd, strerror(errno));
return;
}
conn = calloc(1, sizeof(*conn));
if (conn == NULL) {
debug("malloc: %s", strerror(errno));
close(afd);
return;
}
getnameinfo(sa, salen, conn->addr, sizeof(conn->addr),
NULL, 0, NI_NUMERICHOST);
{
time_t now;
struct tm *tm;
now = ev_now(loop);
tm = localtime(&now);
debug("%d: got connection from %s at %s",
afd, conn->addr, asctime(tm));
}
conn->is_spam = 0;
conn->fd = afd;