-
Notifications
You must be signed in to change notification settings - Fork 176
/
smtp_in.c
5835 lines (4813 loc) · 175 KB
/
smtp_in.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
/*************************************************
* Exim - an Internet mail transport agent *
*************************************************/
/* Copyright (c) The Exim Maintainers 2020 - 2024 */
/* Copyright (c) University of Cambridge 1995 - 2018 */
/* See the file NOTICE for conditions of use and distribution. */
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Functions for handling an incoming SMTP call. */
#include "exim.h"
#include <assert.h>
/* Initialize for TCP wrappers if so configured. It appears that the macro
HAVE_IPV6 is used in some versions of the tcpd.h header, so we unset it before
including that header, and restore its value afterwards. */
#ifdef USE_TCP_WRAPPERS
#if HAVE_IPV6
#define EXIM_HAVE_IPV6
#endif
#undef HAVE_IPV6
#include <tcpd.h>
#undef HAVE_IPV6
#ifdef EXIM_HAVE_IPV6
#define HAVE_IPV6 TRUE
#endif
int allow_severity = LOG_INFO;
int deny_severity = LOG_NOTICE;
uschar *tcp_wrappers_name;
#endif
/* Size of buffer for reading SMTP commands. We used to use 512, as defined
by RFC 821. However, RFC 1869 specifies that this must be increased for SMTP
commands that accept arguments, and this in particular applies to AUTH, where
the data can be quite long. More recently this value was 2048 in Exim;
however, RFC 4954 (circa 2007) recommends 12288 bytes to handle AUTH. Clients
such as Thunderbird will send an AUTH with an initial-response for GSSAPI.
The maximum size of a Kerberos ticket under Windows 2003 is 12000 bytes, and
we need room to handle large base64-encoded AUTHs for GSSAPI.
*/
#define SMTP_CMD_BUFFER_SIZE 16384
/* Size of buffer for reading SMTP incoming packets */
#define IN_BUFFER_SIZE 8192
/* Structure for SMTP command list */
typedef struct {
const char *name;
int len;
short int cmd;
short int has_arg;
short int is_mail_cmd;
} smtp_cmd_list;
/* Codes for identifying commands. We order them so that those that come first
are those for which synchronization is always required. Checking this can help
block some spam. */
enum {
/* These commands are required to be synchronized, i.e. to be the last in a
block of commands when pipelining. */
HELO_CMD, EHLO_CMD, DATA_CMD, /* These are listed in the pipelining */
VRFY_CMD, EXPN_CMD, NOOP_CMD, /* RFC as requiring synchronization */
ETRN_CMD, /* This by analogy with TURN from the RFC */
STARTTLS_CMD, /* Required by the STARTTLS RFC */
TLS_AUTH_CMD, /* auto-command at start of SSL */
#ifdef EXPERIMENTAL_XCLIENT
XCLIENT_CMD, /* per xlexkiro implementation */
#endif
/* This is a dummy to identify the non-sync commands when pipelining */
NON_SYNC_CMD_PIPELINING,
/* These commands need not be synchronized when pipelining */
MAIL_CMD, RCPT_CMD, RSET_CMD,
#ifndef DISABLE_WELLKNOWN
WELLKNOWN_CMD,
#endif
/* This is a dummy to identify the non-sync commands when not pipelining */
NON_SYNC_CMD_NON_PIPELINING,
/* RFC3030 section 2: "After all MAIL and RCPT responses are collected and
processed the message is sent using a series of BDAT commands"
implies that BDAT should be synchronized. However, we see Google, at least,
sending MAIL,RCPT,BDAT-LAST in a single packet, clearly not waiting for
processing of the RCPT response(s). We shall do the same, and not require
synch for BDAT. Worse, as the chunk may (very likely will) follow the
command-header in the same packet we cannot do the usual "is there any
follow-on data after the command line" even for non-pipeline mode.
So we'll need an explicit check after reading the expected chunk amount
when non-pipe, before sending the ACK. */
BDAT_CMD,
/* I have been unable to find a statement about the use of pipelining
with AUTH, so to be on the safe side it is here, though I kind of feel
it should be up there with the synchronized commands. */
AUTH_CMD,
/* I'm not sure about these, but I don't think they matter. */
QUIT_CMD, HELP_CMD,
#ifdef SUPPORT_PROXY
PROXY_FAIL_IGNORE_CMD,
#endif
/* These are specials that don't correspond to actual commands */
EOF_CMD, OTHER_CMD, BADARG_CMD, BADCHAR_CMD, BADSYN_CMD,
TOO_MANY_NONMAIL_CMD
};
/* This is a convenience macro for adding the identity of an SMTP command
to the circular buffer that holds a list of the last n received. */
#define HAD(n) \
smtp_connection_had[smtp_ch_index++] = n; \
if (smtp_ch_index >= SMTP_HBUFF_SIZE) smtp_ch_index = 0
/*************************************************
* Local static variables *
*************************************************/
static struct {
BOOL auth_advertised :1;
#ifndef DISABLE_TLS
BOOL tls_advertised :1;
#endif
BOOL dsn_advertised :1;
BOOL esmtp :1;
BOOL helo_verify_required :1;
BOOL helo_verify :1;
BOOL helo_seen :1;
BOOL helo_accept_junk :1;
#ifndef DISABLE_PIPE_CONNECT
BOOL pipe_connect_acceptable :1;
#endif
BOOL rcpt_smtp_response_same :1;
BOOL rcpt_in_progress :1;
BOOL smtp_exit_function_called :1;
#ifdef SUPPORT_I18N
BOOL smtputf8_advertised :1;
#endif
} fl = {
.helo_verify_required = FALSE,
.helo_verify = FALSE,
.smtp_exit_function_called = FALSE,
};
static auth_instance *authenticated_by;
static int count_nonmail;
static int nonmail_command_count;
static int synprot_error_count;
static int unknown_command_count;
static int sync_cmd_limit;
static int smtp_write_error = 0;
static uschar *rcpt_smtp_response;
static uschar *smtp_data_buffer;
static uschar *smtp_cmd_data;
/* We need to know the position of RSET, HELO, EHLO, AUTH, and STARTTLS. Their
final fields of all except AUTH are forced TRUE at the start of a new message
setup, to allow one of each between messages that is not counted as a nonmail
command. (In fact, only one of HELO/EHLO is not counted.) Also, we have to
allow a new EHLO after starting up TLS.
AUTH is "falsely" labelled as a mail command initially, so that it doesn't get
counted. However, the flag is changed when AUTH is received, so that multiple
failing AUTHs will eventually hit the limit. After a successful AUTH, another
AUTH is already forbidden. After a TLS session is started, AUTH's flag is again
forced TRUE, to allow for the re-authentication that can happen at that point.
QUIT is also "falsely" labelled as a mail command so that it doesn't up the
count of non-mail commands and possibly provoke an error.
tls_auth is a pseudo-command, never expected in input. It is activated
on TLS startup and looks for a tls authenticator. */
enum {
CL_RSET = 0,
CL_HELO,
CL_EHLO,
CL_AUTH,
#ifndef DISABLE_TLS
CL_STLS,
CL_TLAU,
#endif
#ifdef EXPERIMENTAL_XCLIENT
CL_XCLI,
#endif
};
static smtp_cmd_list cmd_list[] = {
/* name len cmd has_arg is_mail_cmd */
[CL_RSET] = { "rset", sizeof("rset")-1, RSET_CMD, FALSE, FALSE }, /* First */
[CL_HELO] = { "helo", sizeof("helo")-1, HELO_CMD, TRUE, FALSE },
[CL_EHLO] = { "ehlo", sizeof("ehlo")-1, EHLO_CMD, TRUE, FALSE },
[CL_AUTH] = { "auth", sizeof("auth")-1, AUTH_CMD, TRUE, TRUE },
#ifndef DISABLE_TLS
[CL_STLS] = { "starttls", sizeof("starttls")-1, STARTTLS_CMD, FALSE, FALSE },
[CL_TLAU] = { "tls_auth", 0, TLS_AUTH_CMD, FALSE, FALSE },
#endif
#ifdef EXPERIMENTAL_XCLIENT
[CL_XCLI] = { "xclient", sizeof("xclient")-1, XCLIENT_CMD, TRUE, FALSE },
#endif
{ "mail from:", sizeof("mail from:")-1, MAIL_CMD, TRUE, TRUE },
{ "rcpt to:", sizeof("rcpt to:")-1, RCPT_CMD, TRUE, TRUE },
{ "data", sizeof("data")-1, DATA_CMD, FALSE, TRUE },
{ "bdat", sizeof("bdat")-1, BDAT_CMD, TRUE, TRUE },
{ "quit", sizeof("quit")-1, QUIT_CMD, FALSE, TRUE },
{ "noop", sizeof("noop")-1, NOOP_CMD, TRUE, FALSE },
{ "etrn", sizeof("etrn")-1, ETRN_CMD, TRUE, FALSE },
{ "vrfy", sizeof("vrfy")-1, VRFY_CMD, TRUE, FALSE },
{ "expn", sizeof("expn")-1, EXPN_CMD, TRUE, FALSE },
{ "help", sizeof("help")-1, HELP_CMD, TRUE, FALSE },
#ifndef DISABLE_WELLKNOWN
{ "wellknown", sizeof("wellknown")-1, WELLKNOWN_CMD, TRUE, FALSE },
#endif
};
/* This list of names is used for performing the smtp_no_mail logging action. */
uschar * smtp_names[] =
{
[SCH_NONE] = US"NONE",
[SCH_AUTH] = US"AUTH",
[SCH_DATA] = US"DATA",
[SCH_BDAT] = US"BDAT",
[SCH_EHLO] = US"EHLO",
[SCH_ETRN] = US"ETRN",
[SCH_EXPN] = US"EXPN",
[SCH_HELO] = US"HELO",
[SCH_HELP] = US"HELP",
[SCH_MAIL] = US"MAIL",
[SCH_NOOP] = US"NOOP",
[SCH_QUIT] = US"QUIT",
[SCH_RCPT] = US"RCPT",
[SCH_RSET] = US"RSET",
[SCH_STARTTLS] = US"STARTTLS",
[SCH_VRFY] = US"VRFY",
#ifndef DISABLE_WELLKNOWN
[SCH_WELLKNOWN] = US"WELLKNOWN",
#endif
#ifdef EXPERIMENTAL_XCLIENT
[SCH_XCLIENT] = US"XCLIENT",
#endif
};
static uschar *protocols_local[] = {
US"local-smtp", /* HELO */
US"local-smtps", /* The rare case EHLO->STARTTLS->HELO */
US"local-esmtp", /* EHLO */
US"local-esmtps", /* EHLO->STARTTLS->EHLO */
US"local-esmtpa", /* EHLO->AUTH */
US"local-esmtpsa" /* EHLO->STARTTLS->EHLO->AUTH */
};
static uschar *protocols[] = {
US"smtp", /* HELO */
US"smtps", /* The rare case EHLO->STARTTLS->HELO */
US"esmtp", /* EHLO */
US"esmtps", /* EHLO->STARTTLS->EHLO */
US"esmtpa", /* EHLO->AUTH */
US"esmtpsa" /* EHLO->STARTTLS->EHLO->AUTH */
};
#define pnormal 0
#define pextend 2
#define pcrpted 1 /* added to pextend or pnormal */
#define pauthed 2 /* added to pextend */
/* Sanity check and validate optional args to MAIL FROM: envelope */
enum {
ENV_MAIL_OPT_NULL,
ENV_MAIL_OPT_SIZE, ENV_MAIL_OPT_BODY, ENV_MAIL_OPT_AUTH,
#ifndef DISABLE_PRDR
ENV_MAIL_OPT_PRDR,
#endif
ENV_MAIL_OPT_RET, ENV_MAIL_OPT_ENVID,
#ifdef SUPPORT_I18N
ENV_MAIL_OPT_UTF8,
#endif
};
typedef struct {
uschar * name; /* option requested during MAIL cmd */
int value; /* enum type */
BOOL need_value; /* TRUE requires value (name=value pair format)
FALSE is a singleton */
} env_mail_type_t;
static env_mail_type_t env_mail_type_list[] = {
{ US"SIZE", ENV_MAIL_OPT_SIZE, TRUE },
{ US"BODY", ENV_MAIL_OPT_BODY, TRUE },
{ US"AUTH", ENV_MAIL_OPT_AUTH, TRUE },
#ifndef DISABLE_PRDR
{ US"PRDR", ENV_MAIL_OPT_PRDR, FALSE },
#endif
{ US"RET", ENV_MAIL_OPT_RET, TRUE },
{ US"ENVID", ENV_MAIL_OPT_ENVID, TRUE },
#ifdef SUPPORT_I18N
{ US"SMTPUTF8",ENV_MAIL_OPT_UTF8, FALSE }, /* rfc6531 */
#endif
/* keep this the last entry */
{ US"NULL", ENV_MAIL_OPT_NULL, FALSE },
};
/* When reading SMTP from a remote host, we have to use our own versions of the
C input-reading functions, in order to be able to flush the SMTP output only
when about to read more data from the socket. This is the only way to get
optimal performance when the client is using pipelining. Flushing for every
command causes a separate packet and reply packet each time; saving all the
responses up (when pipelining) combines them into one packet and one response.
For simplicity, these functions are used for *all* SMTP input, not only when
receiving over a socket. However, after setting up a secure socket (SSL), input
is read via the OpenSSL library, and another set of functions is used instead
(see tls.c).
These functions are set in the receive_getc etc. variables and called with the
same interface as the C functions. However, since there can only ever be
one incoming SMTP call, we just use a single buffer and flags. There is no need
to implement a complicated private FILE-like structure.*/
static uschar *smtp_inbuffer;
static uschar *smtp_inptr;
static uschar *smtp_inend;
static int smtp_had_eof;
static int smtp_had_error;
/* forward declarations */
static int smtp_read_command(BOOL check_sync, unsigned buffer_lim);
static int synprot_error(int type, int code, uschar *data, uschar *errmess);
static void smtp_quit_handler(uschar **, uschar **);
static void smtp_rset_handler(void);
/*************************************************
* Log incomplete transactions *
*************************************************/
/* This function is called after a transaction has been aborted by RSET, QUIT,
connection drops or other errors. It logs the envelope information received
so far in order to preserve address verification attempts.
Argument: string to indicate what aborted the transaction
Returns: nothing
*/
static void
incomplete_transaction_log(uschar * what)
{
if (!sender_address /* No transaction in progress */
|| !LOGGING(smtp_incomplete_transaction))
return;
/* Build list of recipients for logging */
if (recipients_count > 0)
{
raw_recipients = store_get(recipients_count * sizeof(uschar *), GET_UNTAINTED);
for (int i = 0; i < recipients_count; i++)
raw_recipients[i] = recipients_list[i].address;
raw_recipients_count = recipients_count;
}
log_write(L_smtp_incomplete_transaction, LOG_MAIN|LOG_SENDER|LOG_RECIPIENTS,
"%s incomplete transaction (%s)", host_and_ident(TRUE), what);
}
static void
log_close_event(const uschar * reason)
{
log_write(L_smtp_connection, LOG_MAIN, "%s D=%s closed %s",
smtp_get_connection_info(), string_timesince(&smtp_connection_start), reason);
}
void
smtp_command_timeout_exit(void)
{
log_write(L_lost_incoming_connection,
LOG_MAIN, "SMTP command timeout on%s connection from %s D=%s",
tls_in.active.sock >= 0 ? " TLS" : "", host_and_ident(FALSE),
string_timesince(&smtp_connection_start));
if (smtp_batched_input)
moan_smtp_batch(NULL, "421 SMTP command timeout"); /* Does not return */
smtp_notquit_exit(US"command-timeout", US"421",
US"%s: SMTP command timeout - closing connection",
smtp_active_hostname);
exim_exit(EXIT_FAILURE);
}
void
smtp_command_sigterm_exit(void)
{
log_close_event(US"after SIGTERM");
if (smtp_batched_input)
moan_smtp_batch(NULL, "421 SIGTERM received"); /* Does not return */
smtp_notquit_exit(US"signal-exit", US"421",
US"%s: Service not available - closing connection", smtp_active_hostname);
exim_exit(EXIT_FAILURE);
}
void
smtp_data_timeout_exit(void)
{
log_write(L_lost_incoming_connection, LOG_MAIN,
"SMTP data timeout (message abandoned) on connection from %s F=<%s> D=%s",
sender_fullhost ? sender_fullhost : US"local process", sender_address,
string_timesince(&smtp_connection_start));
receive_bomb_out(US"data-timeout", US"SMTP incoming data timeout");
/* Does not return */
}
void
smtp_data_sigint_exit(void)
{
log_close_event(had_data_sigint == SIGTERM ? US"SIGTERM":US"SIGINT");
receive_bomb_out(US"signal-exit",
US"Service not available - SIGTERM or SIGINT received");
/* Does not return */
}
/******************************************************************************/
/* SMTP input buffer handling. Most of these are similar to stdio routines. */
static void
smtp_buf_init(void)
{
/* Set up the buffer for inputting using direct read() calls, and arrange to
call the local functions instead of the standard C ones. Place a NUL at the
end of the buffer to safety-stop C-string reads from it. */
if (!(smtp_inbuffer = US malloc(IN_BUFFER_SIZE)))
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "malloc() failed for SMTP input buffer");
smtp_inbuffer[IN_BUFFER_SIZE-1] = '\0';
smtp_inptr = smtp_inend = smtp_inbuffer;
smtp_had_eof = smtp_had_error = 0;
}
/* Refill the buffer, and notify DKIM verification code.
Return false for error or EOF.
*/
static BOOL
smtp_refill(unsigned lim)
{
int rc, save_errno;
if (!smtp_out) return FALSE;
fflush(smtp_out);
if (smtp_receive_timeout > 0) ALARM(smtp_receive_timeout);
/* Limit amount read, so non-message data is not fed to DKIM.
Take care to not touch the safety NUL at the end of the buffer. */
rc = read(fileno(smtp_in), smtp_inbuffer, MIN(IN_BUFFER_SIZE-1, lim));
save_errno = errno;
if (smtp_receive_timeout > 0) ALARM_CLR(0);
if (rc <= 0)
{
/* Must put the error text in fixed store, because this might be during
header reading, where it releases unused store above the header. */
if (rc < 0)
{
if (had_command_timeout) /* set by signal handler */
smtp_command_timeout_exit(); /* does not return */
if (had_command_sigterm)
smtp_command_sigterm_exit();
if (had_data_timeout)
smtp_data_timeout_exit();
if (had_data_sigint)
smtp_data_sigint_exit();
smtp_had_error = save_errno;
smtp_read_error = string_copy_perm(
string_sprintf(" (error: %s)", strerror(save_errno)), FALSE);
}
else
smtp_had_eof = 1;
return FALSE;
}
#ifndef DISABLE_DKIM
dkim_exim_verify_feed(smtp_inbuffer, rc);
#endif
smtp_inend = smtp_inbuffer + rc;
smtp_inptr = smtp_inbuffer;
return TRUE;
}
/* Check if there is buffered data */
BOOL
smtp_hasc(void)
{
return smtp_inptr < smtp_inend;
}
/* SMTP version of getc()
This gets the next byte from the SMTP input buffer. If the buffer is empty,
it flushes the output, and refills the buffer, with a timeout. The signal
handler is set appropriately by the calling function. This function is not used
after a connection has negotiated itself into an TLS/SSL state.
Arguments: lim Maximum amount to read/buffer
Returns: the next character or EOF
*/
int
smtp_getc(unsigned lim)
{
if (!smtp_hasc() && !smtp_refill(lim)) return EOF;
return *smtp_inptr++;
}
/* Get many bytes, refilling buffer if needed */
uschar *
smtp_getbuf(unsigned * len)
{
unsigned size;
uschar * buf;
if (!smtp_hasc() && !smtp_refill(*len))
{ *len = 0; return NULL; }
if ((size = smtp_inend - smtp_inptr) > *len) size = *len;
buf = smtp_inptr;
smtp_inptr += size;
*len = size;
return buf;
}
/* Copy buffered data to the dkim feed.
Called, unless TLS, just before starting to read message headers. */
void
smtp_get_cache(unsigned lim)
{
#ifndef DISABLE_DKIM
int n = smtp_inend - smtp_inptr;
if (n > lim)
n = lim;
if (n > 0)
dkim_exim_verify_feed(smtp_inptr, n);
#endif
}
/* SMTP version of ungetc()
Puts a character back in the input buffer. Only ever called once.
Arguments:
ch the character
Returns: the character
*/
int
smtp_ungetc(int ch)
{
if (smtp_inptr <= smtp_inbuffer) /* NB: NOT smtp_hasc() ! */
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "buffer underflow in smtp_ungetc");
*--smtp_inptr = ch;
return ch;
}
/* SMTP version of feof()
Tests for a previous EOF
Arguments: none
Returns: non-zero if the eof flag is set
*/
int
smtp_feof(void)
{
return smtp_had_eof;
}
/* SMTP version of ferror()
Tests for a previous read error, and returns with errno
restored to what it was when the error was detected.
Arguments: none
Returns: non-zero if the error flag is set
*/
int
smtp_ferror(void)
{
errno = smtp_had_error;
return smtp_had_error;
}
/* Check if a getc will block or not */
static BOOL
smtp_could_getc(void)
{
int fd, rc;
fd_set fds;
struct timeval tzero = {.tv_sec = 0, .tv_usec = 0};
if (smtp_inptr < smtp_inend)
return TRUE;
fd = fileno(smtp_in);
FD_ZERO(&fds);
FD_SET(fd, &fds);
rc = select(fd + 1, (SELECT_ARG2_TYPE *)&fds, NULL, NULL, &tzero);
if (rc <= 0) return FALSE; /* Not ready to read */
rc = smtp_getc(GETC_BUFFER_UNLIMITED);
if (rc < 0) return FALSE; /* End of file or error */
smtp_ungetc(rc);
return TRUE;
}
/******************************************************************************/
/*************************************************
* Recheck synchronization *
*************************************************/
/* Synchronization checks can never be perfect because a packet may be on its
way but not arrived when the check is done. Normally, the checks happen when
commands are read: Exim ensures that there is no more input in the input buffer.
In normal cases, the response to the command will be fast, and there is no
further check.
However, for some commands an ACL is run, and that can include delays. In those
cases, it is useful to do another check on the input just before sending the
response. This also applies at the start of a connection. This function does
that check by means of the select() function, as long as the facility is not
disabled or inappropriate. A failure of select() is ignored.
When there is unwanted input, we read it so that it appears in the log of the
error.
Arguments: none
Returns: TRUE if all is well; FALSE if there is input pending
*/
static BOOL
wouldblock_reading(void)
{
#ifndef DISABLE_TLS
if (tls_in.active.sock >= 0)
return !tls_could_getc();
#endif
return !smtp_could_getc();
}
static BOOL
check_sync(void)
{
if (!smtp_enforce_sync || !sender_host_address || f.sender_host_notsocket)
return TRUE;
return wouldblock_reading();
}
/******************************************************************************/
/* Variants of the smtp_* input handling functions for use in CHUNKING mode */
/* Forward declarations */
static inline void bdat_push_receive_functions(void);
static inline void bdat_pop_receive_functions(void);
/* Get a byte from the smtp input, in CHUNKING mode. Handle ack of the
previous BDAT chunk and getting new ones when we run out. Uses the
underlying smtp_getc or tls_getc both for that and for getting the
(buffered) data byte. EOD signals (an expected) no further data.
ERR signals a protocol error, and EOF a closed input stream.
Called from read_bdat_smtp() in receive.c for the message body, but also
by the headers read loop in receive_msg(); manipulates chunking_state
to handle the BDAT command/response.
Placed here due to the correlation with the above smtp_getc(), which it wraps,
and also by the need to do smtp command/response handling.
Arguments: lim (ignored)
Returns: the next character or ERR, EOD or EOF
*/
int
bdat_getc(unsigned lim)
{
uschar * user_msg = NULL;
uschar * log_msg;
for(;;)
{
#ifndef DISABLE_DKIM
unsigned dkim_save;
#endif
if (chunking_data_left > 0)
return lwr_receive_getc(chunking_data_left--);
bdat_pop_receive_functions();
#ifndef DISABLE_DKIM
dkim_save = dkim_collect_input;
dkim_collect_input = 0;
#endif
/* Unless PIPELINING was offered, there should be no next command
until after we ack that chunk */
if (!f.smtp_in_pipelining_advertised && !check_sync())
{
unsigned n = smtp_inend - smtp_inptr;
if (n > 32) n = 32;
incomplete_transaction_log(US"sync failure");
log_write(0, LOG_MAIN|LOG_REJECT, "SMTP protocol synchronization error "
"(next input sent too soon: pipelining was not advertised): "
"rejected \"%s\" %s next input=\"%s\"%s",
smtp_cmd_buffer, host_and_ident(TRUE),
string_printing(string_copyn(smtp_inptr, n)),
smtp_inend - smtp_inptr > n ? "..." : "");
(void) synprot_error(L_smtp_protocol_error, 554, NULL,
US"SMTP synchronization error");
goto repeat_until_rset;
}
/* If not the last, ack the received chunk. The last response is delayed
until after the data ACL decides on it */
if (chunking_state == CHUNKING_LAST)
{
#ifndef DISABLE_DKIM
dkim_collect_input = dkim_save;
dkim_exim_verify_feed(NULL, 0); /* notify EOD */
dkim_collect_input = 0;
#endif
return EOD;
}
smtp_printf("250 %u byte chunk received\r\n", SP_NO_MORE, chunking_datasize);
chunking_state = CHUNKING_OFFERED;
DEBUG(D_receive) debug_printf("chunking state %d\n", (int)chunking_state);
/* Expect another BDAT cmd from input. RFC 3030 says nothing about
QUIT, RSET or NOOP but handling them seems obvious */
next_cmd:
switch(smtp_read_command(TRUE, 1))
{
default:
(void) synprot_error(L_smtp_protocol_error, 503, NULL,
US"only BDAT permissible after non-LAST BDAT");
repeat_until_rset:
switch(smtp_read_command(TRUE, 1))
{
case QUIT_CMD: smtp_quit_handler(&user_msg, &log_msg); /*FALLTHROUGH */
case EOF_CMD: return EOF;
case RSET_CMD: smtp_rset_handler(); return ERR;
default: if (synprot_error(L_smtp_protocol_error, 503, NULL,
US"only RSET accepted now") > 0)
return EOF;
goto repeat_until_rset;
}
case QUIT_CMD:
smtp_quit_handler(&user_msg, &log_msg);
/*FALLTHROUGH*/
case EOF_CMD:
return EOF;
case RSET_CMD:
smtp_rset_handler();
return ERR;
case NOOP_CMD:
HAD(SCH_NOOP);
smtp_printf("250 OK\r\n", SP_NO_MORE);
goto next_cmd;
case BDAT_CMD:
{
int n;
if (sscanf(CS smtp_cmd_data, "%u %n", &chunking_datasize, &n) < 1)
{
(void) synprot_error(L_smtp_protocol_error, 501, NULL,
US"missing size for BDAT command");
return ERR;
}
chunking_state = strcmpic(smtp_cmd_data+n, US"LAST") == 0
? CHUNKING_LAST : CHUNKING_ACTIVE;
chunking_data_left = chunking_datasize;
DEBUG(D_receive) debug_printf("chunking state %d, %d bytes\n",
(int)chunking_state, chunking_data_left);
if (chunking_datasize == 0)
if (chunking_state == CHUNKING_LAST)
return EOD;
else
{
(void) synprot_error(L_smtp_protocol_error, 504, NULL,
US"zero size for BDAT command");
goto repeat_until_rset;
}
bdat_push_receive_functions();
#ifndef DISABLE_DKIM
dkim_collect_input = dkim_save;
#endif
break; /* to top of main loop */
}
}
}
}
BOOL
bdat_hasc(void)
{
if (chunking_data_left > 0)
return lwr_receive_hasc();
return TRUE;
}
uschar *
bdat_getbuf(unsigned * len)
{
uschar * buf;
if (chunking_data_left <= 0)
{ *len = 0; return NULL; }
if (*len > chunking_data_left) *len = chunking_data_left;
buf = lwr_receive_getbuf(len); /* Either smtp_getbuf or tls_getbuf */
chunking_data_left -= *len;
return buf;
}
void
bdat_flush_data(void)
{
while (chunking_data_left)
{
unsigned n = chunking_data_left;
if (!bdat_getbuf(&n)) break;
}
bdat_pop_receive_functions();
chunking_state = CHUNKING_OFFERED;
DEBUG(D_receive) debug_printf("chunking state %d\n", (int)chunking_state);
}
static inline void
bdat_push_receive_functions(void)
{
/* push the current receive_* function on the "stack", and
replace them by bdat_getc(), which in turn will use the lwr_receive_*
functions to do the dirty work. */
if (!lwr_receive_getc)
{
lwr_receive_getc = receive_getc;
lwr_receive_getbuf = receive_getbuf;
lwr_receive_hasc = receive_hasc;
lwr_receive_ungetc = receive_ungetc;
}
else
{
DEBUG(D_receive) debug_printf("chunking double-push receive functions\n");
}
receive_getc = bdat_getc;
receive_getbuf = bdat_getbuf;
receive_hasc = bdat_hasc;
receive_ungetc = bdat_ungetc;
}
static inline void
bdat_pop_receive_functions(void)
{
if (!lwr_receive_getc)
{
DEBUG(D_receive) debug_printf("chunking double-pop receive functions\n");
return;
}
receive_getc = lwr_receive_getc;
receive_getbuf = lwr_receive_getbuf;
receive_hasc = lwr_receive_hasc;
receive_ungetc = lwr_receive_ungetc;
lwr_receive_getc = NULL;
lwr_receive_getbuf = NULL;
lwr_receive_hasc = NULL;
lwr_receive_ungetc = NULL;
}
int
bdat_ungetc(int ch)
{
chunking_data_left++;
bdat_push_receive_functions(); /* we're not done yet, calling push is safe, because it checks the state before pushing anything */
return lwr_receive_ungetc(ch);
}
/******************************************************************************/
/*************************************************
* Write formatted string to SMTP channel *
*************************************************/
/* This is a separate function so that we don't have to repeat everything for
TLS support or debugging. It is global so that the daemon and the
authentication functions can use it. It does not return any error indication,
because major problems such as dropped connections won't show up till an output
flush for non-TLS connections. The smtp_fflush() function is available for
checking that: for convenience, TLS output errors are remembered here so that
they are also picked up later by smtp_fflush().
This function is exposed to the local_scan API; do not change the signature.
Arguments:
format format string
more further data expected
... optional arguments
Returns: nothing
*/
void
smtp_printf(const char *format, BOOL more, ...)
{
va_list ap;
va_start(ap, more);
smtp_vprintf(format, more, ap);
va_end(ap);
}
/* This is split off so that verify.c:respond_printf() can, in effect, call
smtp_printf(), bearing in mind that in C a vararg function can't directly
call another vararg function, only a function which accepts a va_list.
This function is exposed to the local_scan API; do not change the signature.
*/
/*XXX consider passing caller-info in, for string_vformat-onward */
void
smtp_vprintf(const char *format, BOOL more, va_list ap)
{
gstring gs = { .size = big_buffer_size, .ptr = 0, .s = big_buffer };
BOOL yield;
/* Use taint-unchecked routines for writing into big_buffer, trusting
that we'll never expand it. */
yield = !! string_vformat(&gs, SVFMT_TAINT_NOCHK, format, ap);
string_from_gstring(&gs);
DEBUG(D_receive) for (const uschar * t, * s = gs.s;
s && (t = Ustrchr(s, '\r'));
s = t + 2) /* \r\n */