2 * Copyright (c) 1998-2006 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 # include <libmilter/mfapi.h>
17 # include <libmilter/mfdef.h>
20 SM_RCSID("@(#)$Id: srvrsmtp.c,v 8.924.2.2 2006/05/31 20:56:37 ca Exp $")
27 #endif /* SASL || STARTTLS */
29 # define ENC64LEN(l) (((l) + 2) * 4 / 3 + 1)
30 static int saslmechs __P((sasl_conn_t *, char **));
33 # include <sysexits.h>
35 static SSL_CTX *srv_ctx = NULL; /* TLS server context */
36 static SSL *srv_ssl = NULL; /* per connection context */
38 static bool tls_ok_srv = false;
40 static bool NotFirstDelivery = false;
41 #endif /* _FFR_DM_ONE */
43 extern void tls_set_verify __P((SSL_CTX *, SSL *, bool));
44 # define TLS_VERIFY_CLIENT() tls_set_verify(srv_ctx, srv_ssl, \
45 bitset(SRV_VRFY_CLT, features))
49 #define SRV_NONE 0x0000 /* none... */
50 #define SRV_OFFER_TLS 0x0001 /* offer STARTTLS */
51 #define SRV_VRFY_CLT 0x0002 /* request a cert */
52 #define SRV_OFFER_AUTH 0x0004 /* offer AUTH */
53 #define SRV_OFFER_ETRN 0x0008 /* offer ETRN */
54 #define SRV_OFFER_VRFY 0x0010 /* offer VRFY (not yet used) */
55 #define SRV_OFFER_EXPN 0x0020 /* offer EXPN */
56 #define SRV_OFFER_VERB 0x0040 /* offer VERB */
57 #define SRV_OFFER_DSN 0x0080 /* offer DSN */
59 # define SRV_OFFER_PIPE 0x0100 /* offer PIPELINING */
61 # define SRV_NO_PIPE 0x0200 /* disable PIPELINING, sleep if used */
62 # endif /* _FFR_NO_PIPE */
63 #endif /* PIPELINING */
64 #define SRV_REQ_AUTH 0x0400 /* require AUTH */
65 #define SRV_REQ_SEC 0x0800 /* require security - equiv to AuthOptions=p */
66 #define SRV_TMP_FAIL 0x1000 /* ruleset caused a temporary failure */
68 static unsigned int srvfeatures __P((ENVELOPE *, char *, unsigned int));
70 #define STOP_ATTACK ((time_t) -1)
71 static time_t checksmtpattack __P((volatile unsigned int *, unsigned int,
72 bool, char *, ENVELOPE *));
73 static void mail_esmtp_args __P((char *, char *, ENVELOPE *, unsigned int));
74 static void printvrfyaddr __P((ADDRESS *, bool, bool));
75 static void rcpt_esmtp_args __P((ADDRESS *, char *, char *, ENVELOPE *,
77 static char *skipword __P((char *volatile, char *));
78 static void setup_smtpd_io __P((void));
82 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
83 char *_remoteip, char *_localip,
84 char *_auth_id, sasl_ssf_t *_ext_ssf));
86 # define RESET_SASLCONN \
89 result = reset_saslconn(&conn, AuthRealm, remoteip, \
90 localip, auth_id, &ext_ssf); \
91 if (result != SASL_OK) \
95 # else /* SASL >= 20000 */
96 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
97 struct sockaddr_in *_saddr_r,
98 struct sockaddr_in *_saddr_l,
99 sasl_external_properties_t *_ext_ssf));
100 # define RESET_SASLCONN \
103 result = reset_saslconn(&conn, AuthRealm, &saddr_r, \
104 &saddr_l, &ext_ssf); \
105 if (result != SASL_OK) \
109 # endif /* SASL >= 20000 */
112 extern ENVELOPE BlankEnvelope;
118 (void) sm_snprintf(buf, sizeof buf, "%d", \
119 BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle \
120 ? n_badrcpts - 1 : n_badrcpts); \
121 macdefine(&e->e_macro, A_TEMP, macid("{nbadrcpts}"), buf); \
124 #define SKIP_SPACE(s) while (isascii(*s) && isspace(*s)) \
128 ** SMTP -- run the SMTP protocol.
131 ** nullserver -- if non-NULL, rejection message for
132 ** (almost) all SMTP commands.
133 ** d_flags -- daemon flags
134 ** e -- the envelope.
140 ** Reads commands from the input channel and processes them.
144 ** Notice: The smtp server doesn't have a session context like the client
145 ** side has (mci). Therefore some data (session oriented) is allocated
146 ** or assigned to the "wrong" structure (esp. STARTTLS, AUTH).
147 ** This should be fixed in a successor version.
152 char *cmd_name; /* command name */
153 int cmd_code; /* internal code, see below */
156 /* values for cmd_code */
157 #define CMDERROR 0 /* bad command */
158 #define CMDMAIL 1 /* mail -- designate sender */
159 #define CMDRCPT 2 /* rcpt -- designate recipient */
160 #define CMDDATA 3 /* data -- send message text */
161 #define CMDRSET 4 /* rset -- reset state */
162 #define CMDVRFY 5 /* vrfy -- verify address */
163 #define CMDEXPN 6 /* expn -- expand address */
164 #define CMDNOOP 7 /* noop -- do nothing */
165 #define CMDQUIT 8 /* quit -- close connection and die */
166 #define CMDHELO 9 /* helo -- be polite */
167 #define CMDHELP 10 /* help -- give usage info */
168 #define CMDEHLO 11 /* ehlo -- extended helo (RFC 1425) */
169 #define CMDETRN 12 /* etrn -- flush queue */
171 # define CMDAUTH 13 /* auth -- SASL authenticate */
174 # define CMDSTLS 14 /* STARTTLS -- start TLS session */
175 #endif /* STARTTLS */
176 /* non-standard commands */
177 #define CMDVERB 17 /* verb -- go into verbose mode */
178 /* unimplemented commands from RFC 821 */
179 #define CMDUNIMPL 19 /* unimplemented rfc821 commands */
180 /* use this to catch and log "door handle" attempts on your system */
181 #define CMDLOGBOGUS 23 /* bogus command that should be logged */
182 /* debugging-only commands, only enabled if SMTPDEBUG is defined */
183 #define CMDDBGQSHOW 24 /* showq -- show send queue */
184 #define CMDDBGDEBUG 25 /* debug -- set debug mode */
187 ** Note: If you change this list, remember to update 'helpfile'
190 static struct cmd CmdTab[] =
205 { "send", CMDUNIMPL },
206 { "saml", CMDUNIMPL },
207 { "soml", CMDUNIMPL },
208 { "turn", CMDUNIMPL },
210 { "auth", CMDAUTH, },
213 { "starttls", CMDSTLS, },
214 #endif /* STARTTLS */
215 /* remaining commands are here only to trap and log attempts to use them */
216 { "showq", CMDDBGQSHOW },
217 { "debug", CMDDBGDEBUG },
218 { "wiz", CMDLOGBOGUS },
223 static char *CurSmtpClient; /* who's at the other end of channel */
225 #ifndef MAXBADCOMMANDS
226 # define MAXBADCOMMANDS 25 /* maximum number of bad commands */
227 #endif /* ! MAXBADCOMMANDS */
228 #ifndef MAXHELOCOMMANDS
229 # define MAXHELOCOMMANDS 3 /* max HELO/EHLO commands before slowdown */
230 #endif /* ! MAXHELOCOMMANDS */
231 #ifndef MAXVRFYCOMMANDS
232 # define MAXVRFYCOMMANDS 6 /* max VRFY/EXPN commands before slowdown */
233 #endif /* ! MAXVRFYCOMMANDS */
234 #ifndef MAXETRNCOMMANDS
235 # define MAXETRNCOMMANDS 8 /* max ETRN commands before slowdown */
236 #endif /* ! MAXETRNCOMMANDS */
238 # define MAXTIMEOUT (4 * 60) /* max timeout for bad commands */
239 #endif /* ! MAXTIMEOUT */
242 ** Maximum shift value to compute timeout for bad commands.
243 ** This introduces an upper limit of 2^MAXSHIFT for the timeout.
248 #endif /* ! MAXSHIFT */
250 ERROR _MAXSHIFT > 31 is invalid
251 #endif /* MAXSHIFT */
254 #if MAXBADCOMMANDS > 0
255 # define STOP_IF_ATTACK(r) do \
257 if ((r) == STOP_ATTACK) \
261 #else /* MAXBADCOMMANDS > 0 */
262 # define STOP_IF_ATTACK(r) r
263 #endif /* MAXBADCOMMANDS > 0 */
267 static SM_DEBUG_T DebugLeakSmtp = SM_DEBUG_INITIALIZER("leak_smtp",
268 "@(#)$Debug: leak_smtp - trace memory leaks during SMTP processing $");
269 #endif /* SM_HEAP_CHECK */
273 bool sm_gotmail; /* mail command received */
274 unsigned int sm_nrcpts; /* number of successful RCPT commands */
278 bool sm_milterlist; /* any filters in the list? */
280 char *sm_quarmsg; /* carry quarantining across messages */
283 static bool smtp_data __P((SMTP_T *, ENVELOPE *));
285 #define MSG_TEMPFAIL "451 4.3.2 Please try again later"
288 # define MILTER_ABORT(e) milter_abort((e))
290 # define MILTER_REPLY(str) \
292 int savelogusrerrs = LogUsrErrs; \
296 case SMFIR_SHUTDOWN: \
297 if (MilterLogLevel > 3) \
299 sm_syslog(LOG_INFO, e->e_id, \
300 "Milter: %s=%s, reject=421, errormode=4", \
302 LogUsrErrs = false; \
305 bool tsave = QuickAbort; \
307 QuickAbort = false; \
308 usrerr("421 4.3.0 closing connection"); \
309 QuickAbort = tsave; \
310 e->e_sendqueue = NULL; \
314 case SMFIR_REPLYCODE: \
315 if (MilterLogLevel > 3) \
317 sm_syslog(LOG_INFO, e->e_id, \
318 "Milter: %s=%s, reject=%s", \
319 str, addr, response); \
320 LogUsrErrs = false; \
322 if (strncmp(response, "421 ", 4) == 0 \
323 || strncmp(response, "421-", 4) == 0) \
325 bool tsave = QuickAbort; \
327 QuickAbort = false; \
329 QuickAbort = tsave; \
330 e->e_sendqueue = NULL; \
338 if (MilterLogLevel > 3) \
340 sm_syslog(LOG_INFO, e->e_id, \
341 "Milter: %s=%s, reject=550 5.7.1 Command rejected", \
343 LogUsrErrs = false; \
345 usrerr("550 5.7.1 Command rejected"); \
348 case SMFIR_DISCARD: \
349 if (MilterLogLevel > 3) \
350 sm_syslog(LOG_INFO, e->e_id, \
351 "Milter: %s=%s, discard", \
353 e->e_flags |= EF_DISCARD; \
356 case SMFIR_TEMPFAIL: \
357 if (MilterLogLevel > 3) \
359 sm_syslog(LOG_INFO, e->e_id, \
360 "Milter: %s=%s, reject=%s", \
361 str, addr, MSG_TEMPFAIL); \
362 LogUsrErrs = false; \
364 usrerr(MSG_TEMPFAIL); \
367 LogUsrErrs = savelogusrerrs; \
368 if (response != NULL) \
369 sm_free(response); /* XXX */ \
373 # define MILTER_ABORT(e)
376 /* clear all SMTP state (for HELO/EHLO/RSET) */
377 #define CLEAR_STATE(cmd) \
380 /* abort milter filters */ \
383 if (smtp.sm_nrcpts > 0) \
385 logundelrcpts(e, cmd, 10, false); \
386 smtp.sm_nrcpts = 0; \
387 macdefine(&e->e_macro, A_PERM, \
388 macid("{nrcpts}"), "0"); \
391 e->e_sendqueue = NULL; \
392 e->e_flags |= EF_CLRQUEUE; \
394 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) \
395 logsender(e, NULL); \
396 e->e_flags &= ~EF_LOGSENDER; \
398 /* clean up a bit */ \
399 smtp.sm_gotmail = false; \
401 dropenvelope(e, true, false); \
402 sm_rpool_free(e->e_rpool); \
403 e = newenvelope(e, CurEnv, sm_rpool_new_x(NULL)); \
406 /* put back discard bit */ \
407 if (smtp.sm_discard) \
408 e->e_flags |= EF_DISCARD; \
410 /* restore connection quarantining */ \
411 if (smtp.sm_quarmsg == NULL) \
413 e->e_quarmsg = NULL; \
414 macdefine(&e->e_macro, A_PERM, \
415 macid("{quarantine}"), ""); \
419 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \
421 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \
426 /* sleep to flatten out connection load */
427 #define MIN_DELAY_LOG 15 /* wait before logging this again */
429 /* is it worth setting the process title for 1s? */
430 #define DELAY_CONN(cmd) \
431 if (DelayLA > 0 && (CurrentLA = getla()) >= DelayLA) \
435 sm_setproctitle(true, e, \
436 "%s: %s: delaying %s: load average: %d", \
437 qid_printname(e), CurSmtpClient, \
439 if (LogLevel > 8 && (dnow = curtime()) > log_delay) \
441 sm_syslog(LOG_INFO, e->e_id, \
442 "delaying=%s, load average=%d >= %d", \
443 cmd, CurrentLA, DelayLA); \
444 log_delay = dnow + MIN_DELAY_LOG; \
447 sm_setproctitle(true, e, "%s %s: %.80s", \
448 qid_printname(e), CurSmtpClient, inp); \
453 smtp(nullserver, d_flags, e)
454 char *volatile nullserver;
456 register ENVELOPE *volatile e;
458 register char *volatile p;
459 register struct cmd *volatile c = NULL;
461 auto ADDRESS *vrfyqueue;
463 volatile bool gothello; /* helo command received */
464 bool vrfy; /* set if this is a vrfy command */
465 char *volatile protocol; /* sending protocol */
466 char *volatile sendinghost; /* sending hostname */
467 char *volatile peerhostname; /* name of SMTP peer or "localhost" */
470 volatile unsigned int n_badcmds = 0; /* count of bad commands */
471 volatile unsigned int n_badrcpts = 0; /* number of rejected RCPT */
472 volatile unsigned int n_verifies = 0; /* count of VRFY/EXPN */
473 volatile unsigned int n_etrn = 0; /* count of ETRN */
474 volatile unsigned int n_noop = 0; /* count of NOOP/VERB/etc */
475 volatile unsigned int n_helo = 0; /* count of HELO/EHLO */
476 volatile int save_sevenbitinput;
478 #if _FFR_BLOCK_PROXIES
480 #endif /* _FFR_BLOCK_PROXIES */
481 volatile bool tempfail = false;
482 volatile time_t wt; /* timeout after too many commands */
483 volatile time_t previous; /* time after checksmtpattack() */
484 volatile bool lognullconnection = true;
488 char *greetcode = "220";
489 char *hostname; /* my hostname ($j) */
492 char *args[MAXSMTPARGS];
494 char cmdbuf[MAXLINE];
497 volatile bool sasl_ok;
498 volatile unsigned int n_auth = 0; /* count of AUTH commands */
501 volatile int authenticating;
508 char localip[60], remoteip[60];
509 # else /* SASL >= 20000 */
512 sasl_external_properties_t ext_ssf;
513 struct sockaddr_in saddr_l;
514 struct sockaddr_in saddr_r;
515 # endif /* SASL >= 20000 */
516 sasl_security_properties_t ssp;
518 unsigned int inlen, out2len;
520 char *volatile auth_type;
522 volatile unsigned int n_mechs;
528 volatile bool tls_active = false;
529 volatile bool smtps = bitnset(D_SMTPS, d_flags);
533 #endif /* STARTTLS */
534 volatile unsigned int features;
538 # endif /* _FFR_NO_PIPE */
539 #endif /* PIPELINING */
540 volatile time_t log_delay = (time_t) 0;
542 save_sevenbitinput = SevenBitInput;
545 smtp.sm_milterize = (nullserver == NULL);
546 smtp.sm_milterlist = false;
549 /* setup I/O fd correctly for the SMTP server */
553 if (sm_debug_active(&DebugLeakSmtp, 1))
556 sm_dprintf("smtp() heap group #%d\n", sm_heap_group());
558 #endif /* SM_HEAP_CHECK */
560 /* XXX the rpool should be set when e is initialized in main() */
561 e->e_rpool = sm_rpool_new_x(NULL);
562 e->e_macro.mac_rpool = e->e_rpool;
566 peerhostname = RealHostName;
567 if (peerhostname == NULL)
568 peerhostname = "localhost";
569 CurHostName = peerhostname;
570 CurSmtpClient = macvalue('_', e);
571 if (CurSmtpClient == NULL)
572 CurSmtpClient = CurHostName;
574 /* check_relay may have set discard bit, save for later */
575 smtp.sm_discard = bitset(EF_DISCARD, e->e_flags);
578 /* auto-flush output when reading input */
579 (void) sm_io_autoflush(InChannel, OutChannel);
580 #endif /* PIPELINING */
582 sm_setproctitle(true, e, "server %s startup", CurSmtpClient);
584 /* Set default features for server. */
585 features = ((bitset(PRIV_NOETRN, PrivacyFlags) ||
586 bitnset(D_NOETRN, d_flags)) ? SRV_NONE : SRV_OFFER_ETRN)
587 | (bitnset(D_AUTHREQ, d_flags) ? SRV_REQ_AUTH : SRV_NONE)
588 | (bitset(PRIV_NOEXPN, PrivacyFlags) ? SRV_NONE
590 | (bitset(PRIV_NOVERB, PrivacyFlags)
591 ? SRV_NONE : SRV_OFFER_VERB)))
592 | ((bitset(PRIV_NORECEIPTS, PrivacyFlags) || !SendMIMEErrors)
593 ? SRV_NONE : SRV_OFFER_DSN)
595 | (bitnset(D_NOAUTH, d_flags) ? SRV_NONE : SRV_OFFER_AUTH)
596 | (bitset(SASL_SEC_NOPLAINTEXT, SASLOpts) ? SRV_REQ_SEC
601 #endif /* PIPELINING */
603 | (bitnset(D_NOTLS, d_flags) ? SRV_NONE : SRV_OFFER_TLS)
604 | (bitset(TLS_I_NO_VRFY, TLS_Srv_Opts) ? SRV_NONE
606 #endif /* STARTTLS */
608 if (nullserver == NULL)
610 features = srvfeatures(e, CurSmtpClient, features);
611 if (bitset(SRV_TMP_FAIL, features))
614 sm_syslog(LOG_ERR, NOQID,
615 "ERROR: srv_features=tempfail, relay=%.100s, access temporarily disabled",
617 nullserver = "450 4.3.0 Please try again later.";
623 if (bitset(SRV_NO_PIPE, features))
625 /* for consistency */
626 features &= ~SRV_OFFER_PIPE;
628 # endif /* _FFR_NO_PIPE */
629 #endif /* PIPELINING */
631 if (bitset(SRV_REQ_SEC, features))
632 SASLOpts |= SASL_SEC_NOPLAINTEXT;
634 SASLOpts &= ~SASL_SEC_NOPLAINTEXT;
638 else if (strncmp(nullserver, "421 ", 4) == 0)
644 hostname = macvalue('j', e);
646 if (AuthRealm == NULL)
647 AuthRealm = hostname;
648 sasl_ok = bitset(SRV_OFFER_AUTH, features);
650 authenticating = SASL_NOT_AUTH;
652 /* SASL server new connection */
656 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, NULL,
659 /* use empty realm: only works in SASL > 1.5.5 */
660 result = sasl_server_new("smtp", AuthRealm, "", NULL, 0, &conn);
661 # else /* SASL >= 20000 */
662 /* use no realm -> realm is set to hostname by SASL lib */
663 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, 0,
665 # endif /* SASL >= 20000 */
666 sasl_ok = result == SASL_OK;
670 sm_syslog(LOG_WARNING, NOQID,
671 "AUTH error: sasl_server_new failed=%d",
678 ** SASL set properties for sasl
679 ** set local/remote IP
680 ** XXX Cyrus SASL v1 only supports IPv4
682 ** XXX where exactly are these used/required?
687 localip[0] = remoteip[0] = '\0';
688 # if NETINET || NETINET6
689 in = macvalue(macid("{daemon_family}"), e);
692 strcmp(in, "inet6") == 0 ||
693 # endif /* NETINET6 */
694 strcmp(in, "inet") == 0))
696 SOCKADDR_LEN_T addrsize;
700 addrsize = sizeof(saddr_r);
701 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
703 (struct sockaddr *) &saddr_r,
706 if (iptostring(&saddr_r, addrsize,
707 remoteip, sizeof remoteip))
709 sasl_setprop(conn, SASL_IPREMOTEPORT,
712 addrsize = sizeof(saddr_l);
713 if (getsockname(sm_io_getinfo(InChannel,
716 (struct sockaddr *) &saddr_l,
719 if (iptostring(&saddr_l, addrsize,
730 # endif /* NETINET || NETINET6 */
731 # else /* SASL >= 20000 */
733 in = macvalue(macid("{daemon_family}"), e);
734 if (in != NULL && strcmp(in, "inet") == 0)
736 SOCKADDR_LEN_T addrsize;
738 addrsize = sizeof(struct sockaddr_in);
739 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
741 (struct sockaddr *)&saddr_r,
744 sasl_setprop(conn, SASL_IP_REMOTE, &saddr_r);
745 addrsize = sizeof(struct sockaddr_in);
746 if (getsockname(sm_io_getinfo(InChannel,
749 (struct sockaddr *)&saddr_l,
751 sasl_setprop(conn, SASL_IP_LOCAL,
755 # endif /* NETINET */
756 # endif /* SASL >= 20000 */
762 macdefine(&BlankEnvelope.e_macro, A_PERM,
763 macid("{auth_author}"), NULL);
767 (void) memset(&ssp, '\0', sizeof ssp);
769 /* XXX should these be options settable via .cf ? */
770 /* ssp.min_ssf = 0; is default due to memset() */
772 ssp.max_ssf = MaxSLBits;
773 ssp.maxbufsize = MAXOUTLEN;
775 ssp.security_flags = SASLOpts & SASL_SEC_MASK;
776 sasl_ok = sasl_setprop(conn, SASL_SEC_PROPS, &ssp) == SASL_OK;
781 ** external security strength factor;
782 ** currently we have none so zero
788 sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL,
789 &ext_ssf) == SASL_OK) &&
790 (sasl_setprop(conn, SASL_AUTH_EXTERNAL,
791 auth_id) == SASL_OK));
792 # else /* SASL >= 20000 */
794 ext_ssf.auth_id = NULL;
795 sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL,
796 &ext_ssf) == SASL_OK;
797 # endif /* SASL >= 20000 */
800 n_mechs = saslmechs(conn, &mechlist);
805 #endif /* STARTTLS */
808 if (smtp.sm_milterize)
812 /* initialize mail filter connection */
813 smtp.sm_milterlist = milter_init(e, &state);
817 if (MilterLogLevel > 3)
818 sm_syslog(LOG_INFO, e->e_id,
819 "Milter: initialization failed, rejecting commands");
821 nullserver = "Command rejected";
822 smtp.sm_milterize = false;
826 if (MilterLogLevel > 3)
827 sm_syslog(LOG_INFO, e->e_id,
828 "Milter: initialization failed, temp failing commands");
830 smtp.sm_milterize = false;
834 if (MilterLogLevel > 3)
835 sm_syslog(LOG_INFO, e->e_id,
836 "Milter: initialization failed, closing connection");
838 smtp.sm_milterize = false;
839 message("421 4.7.0 %s closing connection",
842 /* arrange to ignore send list */
843 e->e_sendqueue = NULL;
848 if (smtp.sm_milterlist && smtp.sm_milterize &&
849 !bitset(EF_DISCARD, e->e_flags))
854 response = milter_connect(peerhostname, RealHostAddr,
858 case SMFIR_REPLYCODE: /* REPLYCODE shouldn't happen */
860 if (MilterLogLevel > 3)
861 sm_syslog(LOG_INFO, e->e_id,
862 "Milter: connect: host=%s, addr=%s, rejecting commands",
864 anynet_ntoa(&RealHostAddr));
866 nullserver = "Command rejected";
867 smtp.sm_milterize = false;
871 if (MilterLogLevel > 3)
872 sm_syslog(LOG_INFO, e->e_id,
873 "Milter: connect: host=%s, addr=%s, temp failing commands",
875 anynet_ntoa(&RealHostAddr));
877 smtp.sm_milterize = false;
881 if (MilterLogLevel > 3)
882 sm_syslog(LOG_INFO, e->e_id,
883 "Milter: connect: host=%s, addr=%s, shutdown",
885 anynet_ntoa(&RealHostAddr));
887 smtp.sm_milterize = false;
888 message("421 4.7.0 %s closing connection",
891 /* arrange to ignore send list */
892 e->e_sendqueue = NULL;
895 if (response != NULL)
896 sm_free(response); /* XXX */
901 ** Broken proxies and SMTP slammers
902 ** push data without waiting, catch them
908 #endif /* STARTTLS */
913 char pvpbuf[PSBUFSIZE];
915 /* Ask the rulesets how long to pause */
917 r = rscap("greet_pause", peerhostname,
918 anynet_ntoa(&RealHostAddr), e,
919 &pvp, pvpbuf, sizeof(pvpbuf));
920 if (r == EX_OK && pvp != NULL && pvp[0] != NULL &&
921 (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL)
923 msecs = strtol(pvp[1], NULL, 10);
930 struct timeval timeout;
931 #if _FFR_LOG_GREET_PAUSE
932 struct timeval bp, ep, tp; /* {begin,end,total}pause */
933 #endif /* _FFR_LOG_GREET_PAUSE */
935 /* pause for a moment */
936 timeout.tv_sec = msecs / 1000;
937 timeout.tv_usec = (msecs % 1000) * 1000;
939 /* Obey RFC 2821: 4.3.5.2: 220 timeout of 5 minutes */
940 if (timeout.tv_sec >= 300)
942 timeout.tv_sec = 300;
946 /* check if data is on the socket during the pause */
947 fd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
949 SM_FD_SET(fd, &readfds);
950 #if _FFR_LOG_GREET_PAUSE
951 gettimeofday(&bp, NULL);
952 #endif /* _FFR_LOG_GREET_PAUSE */
953 if (select(fd + 1, FDSET_CAST &readfds,
954 NULL, NULL, &timeout) > 0 &&
955 FD_ISSET(fd, &readfds))
957 #if _FFR_LOG_GREET_PAUSE
958 gettimeofday(&ep, NULL);
959 timersub(&ep, &bp, &tp);
960 #endif /* _FFR_LOG_GREET_PAUSE */
962 nullserver = "Command rejected";
963 sm_syslog(LOG_INFO, e->e_id,
964 #if _FFR_LOG_GREET_PAUSE
965 "rejecting commands from %s [%s] after %d seconds due to pre-greeting traffic",
966 #else /* _FFR_LOG_GREET_PAUSE */
967 "rejecting commands from %s [%s] due to pre-greeting traffic",
968 #endif /* _FFR_LOG_GREET_PAUSE */
970 anynet_ntoa(&RealHostAddr)
971 #if _FFR_LOG_GREET_PAUSE
973 (tp.tv_usec >= 500000 ? 1 : 0)
974 #endif /* _FFR_LOG_GREET_PAUSE */
981 /* If this an smtps connection, start TLS now */
990 #endif /* STARTTLS */
992 /* output the first line, inserting "ESMTP" as second word */
993 if (*greetcode == '5')
994 (void) sm_snprintf(inp, sizeof inp, "%s not accepting messages",
997 expand(SmtpGreeting, inp, sizeof inp, e);
999 p = strchr(inp, '\n');
1002 id = strchr(inp, ' ');
1004 id = &inp[strlen(inp)];
1006 (void) sm_snprintf(cmdbuf, sizeof cmdbuf,
1007 "%s %%.*s ESMTP%%s", greetcode);
1009 (void) sm_snprintf(cmdbuf, sizeof cmdbuf,
1010 "%s-%%.*s ESMTP%%s", greetcode);
1011 message(cmdbuf, (int) (id - inp), inp, id);
1013 /* output remaining lines */
1014 while ((id = p) != NULL && (p = strchr(id, '\n')) != NULL)
1017 if (isascii(*id) && isspace(*id))
1019 (void) sm_strlcpyn(cmdbuf, sizeof cmdbuf, 2, greetcode, "-%s");
1020 message(cmdbuf, id);
1024 if (isascii(*id) && isspace(*id))
1026 (void) sm_strlcpyn(cmdbuf, sizeof cmdbuf, 2, greetcode, " %s");
1027 message(cmdbuf, id);
1031 sendinghost = macvalue('s', e);
1033 /* If quarantining by a connect/ehlo action, save between messages */
1034 if (e->e_quarmsg == NULL)
1035 smtp.sm_quarmsg = NULL;
1037 smtp.sm_quarmsg = newstr(e->e_quarmsg);
1039 /* sendinghost's storage must outlive the current envelope */
1040 if (sendinghost != NULL)
1041 sendinghost = sm_strdup_x(sendinghost);
1042 #if _FFR_BLOCK_PROXIES
1044 #endif /* _FFR_BLOCK_PROXIES */
1046 smtp.sm_gotmail = false;
1055 OnlyOneError = true;
1056 e->e_flags &= ~(EF_VRFYONLY|EF_GLOBALERRS);
1058 /* setup for the read */
1062 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
1064 /* read the input line */
1065 SmtpPhase = "server cmd read";
1066 sm_setproctitle(true, e, "server %s cmd read", CurSmtpClient);
1069 ** XXX SMTP AUTH requires accepting any length,
1070 ** at least for challenge/response
1075 if (sm_io_error(OutChannel) ||
1076 (p = sfgets(inp, sizeof inp, InChannel,
1077 TimeOuts.to_nextcommand, SmtpPhase)) == NULL)
1081 d = macvalue(macid("{daemon_name}"), e);
1084 /* end of file, just die */
1088 /* close out milter filters */
1092 message("421 4.4.1 %s Lost input channel from %s",
1093 MyHostName, CurSmtpClient);
1094 if (LogLevel > (smtp.sm_gotmail ? 1 : 19))
1095 sm_syslog(LOG_NOTICE, e->e_id,
1096 "lost input channel from %s to %s after %s",
1098 (c == NULL || c->cmd_name == NULL) ? "startup" : c->cmd_name);
1100 ** If have not accepted mail (DATA), do not bounce
1101 ** bad addresses back to sender.
1104 if (bitset(EF_CLRQUEUE, e->e_flags))
1105 e->e_sendqueue = NULL;
1109 #if _FFR_BLOCK_PROXIES
1112 size_t inplen, cmdlen;
1115 static char *http_cmds[] = { "GET", "POST",
1116 "CONNECT", "USER", NULL };
1118 inplen = strlen(inp);
1119 for (idx = 0; (http_cmd = http_cmds[idx]) != NULL;
1122 cmdlen = strlen(http_cmd);
1123 if (cmdlen < inplen &&
1124 sm_strncasecmp(inp, http_cmd, cmdlen) == 0 &&
1125 isascii(inp[cmdlen]) && isspace(inp[cmdlen]))
1127 /* Open proxy, drop it */
1128 message("421 4.7.0 %s Rejecting open proxy %s",
1129 MyHostName, CurSmtpClient);
1130 sm_syslog(LOG_INFO, e->e_id,
1131 "%s: probable open proxy: command=%.40s",
1132 CurSmtpClient, inp);
1138 #endif /* _FFR_BLOCK_PROXIES */
1140 /* clean up end of line */
1146 ** if there is more input and pipelining is disabled:
1147 ** delay ... (and maybe discard the input?)
1148 ** XXX this doesn't really work, at least in tests using
1149 ** telnet SM_IO_IS_READABLE only returns 1 if there were
1150 ** more than 2 input lines available.
1153 if (bitset(SRV_NO_PIPE, features) &&
1154 sm_io_getinfo(InChannel, SM_IO_IS_READABLE, NULL) > 0)
1157 sm_syslog(LOG_INFO, NOQID,
1158 "unauthorized PIPELINING, sleeping");
1162 # endif /* _FFR_NO_PIPE */
1163 #endif /* PIPELINING */
1166 if (authenticating == SASL_PROC_AUTH)
1171 authenticating = SASL_NOT_AUTH;
1172 message("501 5.5.2 missing input");
1177 if (*inp == '*' && *(inp + 1) == '\0')
1179 authenticating = SASL_NOT_AUTH;
1182 message("501 5.0.0 AUTH aborted");
1187 /* could this be shorter? XXX */
1189 in = xalloc(strlen(inp) + 1);
1190 result = sasl_decode64(inp, strlen(inp), in,
1191 strlen(inp), &inlen);
1192 # else /* SASL >= 20000 */
1193 out = xalloc(strlen(inp));
1194 result = sasl_decode64(inp, strlen(inp), out, &outlen);
1195 # endif /* SASL >= 20000 */
1196 if (result != SASL_OK)
1198 authenticating = SASL_NOT_AUTH;
1201 message("501 5.5.4 cannot decode AUTH parameter %s",
1205 # endif /* SASL >= 20000 */
1211 result = sasl_server_step(conn, in, inlen,
1214 # else /* SASL >= 20000 */
1215 result = sasl_server_step(conn, out, outlen,
1216 &out, &outlen, &errstr);
1217 # endif /* SASL >= 20000 */
1219 /* get an OK if we're done */
1220 if (result == SASL_OK)
1223 message("235 2.0.0 OK Authenticated");
1224 authenticating = SASL_IS_AUTH;
1225 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1226 macid("{auth_type}"), auth_type);
1229 user = macvalue(macid("{auth_authen}"), e);
1231 /* get security strength (features) */
1232 result = sasl_getprop(conn, SASL_SSF,
1233 (const void **) &ssf);
1234 # else /* SASL >= 20000 */
1235 result = sasl_getprop(conn, SASL_USERNAME,
1237 if (result != SASL_OK)
1240 macdefine(&BlankEnvelope.e_macro,
1242 macid("{auth_authen}"), NULL);
1246 macdefine(&BlankEnvelope.e_macro,
1248 macid("{auth_authen}"),
1249 xtextify(user, "<>\")"));
1254 sasl_getprop(conn, SASL_REALM, (void **) &data);
1257 /* get security strength (features) */
1258 result = sasl_getprop(conn, SASL_SSF,
1260 # endif /* SASL >= 20000 */
1261 if (result != SASL_OK)
1263 macdefine(&BlankEnvelope.e_macro,
1265 macid("{auth_ssf}"), "0");
1272 (void) sm_snprintf(pbuf, sizeof pbuf,
1274 macdefine(&BlankEnvelope.e_macro,
1276 macid("{auth_ssf}"), pbuf);
1278 sm_dprintf("AUTH auth_ssf: %u\n",
1283 ** Only switch to encrypted connection
1284 ** if a security layer has been negotiated
1287 if (ssf != NULL && *ssf > 0)
1292 ** Convert I/O layer to use SASL.
1293 ** If the call fails, the connection
1297 tmo = TimeOuts.to_datablock * 1000;
1298 if (sfdcsasl(&InChannel, &OutChannel,
1301 /* restart dialogue */
1304 (void) sm_io_autoflush(InChannel,
1306 # endif /* PIPELINING */
1309 syserr("503 5.3.3 SASL TLS failed");
1312 /* NULL pointer ok since it's our function */
1314 sm_syslog(LOG_INFO, NOQID,
1315 "AUTH=server, relay=%s, authid=%.128s, mech=%.16s, bits=%d",
1317 shortenstring(user, 128),
1320 else if (result == SASL_CONTINUE)
1322 len = ENC64LEN(outlen);
1324 result = sasl_encode64(out, outlen, out2, len,
1326 if (result != SASL_OK)
1328 /* correct code? XXX */
1329 /* 454 Temp. authentication failure */
1330 message("454 4.5.4 Internal error: unable to encode64");
1332 sm_syslog(LOG_WARNING, e->e_id,
1333 "AUTH encode64 error [%d for \"%s\"]",
1336 authenticating = SASL_NOT_AUTH;
1340 message("334 %s", out2);
1342 sm_dprintf("AUTH continue: msg='%s' len=%u\n",
1347 # endif /* SASL >= 20000 */
1351 /* not SASL_OK or SASL_CONT */
1352 message("535 5.7.0 authentication failed");
1354 sm_syslog(LOG_WARNING, e->e_id,
1355 "AUTH failure (%s): %s (%d) %s",
1357 sasl_errstring(result, NULL,
1361 sasl_errdetail(conn));
1362 # else /* SASL >= 20000 */
1363 errstr == NULL ? "" : errstr);
1364 # endif /* SASL >= 20000 */
1366 authenticating = SASL_NOT_AUTH;
1371 /* don't want to do any of this if authenticating */
1374 /* echo command to transcript */
1375 if (e->e_xfp != NULL)
1376 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1380 sm_syslog(LOG_INFO, e->e_id, "<-- %s", inp);
1382 /* break off command */
1383 for (p = inp; isascii(*p) && isspace(*p); p++)
1386 while (*p != '\0' &&
1387 !(isascii(*p) && isspace(*p)) &&
1388 cmd < &cmdbuf[sizeof cmdbuf - 2])
1392 /* throw away leading whitespace */
1395 /* decode command */
1396 for (c = CmdTab; c->cmd_name != NULL; c++)
1398 if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0)
1405 /* check whether a "non-null" command has been used */
1406 switch (c->cmd_code)
1410 /* avoid information leak; take first two words? */
1419 lognullconnection = false;
1426 if (e->e_id == NULL)
1427 sm_setproctitle(true, e, "%s: %.80s",
1430 sm_setproctitle(true, e, "%s %s: %.80s",
1437 ** If we are running as a null server, return 550
1438 ** to almost everything.
1441 if (nullserver != NULL || bitnset(D_ETRNONLY, d_flags))
1443 switch (c->cmd_code)
1451 /* process normally */
1455 if (bitnset(D_ETRNONLY, d_flags) &&
1462 #if MAXBADCOMMANDS > 0
1463 /* theoretically this could overflow */
1464 if (nullserver != NULL &&
1465 ++n_badcmds > MAXBADCOMMANDS)
1467 message("421 4.7.0 %s Too many bad commands; closing connection",
1470 /* arrange to ignore send list */
1471 e->e_sendqueue = NULL;
1474 #endif /* MAXBADCOMMANDS > 0 */
1475 if (nullserver != NULL)
1477 if (ISSMTPREPLY(nullserver))
1480 usrerr("550 5.0.0 %s",
1484 usrerr("452 4.4.5 Insufficient disk space; try again later");
1489 switch (c->cmd_code)
1492 case CMDAUTH: /* sasl */
1494 if (!sasl_ok || n_mechs <= 0)
1496 message("503 5.3.3 AUTH not available");
1499 if (authenticating == SASL_IS_AUTH)
1501 message("503 5.5.0 Already Authenticated");
1504 if (smtp.sm_gotmail)
1506 message("503 5.5.0 AUTH not permitted during a mail transaction");
1512 sm_syslog(LOG_INFO, e->e_id,
1513 "SMTP AUTH command (%.100s) from %s tempfailed (due to previous checks)",
1515 usrerr("454 4.3.0 Please try again later");
1521 /* crude way to avoid crack attempts */
1522 STOP_IF_ATTACK(checksmtpattack(&n_auth, n_mechs + 1,
1525 /* make sure mechanism (p) is a valid string */
1526 for (q = p; *q != '\0' && isascii(*q); q++)
1531 while (*++q != '\0' &&
1532 isascii(*q) && isspace(*q))
1535 ismore = (*q != '\0');
1542 message("501 5.5.2 AUTH mechanism must be specified");
1546 /* check whether mechanism is available */
1547 if (iteminlist(p, mechlist, " ") == NULL)
1549 message("504 5.3.3 AUTH mechanism %.32s not available",
1556 /* could this be shorter? XXX */
1558 in = xalloc(strlen(q) + 1);
1559 result = sasl_decode64(q, strlen(q), in,
1561 # else /* SASL >= 20000 */
1562 in = sm_rpool_malloc(e->e_rpool, strlen(q));
1563 result = sasl_decode64(q, strlen(q), in,
1565 # endif /* SASL >= 20000 */
1566 if (result != SASL_OK)
1568 message("501 5.5.4 cannot BASE64 decode '%s'",
1571 sm_syslog(LOG_WARNING, e->e_id,
1572 "AUTH decode64 error [%d for \"%s\"]",
1575 authenticating = SASL_NOT_AUTH;
1578 # endif /* SASL >= 20000 */
1590 /* see if that auth type exists */
1592 result = sasl_server_start(conn, p, in, inlen,
1596 # else /* SASL >= 20000 */
1597 result = sasl_server_start(conn, p, in, inlen,
1598 &out, &outlen, &errstr);
1599 # endif /* SASL >= 20000 */
1601 if (result != SASL_OK && result != SASL_CONTINUE)
1603 message("535 5.7.0 authentication failed");
1605 sm_syslog(LOG_ERR, e->e_id,
1606 "AUTH failure (%s): %s (%d) %s",
1608 sasl_errstring(result, NULL,
1612 sasl_errdetail(conn));
1613 # else /* SASL >= 20000 */
1615 # endif /* SASL >= 20000 */
1619 auth_type = newstr(p);
1621 if (result == SASL_OK)
1623 /* ugly, but same code */
1625 /* authenticated by the initial response */
1628 /* len is at least 2 */
1629 len = ENC64LEN(outlen);
1631 result = sasl_encode64(out, outlen, out2, len,
1634 if (result != SASL_OK)
1636 message("454 4.5.4 Temporary authentication failure");
1638 sm_syslog(LOG_WARNING, e->e_id,
1639 "AUTH encode64 error [%d for \"%s\"]",
1643 authenticating = SASL_NOT_AUTH;
1648 message("334 %s", out2);
1649 authenticating = SASL_PROC_AUTH;
1653 # endif /* SASL >= 20000 */
1658 case CMDSTLS: /* starttls */
1659 DELAY_CONN("STARTTLS");
1662 message("501 5.5.2 Syntax error (no parameters allowed)");
1665 if (!bitset(SRV_OFFER_TLS, features))
1667 message("503 5.5.0 TLS not available");
1672 message("454 4.3.3 TLS not available after start");
1675 if (smtp.sm_gotmail)
1677 message("503 5.5.0 TLS not permitted during a mail transaction");
1683 sm_syslog(LOG_INFO, e->e_id,
1684 "SMTP STARTTLS command (%.100s) from %s tempfailed (due to previous checks)",
1686 usrerr("454 4.7.0 Please try again later");
1692 ** XXX do we need a temp key ?
1694 # else /* TLS_NO_RSA */
1695 # endif /* TLS_NO_RSA */
1697 # if TLS_VRFY_PER_CTX
1699 ** Note: this sets the verification globally
1701 ** it's ok since it applies only to one transaction
1704 TLS_VERIFY_CLIENT();
1705 # endif /* TLS_VRFY_PER_CTX */
1707 if (srv_ssl != NULL)
1709 else if ((srv_ssl = SSL_new(srv_ctx)) == NULL)
1711 message("454 4.3.3 TLS not available: error generating SSL handle");
1713 tlslogerr("server");
1717 # if !TLS_VRFY_PER_CTX
1719 ** this could be used if it were possible to set
1720 ** verification per SSL (connection)
1721 ** not just per SSL_CTX (global)
1724 TLS_VERIFY_CLIENT();
1725 # endif /* !TLS_VRFY_PER_CTX */
1727 rfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1728 wfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
1730 if (rfd < 0 || wfd < 0 ||
1731 SSL_set_rfd(srv_ssl, rfd) <= 0 ||
1732 SSL_set_wfd(srv_ssl, wfd) <= 0)
1734 message("454 4.3.3 TLS not available: error set fd");
1740 message("220 2.0.0 Ready to start TLS");
1742 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
1743 # endif /* PIPELINING */
1745 SSL_set_accept_state(srv_ssl);
1747 # define SSL_ACC(s) SSL_accept(s)
1749 tlsstart = curtime();
1751 if ((r = SSL_ACC(srv_ssl)) <= 0)
1755 ssl_err = SSL_get_error(srv_ssl, r);
1756 i = tls_retry(srv_ssl, rfd, wfd, tlsstart,
1757 TimeOuts.to_starttls, ssl_err,
1764 sm_syslog(LOG_WARNING, NOQID,
1765 "STARTTLS=server, error: accept failed=%d, SSL_error=%d, errno=%d, retry=%d",
1766 r, ssl_err, errno, i);
1768 tlslogerr("server");
1775 ** according to the next draft of
1776 ** RFC 2487 the connection should be dropped
1779 /* arrange to ignore any current send list */
1780 e->e_sendqueue = NULL;
1784 /* ignore return code for now, it's in {verify} */
1785 (void) tls_get_info(srv_ssl, true,
1787 &BlankEnvelope.e_macro,
1788 bitset(SRV_VRFY_CLT, features));
1791 ** call Stls_client to find out whether
1792 ** to accept the connection from the client
1795 saveQuickAbort = QuickAbort;
1796 saveSuprErrs = SuprErrs;
1799 if (rscheck("tls_client",
1800 macvalue(macid("{verify}"), e),
1802 RSF_RMCOMM|RSF_COUNT,
1803 5, NULL, NOQID) != EX_OK ||
1806 extern char MsgBuf[];
1808 if (MsgBuf[0] != '\0' && ISSMTPREPLY(MsgBuf))
1809 nullserver = newstr(MsgBuf);
1811 nullserver = "503 5.7.0 Authentication required.";
1813 QuickAbort = saveQuickAbort;
1814 SuprErrs = saveSuprErrs;
1816 tls_ok_srv = false; /* don't offer STARTTLS again */
1825 s = macvalue(macid("{cipher_bits}"), e);
1826 v = macvalue(macid("{verify}"), e);
1827 c = macvalue(macid("{cert_subject}"), e);
1828 verified = (v != NULL && strcmp(v, "OK") == 0);
1829 if (s != NULL && (cipher_bits = atoi(s)) > 0)
1832 ext_ssf = cipher_bits;
1833 auth_id = verified ? c : NULL;
1834 sasl_ok = ((sasl_setprop(conn,
1836 &ext_ssf) == SASL_OK) &&
1839 auth_id) == SASL_OK));
1840 # else /* SASL >= 20000 */
1841 ext_ssf.ssf = cipher_bits;
1842 ext_ssf.auth_id = verified ? c : NULL;
1843 sasl_ok = sasl_setprop(conn,
1845 &ext_ssf) == SASL_OK;
1846 # endif /* SASL >= 20000 */
1849 n_mechs = saslmechs(conn,
1855 /* switch to secure connection */
1856 if (sfdctls(&InChannel, &OutChannel, srv_ssl) == 0)
1860 (void) sm_io_autoflush(InChannel, OutChannel);
1861 # endif /* PIPELINING */
1866 ** XXX this is an internal error
1867 ** how to deal with it?
1868 ** we can't generate an error message
1869 ** since the other side switched to an
1870 ** encrypted layer, but we could not...
1874 nullserver = "454 4.3.3 TLS not available: can't switch to encrypted layer";
1875 syserr("STARTTLS: can't switch to encrypted layer");
1886 #endif /* STARTTLS */
1888 case CMDHELO: /* hello -- introduce yourself */
1889 case CMDEHLO: /* extended hello */
1891 if (c->cmd_code == CMDEHLO)
1894 SmtpPhase = "server EHLO";
1899 SmtpPhase = "server HELO";
1902 /* avoid denial-of-service */
1903 STOP_IF_ATTACK(checksmtpattack(&n_helo, MAXHELOCOMMANDS,
1904 true, "HELO/EHLO", e));
1907 /* RFC2821 4.1.4 allows duplicate HELO/EHLO */
1908 /* check for duplicate HELO/EHLO per RFC 1651 4.2 */
1911 usrerr("503 %s Duplicate HELO/EHLO",
1917 /* check for valid domain name (re 1123 5.2.5) */
1918 if (*p == '\0' && !AllowBogusHELO)
1920 usrerr("501 %s requires domain address",
1925 /* check for long domain name (hides Received: info) */
1926 if (strlen(p) > MAXNAME)
1928 usrerr("501 Invalid domain name");
1930 sm_syslog(LOG_INFO, CurEnv->e_id,
1931 "invalid domain name (too long) from %s",
1937 for (q = p; *q != '\0'; q++)
1947 /* only complain if strict check */
1948 ok = AllowBogusHELO;
1950 /* allow trailing whitespace */
1951 while (!ok && *++q != '\0' &&
1958 if (strchr("[].-_#:", *q) == NULL)
1962 if (*q == '\0' && ok)
1964 q = "pleased to meet you";
1965 sendinghost = sm_strdup_x(p);
1967 else if (!AllowBogusHELO)
1969 usrerr("501 Invalid domain name");
1971 sm_syslog(LOG_INFO, CurEnv->e_id,
1972 "invalid domain name (%s) from %.100s",
1978 q = "accepting invalid domain name";
1981 if (gothello || smtp.sm_gotmail)
1982 CLEAR_STATE(cmdbuf);
1985 if (smtp.sm_milterlist && smtp.sm_milterize &&
1986 !bitset(EF_DISCARD, e->e_flags))
1991 response = milter_helo(p, e, &state);
1994 case SMFIR_REPLYCODE:
1995 if (MilterLogLevel > 3)
1996 sm_syslog(LOG_INFO, e->e_id,
1997 "Milter: helo=%s, reject=%s",
1999 nullserver = newstr(response);
2000 smtp.sm_milterize = false;
2004 if (MilterLogLevel > 3)
2005 sm_syslog(LOG_INFO, e->e_id,
2006 "Milter: helo=%s, reject=Command rejected",
2008 nullserver = "Command rejected";
2009 smtp.sm_milterize = false;
2012 case SMFIR_TEMPFAIL:
2013 if (MilterLogLevel > 3)
2014 sm_syslog(LOG_INFO, e->e_id,
2015 "Milter: helo=%s, reject=%s",
2018 smtp.sm_milterize = false;
2021 case SMFIR_SHUTDOWN:
2022 if (MilterLogLevel > 3)
2023 sm_syslog(LOG_INFO, e->e_id,
2024 "Milter: helo=%s, reject=421 4.7.0 %s closing connection",
2027 smtp.sm_milterize = false;
2028 message("421 4.7.0 %s closing connection",
2030 /* arrange to ignore send list */
2031 e->e_sendqueue = NULL;
2034 if (response != NULL)
2038 ** If quarantining by a connect/ehlo action,
2039 ** save between messages
2042 if (smtp.sm_quarmsg == NULL &&
2043 e->e_quarmsg != NULL)
2044 smtp.sm_quarmsg = newstr(e->e_quarmsg);
2049 /* print HELO response message */
2050 if (c->cmd_code != CMDEHLO)
2052 message("250 %s Hello %s, %s",
2053 MyHostName, CurSmtpClient, q);
2057 message("250-%s Hello %s, %s",
2058 MyHostName, CurSmtpClient, q);
2060 /* offer ENHSC even for nullserver */
2061 if (nullserver != NULL)
2063 message("250 ENHANCEDSTATUSCODES");
2068 ** print EHLO features list
2070 ** Note: If you change this list,
2071 ** remember to update 'helpfile'
2074 message("250-ENHANCEDSTATUSCODES");
2076 if (bitset(SRV_OFFER_PIPE, features))
2077 message("250-PIPELINING");
2078 #endif /* PIPELINING */
2079 if (bitset(SRV_OFFER_EXPN, features))
2081 message("250-EXPN");
2082 if (bitset(SRV_OFFER_VERB, features))
2083 message("250-VERB");
2086 message("250-8BITMIME");
2087 #endif /* MIME8TO7 */
2088 if (MaxMessageSize > 0)
2089 message("250-SIZE %ld", MaxMessageSize);
2091 message("250-SIZE");
2093 if (SendMIMEErrors && bitset(SRV_OFFER_DSN, features))
2096 if (bitset(SRV_OFFER_ETRN, features))
2097 message("250-ETRN");
2099 if (sasl_ok && mechlist != NULL && *mechlist != '\0')
2100 message("250-AUTH %s", mechlist);
2104 bitset(SRV_OFFER_TLS, features))
2105 message("250-STARTTLS");
2106 #endif /* STARTTLS */
2107 if (DeliverByMin > 0)
2108 message("250-DELIVERBY %ld",
2109 (long) DeliverByMin);
2110 else if (DeliverByMin == 0)
2111 message("250-DELIVERBY");
2113 /* < 0: no deliver-by */
2115 message("250 HELP");
2118 case CMDMAIL: /* mail -- designate sender */
2119 SmtpPhase = "server MAIL";
2122 /* check for validity of this command */
2123 if (!gothello && bitset(PRIV_NEEDMAILHELO, PrivacyFlags))
2125 usrerr("503 5.0.0 Polite people say HELO first");
2128 if (smtp.sm_gotmail)
2130 usrerr("503 5.5.0 Sender already specified");
2134 if (bitset(SRV_REQ_AUTH, features) &&
2135 authenticating != SASL_IS_AUTH)
2137 usrerr("530 5.7.0 Authentication required");
2142 p = skipword(p, "from");
2148 sm_syslog(LOG_INFO, e->e_id,
2149 "SMTP MAIL command (%.100s) from %s tempfailed (due to previous checks)",
2151 usrerr(MSG_TEMPFAIL);
2155 /* make sure we know who the sending host is */
2156 if (sendinghost == NULL)
2157 sendinghost = peerhostname;
2161 if (sm_debug_active(&DebugLeakSmtp, 1))
2164 sm_dprintf("smtp() heap group #%d\n",
2167 #endif /* SM_HEAP_CHECK */
2173 auth_warning(e, "%s didn't use HELO protocol",
2176 #ifdef PICKY_HELO_CHECK
2177 if (sm_strcasecmp(sendinghost, peerhostname) != 0 &&
2178 (sm_strcasecmp(peerhostname, "localhost") != 0 ||
2179 sm_strcasecmp(sendinghost, MyHostName) != 0))
2181 auth_warning(e, "Host %s claimed to be %s",
2182 CurSmtpClient, sendinghost);
2184 #endif /* PICKY_HELO_CHECK */
2186 if (protocol == NULL)
2188 macdefine(&e->e_macro, A_PERM, 'r', protocol);
2189 macdefine(&e->e_macro, A_PERM, 's', sendinghost);
2195 macdefine(&e->e_macro, A_PERM, macid("{ntries}"), "0");
2196 macdefine(&e->e_macro, A_PERM, macid("{nrcpts}"), "0");
2197 macdefine(&e->e_macro, A_PERM, macid("{nbadrcpts}"),
2199 e->e_flags |= EF_CLRQUEUE;
2200 sm_setproctitle(true, e, "%s %s: %.80s",
2202 CurSmtpClient, inp);
2204 /* do the processing */
2207 extern char *FullName;
2210 SM_FREE_CLR(FullName);
2212 /* must parse sender first */
2214 setsender(p, e, &delimptr, ' ', false);
2215 if (delimptr != NULL && *delimptr != '\0')
2218 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2220 /* Successfully set e_from, allow logging */
2221 e->e_flags |= EF_LOGSENDER;
2223 /* put resulting triple from parseaddr() into macros */
2224 if (e->e_from.q_mailer != NULL)
2225 macdefine(&e->e_macro, A_PERM,
2226 macid("{mail_mailer}"),
2227 e->e_from.q_mailer->m_name);
2229 macdefine(&e->e_macro, A_PERM,
2230 macid("{mail_mailer}"), NULL);
2231 if (e->e_from.q_host != NULL)
2232 macdefine(&e->e_macro, A_PERM,
2233 macid("{mail_host}"),
2236 macdefine(&e->e_macro, A_PERM,
2237 macid("{mail_host}"), "localhost");
2238 if (e->e_from.q_user != NULL)
2239 macdefine(&e->e_macro, A_PERM,
2240 macid("{mail_addr}"),
2243 macdefine(&e->e_macro, A_PERM,
2244 macid("{mail_addr}"), NULL);
2246 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2248 /* check for possible spoofing */
2249 if (RealUid != 0 && OpMode == MD_SMTP &&
2250 !wordinclass(RealUserName, 't') &&
2251 (!bitnset(M_LOCALMAILER,
2252 e->e_from.q_mailer->m_flags) ||
2253 strcmp(e->e_from.q_user, RealUserName) != 0))
2255 auth_warning(e, "%s owned process doing -bs",
2259 /* reset to default value */
2260 SevenBitInput = save_sevenbitinput;
2262 /* now parse ESMTP arguments */
2268 while (p != NULL && *p != '\0')
2274 /* locate the beginning of the keyword */
2280 /* skip to the value portion */
2281 while ((isascii(*p) && isalnum(*p)) || *p == '-')
2289 /* skip to the end of the value */
2290 while (*p != '\0' && *p != ' ' &&
2291 !(isascii(*p) && iscntrl(*p)) &&
2300 sm_dprintf("MAIL: got arg %s=\"%s\"\n", kp,
2301 vp == NULL ? "<null>" : vp);
2303 mail_esmtp_args(kp, vp, e, features);
2307 if (argno >= MAXSMTPARGS - 1)
2308 usrerr("501 5.5.4 Too many parameters");
2310 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2314 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2317 # if _FFR_AUTH_PASSING
2318 /* set the default AUTH= if the sender didn't */
2319 if (e->e_auth_param == NULL)
2321 /* XXX only do this for an MSA? */
2322 e->e_auth_param = macvalue(macid("{auth_authen}"),
2324 if (e->e_auth_param == NULL)
2325 e->e_auth_param = "<>";
2328 ** XXX should we invoke Strust_auth now?
2329 ** authorizing as the client that just
2330 ** authenticated, so we'll trust implicitly
2333 # endif /* _FFR_AUTH_PASSING */
2336 /* do config file checking of the sender */
2337 macdefine(&e->e_macro, A_PERM,
2338 macid("{addr_type}"), "e s");
2340 /* make the "real" sender address available */
2341 macdefine(&e->e_macro, A_TEMP, macid("{mail_from}"),
2343 #endif /* _FFR_MAIL_MACRO */
2344 if (rscheck("check_mail", addr,
2345 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2346 NULL, e->e_id) != EX_OK ||
2348 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2349 macdefine(&e->e_macro, A_PERM,
2350 macid("{addr_type}"), NULL);
2352 if (MaxMessageSize > 0 &&
2353 (e->e_msgsize > MaxMessageSize ||
2356 usrerr("552 5.2.3 Message size exceeds fixed maximum message size (%ld)",
2358 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2362 ** XXX always check whether there is at least one fs
2363 ** with enough space?
2364 ** However, this may not help much: the queue group
2365 ** selection may later on select a FS that hasn't
2369 if ((NumFileSys == 1 || NumQueue == 1) &&
2370 !enoughdiskspace(e->e_msgsize, e)
2371 #if _FFR_ANY_FREE_FS
2372 && !filesys_free(e->e_msgsize)
2373 #endif /* _FFR_ANY_FREE_FS */
2377 ** We perform this test again when the
2378 ** queue directory is selected, in collect.
2381 usrerr("452 4.4.5 Insufficient disk space; try again later");
2382 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2385 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2389 if (smtp.sm_milterlist && smtp.sm_milterize &&
2390 !bitset(EF_DISCARD, e->e_flags))
2395 response = milter_envfrom(args, e, &state);
2396 MILTER_REPLY("from");
2400 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2402 message("250 2.1.0 Sender ok");
2403 smtp.sm_gotmail = true;
2405 SM_EXCEPT(exc, "[!F]*")
2408 ** An error occurred while processing a MAIL command.
2409 ** Jump to the common error handling code.
2419 e->e_flags &= ~EF_PM_NOTIFY;
2423 case CMDRCPT: /* rcpt -- designate recipient */
2425 if (BadRcptThrottle > 0 &&
2426 n_badrcpts >= BadRcptThrottle)
2429 n_badrcpts == BadRcptThrottle)
2431 sm_syslog(LOG_INFO, e->e_id,
2432 "%s: Possible SMTP RCPT flood, throttling.",
2435 /* To avoid duplicated message */
2441 ** Don't use exponential backoff for now.
2442 ** Some servers will open more connections
2443 ** and actually overload the receiver even
2449 if (!smtp.sm_gotmail)
2451 usrerr("503 5.0.0 Need MAIL before RCPT");
2454 SmtpPhase = "server RCPT";
2460 /* limit flooding of our machine */
2461 if (MaxRcptPerMsg > 0 &&
2462 smtp.sm_nrcpts >= MaxRcptPerMsg)
2464 /* sleep(1); / * slow down? */
2465 usrerr("452 4.5.3 Too many recipients");
2469 if (e->e_sendmode != SM_DELIVER
2471 && (NotFirstDelivery || SM_DM_ONE != e->e_sendmode)
2472 #endif /* _FFR_DM_ONE */
2474 e->e_flags |= EF_VRFYONLY;
2478 ** If the filter will be deleting recipients,
2479 ** don't expand them at RCPT time (in the call
2480 ** to recipient()). If they are expanded, it
2481 ** is impossible for removefromlist() to figure
2482 ** out the expanded members of the original
2483 ** recipient and mark them as QS_DONTSEND.
2486 if (milter_can_delrcpts())
2487 e->e_flags |= EF_VRFYONLY;
2490 p = skipword(p, "to");
2493 macdefine(&e->e_macro, A_PERM,
2494 macid("{addr_type}"), "e r");
2495 a = parseaddr(p, NULLADDR, RF_COPYALL, ' ', &delimptr,
2497 macdefine(&e->e_macro, A_PERM,
2498 macid("{addr_type}"), NULL);
2503 usrerr("501 5.0.0 Missing recipient");
2507 if (delimptr != NULL && *delimptr != '\0')
2510 /* put resulting triple from parseaddr() into macros */
2511 if (a->q_mailer != NULL)
2512 macdefine(&e->e_macro, A_PERM,
2513 macid("{rcpt_mailer}"),
2514 a->q_mailer->m_name);
2516 macdefine(&e->e_macro, A_PERM,
2517 macid("{rcpt_mailer}"), NULL);
2518 if (a->q_host != NULL)
2519 macdefine(&e->e_macro, A_PERM,
2520 macid("{rcpt_host}"), a->q_host);
2522 macdefine(&e->e_macro, A_PERM,
2523 macid("{rcpt_host}"), "localhost");
2524 if (a->q_user != NULL)
2525 macdefine(&e->e_macro, A_PERM,
2526 macid("{rcpt_addr}"), a->q_user);
2528 macdefine(&e->e_macro, A_PERM,
2529 macid("{rcpt_addr}"), NULL);
2533 /* now parse ESMTP arguments */
2538 while (p != NULL && *p != '\0')
2544 /* locate the beginning of the keyword */
2550 /* skip to the value portion */
2551 while ((isascii(*p) && isalnum(*p)) || *p == '-')
2559 /* skip to the end of the value */
2560 while (*p != '\0' && *p != ' ' &&
2561 !(isascii(*p) && iscntrl(*p)) &&
2570 sm_dprintf("RCPT: got arg %s=\"%s\"\n", kp,
2571 vp == NULL ? "<null>" : vp);
2573 rcpt_esmtp_args(a, kp, vp, e, features);
2577 if (argno >= MAXSMTPARGS - 1)
2578 usrerr("501 5.5.4 Too many parameters");
2586 /* do config file checking of the recipient */
2587 macdefine(&e->e_macro, A_PERM,
2588 macid("{addr_type}"), "e r");
2589 if (rscheck("check_rcpt", addr,
2590 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2591 NULL, e->e_id) != EX_OK ||
2594 macdefine(&e->e_macro, A_PERM,
2595 macid("{addr_type}"), NULL);
2597 /* If discarding, don't bother to verify user */
2598 if (bitset(EF_DISCARD, e->e_flags))
2599 a->q_state = QS_VERIFIED;
2602 if (smtp.sm_milterlist && smtp.sm_milterize &&
2603 !bitset(EF_DISCARD, e->e_flags))
2608 response = milter_envrcpt(args, e, &state);
2613 macdefine(&e->e_macro, A_PERM,
2614 macid("{rcpt_mailer}"), NULL);
2615 macdefine(&e->e_macro, A_PERM,
2616 macid("{rcpt_host}"), NULL);
2617 macdefine(&e->e_macro, A_PERM,
2618 macid("{rcpt_addr}"), NULL);
2619 macdefine(&e->e_macro, A_PERM,
2620 macid("{dsn_notify}"), NULL);
2624 /* save in recipient list after ESMTP mods */
2625 a = recipient(a, &e->e_sendqueue, 0, e);
2629 /* no errors during parsing, but might be a duplicate */
2630 e->e_to = a->q_paddr;
2631 if (!QS_IS_BADADDR(a->q_state))
2633 if (smtp.sm_nrcpts == 0)
2635 message("250 2.1.5 Recipient ok%s",
2636 QS_IS_QUEUEUP(a->q_state) ?
2637 " (will queue)" : "");
2642 /* punt -- should keep message in ADDRESS.... */
2643 usrerr("550 5.1.1 Addressee unknown");
2652 SM_EXCEPT(exc, "[!F]*")
2654 /* An exception occurred while processing RCPT */
2655 e->e_flags &= ~(EF_FATALERRS|EF_PM_NOTIFY);
2662 case CMDDATA: /* data -- text of mail */
2664 if (!smtp_data(&smtp, e))
2668 case CMDRSET: /* rset -- reset state */
2670 message("451 4.0.0 Test failure");
2672 message("250 2.0.0 Reset state");
2673 CLEAR_STATE(cmdbuf);
2676 case CMDVRFY: /* vrfy -- verify address */
2677 case CMDEXPN: /* expn -- expand address */
2678 vrfy = c->cmd_code == CMDVRFY;
2679 DELAY_CONN(vrfy ? "VRFY" : "EXPN");
2683 sm_syslog(LOG_INFO, e->e_id,
2684 "SMTP %s command (%.100s) from %s tempfailed (due to previous checks)",
2685 vrfy ? "VRFY" : "EXPN",
2688 /* RFC 821 doesn't allow 4xy reply code */
2689 usrerr("550 5.7.1 Please try again later");
2692 wt = checksmtpattack(&n_verifies, MAXVRFYCOMMANDS,
2693 false, vrfy ? "VRFY" : "EXPN", e);
2695 previous = curtime();
2696 if ((vrfy && bitset(PRIV_NOVRFY, PrivacyFlags)) ||
2697 (!vrfy && !bitset(SRV_OFFER_EXPN, features)))
2700 message("252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)");
2702 message("502 5.7.0 Sorry, we do not allow this operation");
2704 sm_syslog(LOG_INFO, e->e_id,
2705 "%s: %s [rejected]",
2707 shortenstring(inp, MAXSHORTSTR));
2710 else if (!gothello &&
2711 bitset(vrfy ? PRIV_NEEDVRFYHELO : PRIV_NEEDEXPNHELO,
2714 usrerr("503 5.0.0 I demand that you introduce yourself first");
2720 sm_syslog(LOG_INFO, e->e_id, "%s: %s",
2722 shortenstring(inp, MAXSHORTSTR));
2728 e->e_flags |= EF_VRFYONLY;
2729 while (*p != '\0' && isascii(*p) && isspace(*p))
2733 usrerr("501 5.5.2 Argument required");
2737 /* do config file checking of the address */
2738 if (rscheck(vrfy ? "check_vrfy" : "check_expn",
2739 p, NULL, e, RSF_RMCOMM,
2740 3, NULL, NOQID) != EX_OK ||
2742 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2743 (void) sendtolist(p, NULLADDR, &vrfyqueue, 0, e);
2749 t = wt - (curtime() - previous);
2754 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2755 if (vrfyqueue == NULL)
2757 usrerr("554 5.5.2 Nothing to %s", vrfy ? "VRFY" : "EXPN");
2759 while (vrfyqueue != NULL)
2761 if (!QS_IS_UNDELIVERED(vrfyqueue->q_state))
2763 vrfyqueue = vrfyqueue->q_next;
2767 /* see if there is more in the vrfy list */
2769 while ((a = a->q_next) != NULL &&
2770 (!QS_IS_UNDELIVERED(a->q_state)))
2772 printvrfyaddr(vrfyqueue, a == NULL, vrfy);
2776 SM_EXCEPT(exc, "[!F]*")
2779 ** An exception occurred while processing VRFY/EXPN
2788 case CMDETRN: /* etrn -- force queue flush */
2791 /* Don't leak queue information via debug flags */
2792 if (!bitset(SRV_OFFER_ETRN, features) || UseMSP ||
2793 (RealUid != 0 && RealUid != TrustedUid &&
2796 /* different message for MSA ? */
2797 message("502 5.7.0 Sorry, we do not allow this operation");
2799 sm_syslog(LOG_INFO, e->e_id,
2800 "%s: %s [rejected]",
2802 shortenstring(inp, MAXSHORTSTR));
2808 sm_syslog(LOG_INFO, e->e_id,
2809 "SMTP ETRN command (%.100s) from %s tempfailed (due to previous checks)",
2811 usrerr(MSG_TEMPFAIL);
2817 usrerr("500 5.5.2 Parameter required");
2821 /* crude way to avoid denial-of-service attacks */
2822 STOP_IF_ATTACK(checksmtpattack(&n_etrn, MAXETRNCOMMANDS,
2826 ** Do config file checking of the parameter.
2827 ** Even though we have srv_features now, we still
2828 ** need this ruleset because the former is called
2829 ** when the connection has been established, while
2830 ** this ruleset is called when the command is
2831 ** actually issued and therefore has all information
2832 ** available to make a decision.
2835 if (rscheck("check_etrn", p, NULL, e,
2836 RSF_RMCOMM, 3, NULL, NOQID) != EX_OK ||
2841 sm_syslog(LOG_INFO, e->e_id,
2842 "%s: ETRN %s", CurSmtpClient,
2843 shortenstring(p, MAXSHORTSTR));
2851 qgrp = name2qid(id);
2852 if (!ISVALIDQGRP(qgrp))
2854 usrerr("459 4.5.4 Queue %s unknown",
2858 for (i = 0; i < NumQueue && Queue[i] != NULL;
2860 Queue[i]->qg_nextrun = (time_t) -1;
2861 Queue[qgrp]->qg_nextrun = 0;
2862 ok = run_work_group(Queue[qgrp]->qg_wgrp,
2863 RWG_FORK|RWG_FORCE);
2864 if (ok && Errors == 0)
2865 message("250 2.0.0 Queuing for queue group %s started", id);
2874 new = (QUEUE_CHAR *) sm_malloc(sizeof(QUEUE_CHAR));
2877 syserr("500 5.5.0 ETRN out of memory");
2880 new->queue_match = id;
2881 new->queue_negate = false;
2882 new->queue_next = NULL;
2883 QueueLimitRecipient = new;
2884 ok = runqueue(true, false, false, true);
2885 sm_free(QueueLimitRecipient); /* XXX */
2886 QueueLimitRecipient = NULL;
2887 if (ok && Errors == 0)
2888 message("250 2.0.0 Queuing for node %s started", p);
2891 case CMDHELP: /* help -- give user info */
2896 case CMDNOOP: /* noop -- do nothing */
2898 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
2900 message("250 2.0.0 OK");
2903 case CMDQUIT: /* quit -- leave mail */
2904 message("221 2.0.0 %s closing connection", MyHostName);
2906 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
2907 #endif /* PIPELINING */
2909 if (smtp.sm_nrcpts > 0)
2910 logundelrcpts(e, "aborted by sender", 9, false);
2912 /* arrange to ignore any current send list */
2913 e->e_sendqueue = NULL;
2916 /* shutdown TLS connection */
2919 (void) endtls(srv_ssl, "server");
2922 #endif /* STARTTLS */
2924 if (authenticating == SASL_IS_AUTH)
2926 sasl_dispose(&conn);
2927 authenticating = SASL_NOT_AUTH;
2928 /* XXX sasl_done(); this is a child */
2933 /* avoid future 050 messages */
2937 /* close out milter filters */
2941 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
2943 e->e_flags &= ~EF_LOGSENDER;
2945 if (lognullconnection && LogLevel > 5 &&
2950 d = macvalue(macid("{daemon_name}"), e);
2955 ** even though this id is "bogus", it makes
2956 ** it simpler to "grep" related events, e.g.,
2957 ** timeouts for the same connection.
2960 sm_syslog(LOG_INFO, e->e_id,
2961 "%s did not issue MAIL/EXPN/VRFY/ETRN during connection to %s",
2966 /* return to handle next connection */
2969 finis(true, true, ExitStat);
2972 /* just to avoid bogus warning from some compilers */
2975 case CMDVERB: /* set verbose mode */
2977 if (!bitset(SRV_OFFER_EXPN, features) ||
2978 !bitset(SRV_OFFER_VERB, features))
2980 /* this would give out the same info */
2981 message("502 5.7.0 Verbose unavailable");
2984 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
2987 set_delivery_mode(SM_DELIVER, e);
2988 message("250 2.0.0 Verbose mode");
2992 case CMDDBGQSHOW: /* show queues */
2993 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2995 printaddr(smioout, e->e_sendqueue, true);
2998 case CMDDBGDEBUG: /* set debug mode */
2999 tTsetup(tTdvect, sizeof tTdvect, "0-99.1");
3001 message("200 2.0.0 Debug set");
3004 #else /* SMTPDEBUG */
3005 case CMDDBGQSHOW: /* show queues */
3006 case CMDDBGDEBUG: /* set debug mode */
3007 #endif /* SMTPDEBUG */
3008 case CMDLOGBOGUS: /* bogus command */
3009 DELAY_CONN("Bogus");
3011 sm_syslog(LOG_CRIT, e->e_id,
3012 "\"%s\" command from %s (%.100s)",
3013 c->cmd_name, CurSmtpClient,
3014 anynet_ntoa(&RealHostAddr));
3017 case CMDERROR: /* unknown command */
3018 #if MAXBADCOMMANDS > 0
3019 if (++n_badcmds > MAXBADCOMMANDS)
3022 message("421 4.7.0 %s Too many bad commands; closing connection",
3025 /* arrange to ignore any current send list */
3026 e->e_sendqueue = NULL;
3029 #endif /* MAXBADCOMMANDS > 0 */
3031 #if MILTER && SMFI_VERSION > 2
3032 if (smtp.sm_milterlist && smtp.sm_milterize &&
3033 !bitset(EF_DISCARD, e->e_flags))
3038 if (MilterLogLevel > 9)
3039 sm_syslog(LOG_INFO, e->e_id,
3040 "Sending \"%s\" to Milter", inp);
3041 response = milter_unknown(inp, e, &state);
3042 MILTER_REPLY("unknown");
3043 if (state == SMFIR_REPLYCODE ||
3044 state == SMFIR_REJECT ||
3045 state == SMFIR_TEMPFAIL ||
3046 state == SMFIR_SHUTDOWN)
3048 /* MILTER_REPLY already gave an error */
3052 #endif /* MILTER && SMFI_VERSION > 2 */
3054 usrerr("500 5.5.1 Command unrecognized: \"%s\"",
3055 shortenstring(inp, MAXSHORTSTR));
3059 DELAY_CONN("Unimpl");
3060 usrerr("502 5.5.1 Command not implemented: \"%s\"",
3061 shortenstring(inp, MAXSHORTSTR));
3065 DELAY_CONN("default");
3067 syserr("500 5.5.0 smtp: unknown code %d", c->cmd_code);
3074 SM_EXCEPT(exc, "[!F]*")
3077 ** The only possible exception is "E:mta.quickabort".
3078 ** There is nothing to do except fall through and loop.
3085 ** SMTP_DATA -- implement the SMTP DATA command.
3088 ** smtp -- status of SMTP connection.
3092 ** true iff SMTP session can continue.
3095 ** possibly sends message.
3115 SmtpPhase = "server DATA";
3116 if (!smtp->sm_gotmail)
3118 usrerr("503 5.0.0 Need MAIL command");
3121 else if (smtp->sm_nrcpts <= 0)
3123 usrerr("503 5.0.0 Need RCPT (recipient)");
3126 (void) sm_snprintf(buf, sizeof buf, "%u", smtp->sm_nrcpts);
3127 if (rscheck("check_data", buf, NULL, e,
3128 RSF_RMCOMM|RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL,
3132 #if MILTER && SMFI_VERSION > 3
3133 if (smtp->sm_milterlist && smtp->sm_milterize &&
3134 !bitset(EF_DISCARD, e->e_flags))
3138 int savelogusrerrs = LogUsrErrs;
3140 response = milter_data_cmd(e, &state);
3143 case SMFIR_REPLYCODE:
3144 if (MilterLogLevel > 3)
3146 sm_syslog(LOG_INFO, e->e_id,
3147 "Milter: cmd=data, reject=%s",
3152 if (strncmp(response, "421 ", 4) == 0
3153 || strncmp(response, "421-", 4) == 0)
3155 e->e_sendqueue = NULL;
3161 if (MilterLogLevel > 3)
3163 sm_syslog(LOG_INFO, e->e_id,
3164 "Milter: cmd=data, reject=550 5.7.1 Command rejected");
3167 usrerr("550 5.7.1 Command rejected");
3171 if (MilterLogLevel > 3)
3172 sm_syslog(LOG_INFO, e->e_id,
3173 "Milter: cmd=data, discard");
3174 e->e_flags |= EF_DISCARD;
3177 case SMFIR_TEMPFAIL:
3178 if (MilterLogLevel > 3)
3180 sm_syslog(LOG_INFO, e->e_id,
3181 "Milter: cmd=data, reject=%s",
3185 usrerr(MSG_TEMPFAIL);
3188 case SMFIR_SHUTDOWN:
3189 if (MilterLogLevel > 3)
3191 sm_syslog(LOG_INFO, e->e_id,
3192 "Milter: cmd=data, reject=421 4.7.0 %s closing connection",
3196 usrerr("421 4.7.0 %s closing connection", MyHostName);
3197 e->e_sendqueue = NULL;
3200 LogUsrErrs = savelogusrerrs;
3201 if (response != NULL)
3202 sm_free(response); /* XXX */
3204 #endif /* MILTER && SMFI_VERSION > 3 */
3206 /* put back discard bit */
3207 if (smtp->sm_discard)
3208 e->e_flags |= EF_DISCARD;
3210 /* check to see if we need to re-expand aliases */
3211 /* also reset QS_BADADDR on already-diagnosted addrs */
3212 doublequeue = false;
3213 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3215 if (QS_IS_VERIFIED(a->q_state) &&
3216 !bitset(EF_DISCARD, e->e_flags))
3218 /* need to re-expand aliases */
3221 if (QS_IS_BADADDR(a->q_state))
3223 /* make this "go away" */
3224 a->q_state = QS_DONTSEND;
3228 /* collect the text of the message */
3229 SmtpPhase = "collect";
3232 collect(InChannel, true, NULL, e, true);
3234 /* redefine message size */
3235 (void) sm_snprintf(buf, sizeof buf, "%ld", e->e_msgsize);
3236 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3239 /* rscheck() will set Errors or EF_DISCARD if it trips */
3240 (void) rscheck("check_eom", buf, NULL, e, RSF_UNSTRUCTURED|RSF_COUNT,
3242 #endif /* _FFR_CHECK_EOM */
3245 milteraccept = true;
3246 if (smtp->sm_milterlist && smtp->sm_milterize &&
3248 !bitset(EF_DISCARD, e->e_flags))
3253 response = milter_data(e, &state);
3256 case SMFIR_REPLYCODE:
3257 if (MilterLogLevel > 3)
3258 sm_syslog(LOG_INFO, e->e_id,
3259 "Milter: data, reject=%s",
3261 milteraccept = false;
3266 milteraccept = false;
3267 if (MilterLogLevel > 3)
3268 sm_syslog(LOG_INFO, e->e_id,
3269 "Milter: data, reject=554 5.7.1 Command rejected");
3270 usrerr("554 5.7.1 Command rejected");
3274 if (MilterLogLevel > 3)
3275 sm_syslog(LOG_INFO, e->e_id,
3276 "Milter: data, discard");
3277 milteraccept = false;
3278 e->e_flags |= EF_DISCARD;
3281 case SMFIR_TEMPFAIL:
3282 if (MilterLogLevel > 3)
3283 sm_syslog(LOG_INFO, e->e_id,
3284 "Milter: data, reject=%s",
3286 milteraccept = false;
3287 usrerr(MSG_TEMPFAIL);
3290 case SMFIR_SHUTDOWN:
3291 if (MilterLogLevel > 3)
3292 sm_syslog(LOG_INFO, e->e_id,
3293 "Milter: data, reject=421 4.7.0 %s closing connection",
3295 milteraccept = false;
3296 usrerr("421 4.7.0 %s closing connection", MyHostName);
3300 if (response != NULL)
3304 /* Milter may have changed message size */
3305 (void) sm_snprintf(buf, sizeof buf, "%ld", e->e_msgsize);
3306 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3308 /* abort message filters that didn't get the body & log msg is OK */
3309 if (smtp->sm_milterlist && smtp->sm_milterize)
3312 if (milteraccept && MilterLogLevel > 9)
3313 sm_syslog(LOG_INFO, e->e_id, "Milter accept: message");
3317 ** If SuperSafe is SAFE_REALLY_POSTMILTER, and we don't have milter or
3318 ** milter accepted message, sync it now
3320 ** XXX This is almost a copy of the code in collect(): put it into
3321 ** a function that is called from both places?
3324 if (milteraccept && SuperSafe == SAFE_REALLY_POSTMILTER)
3327 SM_FILE_T *volatile df;
3331 dfname = queuename(e, DATAFL_LETTER);
3332 if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0
3338 if (save_errno == EEXIST)
3343 if (stat(dfname, &st) < 0)
3346 syserr("@collect: bfcommit(%s): already on disk, size=%ld",
3347 dfname, (long) st.st_size);
3348 dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
3350 dumpfd(dfd, true, true);
3353 dferror(df, "bfcommit", e);
3355 finis(save_errno != EEXIST, true, ExitStat);
3357 else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0)
3359 dferror(df, "sm_io_getinfo", e);
3361 finis(true, true, ExitStat);
3364 else if (fsync(afd) < 0)
3366 dferror(df, "fsync", e);
3368 finis(true, true, ExitStat);
3371 else if (sm_io_close(df, SM_TIME_DEFAULT) < 0)
3373 dferror(df, "sm_io_close", e);
3375 finis(true, true, ExitStat);
3379 /* Now reopen the df file */
3380 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
3381 SM_IO_RDONLY, NULL);
3382 if (e->e_dfp == NULL)
3384 /* we haven't acked receipt yet, so just chuck this */
3385 syserr("@Cannot reopen %s", dfname);
3386 finis(true, true, ExitStat);
3392 /* Check if quarantining stats should be updated */
3393 if (e->e_quarmsg != NULL)
3394 markstats(e, NULL, STATS_QUARANTINE);
3397 ** If a header/body check (header checks or milter)
3398 ** set EF_DISCARD, don't queueup the message --
3399 ** that would lose the EF_DISCARD bit and deliver
3403 if (bitset(EF_DISCARD, e->e_flags))
3404 doublequeue = false;
3406 aborting = Errors > 0;
3407 if (!(aborting || bitset(EF_DISCARD, e->e_flags)) &&
3408 (QueueMode == QM_QUARANTINE || e->e_quarmsg == NULL) &&
3409 !split_by_recipient(e))
3410 aborting = bitset(EF_FATALERRS, e->e_flags);
3414 /* Log who the mail would have gone to */
3415 logundelrcpts(e, e->e_message, 8, false);
3421 /* from now on, we have to operate silently */
3426 ** Clear message, it may contain an error from the SMTP dialogue.
3427 ** This error must not show up in the queue.
3428 ** Some error message should show up, e.g., alias database
3429 ** not available, but others shouldn't, e.g., from check_rcpt.
3432 e->e_message = NULL;
3436 ** Arrange to send to everyone.
3437 ** If sending to multiple people, mail back
3438 ** errors rather than reporting directly.
3439 ** In any case, don't mail back errors for
3440 ** anything that has happened up to
3441 ** now (the other end will do this).
3442 ** Truncate our transcript -- the mail has gotten
3443 ** to us successfully, and if we have
3444 ** to mail this back, it will be easier
3446 ** Then send to everyone.
3447 ** Finally give a reply code. If an error has
3448 ** already been given, don't mail a
3450 ** We goose error returns by clearing error bit.
3453 SmtpPhase = "delivery";
3454 (void) sm_io_setinfo(e->e_xfp, SM_BF_TRUNCATE, NULL);
3458 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
3459 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
3460 #endif /* NAMED_BIND */
3462 for (ee = e; ee != NULL; ee = ee->e_sibling)
3464 /* make sure we actually do delivery */
3465 ee->e_flags &= ~EF_CLRQUEUE;
3467 /* from now on, operate silently */
3468 ee->e_errormode = EM_MAIL;
3472 /* make sure it is in the queue */
3473 queueup(ee, false, true);
3479 /* send to all recipients */
3482 if (SM_DM_ONE == e->e_sendmode)
3484 if (NotFirstDelivery)
3487 e->e_sendmode = SM_QUEUE;
3492 NotFirstDelivery = true;
3495 #endif /* _FFR_DM_ONE */
3501 /* put back id for SMTP logging in putoutmsg() */
3502 oldid = CurEnv->e_id;
3505 /* issue success message */
3507 if (MessageAccept != NULL && *MessageAccept != '\0')
3511 expand(MessageAccept, msg, sizeof msg, e);
3512 message("250 2.0.0 %s", msg);
3515 #endif /* _FFR_MSG_ACCEPT */
3516 message("250 2.0.0 %s Message accepted for delivery", id);
3517 CurEnv->e_id = oldid;
3519 /* if we just queued, poke it */
3522 bool anything_to_send = false;
3525 for (ee = e; ee != NULL; ee = ee->e_sibling)
3527 if (WILL_BE_QUEUED(ee->e_sendmode))
3529 if (shouldqueue(ee->e_msgpriority, ee->e_ctime))
3531 ee->e_sendmode = SM_QUEUE;
3534 else if (QueueMode != QM_QUARANTINE &&
3535 ee->e_quarmsg != NULL)
3537 ee->e_sendmode = SM_QUEUE;
3540 anything_to_send = true;
3542 /* close all the queue files */
3544 if (ee->e_dfp != NULL)
3546 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
3551 if (anything_to_send)
3555 ** XXX if we don't do this, we get 250 twice
3556 ** because it is also flushed in the child.
3559 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3560 #endif /* PIPELINING */
3561 (void) doworklist(e, true, true);
3566 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3568 e->e_flags &= ~EF_LOGSENDER;
3570 /* clean up a bit */
3571 smtp->sm_gotmail = false;
3574 ** Call dropenvelope if and only if the envelope is *not*
3575 ** being processed by the child process forked by doworklist().
3578 if (aborting || bitset(EF_DISCARD, e->e_flags))
3579 dropenvelope(e, true, false);
3582 for (ee = e; ee != NULL; ee = ee->e_sibling)
3585 QueueMode != QM_QUARANTINE &&
3586 ee->e_quarmsg != NULL)
3588 dropenvelope(ee, true, false);
3591 if (WILL_BE_QUEUED(ee->e_sendmode))
3592 dropenvelope(ee, true, false);
3595 sm_rpool_free(e->e_rpool);
3598 ** At this point, e == &MainEnvelope, but if we did splitting,
3599 ** then CurEnv may point to an envelope structure that was just
3600 ** freed with the rpool. So reset CurEnv *before* calling
3605 newenvelope(e, e, sm_rpool_new_x(NULL));
3606 e->e_flags = BlankEnvelope.e_flags;
3608 /* restore connection quarantining */
3609 if (smtp->sm_quarmsg == NULL)
3611 e->e_quarmsg = NULL;
3612 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
3616 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, smtp->sm_quarmsg);
3617 macdefine(&e->e_macro, A_PERM,
3618 macid("{quarantine}"), e->e_quarmsg);
3623 ** LOGUNDELRCPTS -- log undelivered (or all) recipients.
3627 ** msg -- message for Stat=
3628 ** level -- log level.
3629 ** all -- log all recipients.
3635 ** logs undelivered (or all) recipients
3639 logundelrcpts(e, msg, level, all)
3647 if (LogLevel <= level || msg == NULL || *msg == '\0')
3650 /* Clear $h so relay= doesn't get mislogged by logdelivery() */
3651 macdefine(&e->e_macro, A_PERM, 'h', NULL);
3653 /* Log who the mail would have gone to */
3654 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3656 if (!QS_IS_UNDELIVERED(a->q_state) && !all)
3658 e->e_to = a->q_paddr;
3659 logdelivery(NULL, NULL, a->q_status, msg, NULL,
3665 ** CHECKSMTPATTACK -- check for denial-of-service attack by repetition
3668 ** pcounter -- pointer to a counter for this command.
3669 ** maxcount -- maximum value for this counter before we
3671 ** waitnow -- sleep now (in this routine)?
3672 ** cname -- command name for logging.
3673 ** e -- the current envelope.
3677 ** STOP_ATTACK if twice as many commands as allowed and
3681 ** Slows down if we seem to be under attack.
3685 checksmtpattack(pcounter, maxcount, waitnow, cname, e)
3686 volatile unsigned int *pcounter;
3687 unsigned int maxcount;
3692 if (maxcount <= 0) /* no limit */
3695 if (++(*pcounter) >= maxcount)
3700 if (*pcounter == maxcount && LogLevel > 5)
3702 sm_syslog(LOG_INFO, e->e_id,
3703 "%s: possible SMTP attack: command=%.40s, count=%u",
3704 CurSmtpClient, cname, *pcounter);
3706 shift = *pcounter - maxcount;
3708 if (shift > MAXSHIFT || s >= MAXTIMEOUT || s <= 0)
3711 #define IS_ATTACK(s) ((MaxChildren > 0 && *pcounter >= maxcount * 2) \
3712 ? STOP_ATTACK : (time_t) s)
3714 /* sleep at least 1 second before returning */
3715 (void) sleep(*pcounter / maxcount);
3716 s -= *pcounter / maxcount;
3717 if (s >= MAXTIMEOUT || s < 0)
3719 if (waitnow && s > 0)
3722 return IS_ATTACK(0);
3724 return IS_ATTACK(s);
3729 ** SETUP_SMTPD_IO -- setup I/O fd correctly for the SMTP server
3738 ** may change I/O fd.
3744 int inchfd, outchfd, outfd;
3746 inchfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
3747 outchfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
3748 outfd = sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL);
3749 if (outchfd != outfd)
3751 /* arrange for debugging output to go to remote host */
3752 (void) dup2(outchfd, outfd);
3756 ** if InChannel and OutChannel are stdin/stdout
3757 ** and connected to ttys
3758 ** and fcntl(STDIN, F_SETFL, O_NONBLOCKING) also changes STDOUT,
3759 ** then "chain" them together.
3762 if (inchfd == STDIN_FILENO && outchfd == STDOUT_FILENO &&
3763 isatty(inchfd) && isatty(outchfd))
3765 int inmode, outmode;
3767 inmode = fcntl(inchfd, F_GETFL, 0);
3771 sm_syslog(LOG_INFO, NOQID,
3772 "fcntl(inchfd, F_GETFL) failed: %s",
3773 sm_errstring(errno));
3776 outmode = fcntl(outchfd, F_GETFL, 0);
3780 sm_syslog(LOG_INFO, NOQID,
3781 "fcntl(outchfd, F_GETFL) failed: %s",
3782 sm_errstring(errno));
3785 if (bitset(O_NONBLOCK, inmode) ||
3786 bitset(O_NONBLOCK, outmode) ||
3787 fcntl(inchfd, F_SETFL, inmode | O_NONBLOCK) == -1)
3789 outmode = fcntl(outchfd, F_GETFL, 0);
3790 if (outmode != -1 && bitset(O_NONBLOCK, outmode))
3792 /* changing InChannel also changes OutChannel */
3793 sm_io_automode(OutChannel, InChannel);
3794 if (tTd(97, 4) && LogLevel > 9)
3795 sm_syslog(LOG_INFO, NOQID,
3796 "set automode for I (%d)/O (%d) in SMTP server",
3800 /* undo change of inchfd */
3801 (void) fcntl(inchfd, F_SETFL, inmode);
3805 ** SKIPWORD -- skip a fixed word.
3808 ** p -- place to start looking.
3809 ** w -- word to skip.
3816 ** clobbers the p data area.
3821 register char *volatile p;
3827 /* find beginning of word */
3831 /* find end of word */
3832 while (*p != '\0' && *p != ':' && !(isascii(*p) && isspace(*p)))
3834 while (isascii(*p) && isspace(*p))
3839 usrerr("501 5.5.2 Syntax error in parameters scanning \"%s\"",
3840 shortenstring(firstp, MAXSHORTSTR));
3849 /* see if the input word matches desired word */
3850 if (sm_strcasecmp(q, w))
3857 ** MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
3860 ** kp -- the parameter key.
3861 ** vp -- the value of that parameter.
3862 ** e -- the envelope.
3863 ** features -- current server features
3870 mail_esmtp_args(kp, vp, e, features)
3874 unsigned int features;
3876 if (sm_strcasecmp(kp, "size") == 0)
3880 usrerr("501 5.5.2 SIZE requires a value");
3883 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), vp);
3885 e->e_msgsize = strtol(vp, (char **) NULL, 10);
3886 if (e->e_msgsize == LONG_MAX && errno == ERANGE)
3888 usrerr("552 5.2.3 Message size exceeds maximum value");
3891 if (e->e_msgsize < 0)
3893 usrerr("552 5.2.3 Message size invalid");
3897 else if (sm_strcasecmp(kp, "body") == 0)
3901 usrerr("501 5.5.2 BODY requires a value");
3904 else if (sm_strcasecmp(vp, "8bitmime") == 0)
3906 SevenBitInput = false;
3908 else if (sm_strcasecmp(vp, "7bit") == 0)
3910 SevenBitInput = true;
3914 usrerr("501 5.5.4 Unknown BODY type %s", vp);
3917 e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, vp);
3919 else if (sm_strcasecmp(kp, "envid") == 0)
3921 if (!bitset(SRV_OFFER_DSN, features))
3923 usrerr("504 5.7.0 Sorry, ENVID not supported, we do not allow DSN");
3928 usrerr("501 5.5.2 ENVID requires a value");
3933 usrerr("501 5.5.4 Syntax error in ENVID parameter value");
3936 if (e->e_envid != NULL)
3938 usrerr("501 5.5.0 Duplicate ENVID parameter");
3941 e->e_envid = sm_rpool_strdup_x(e->e_rpool, vp);
3942 macdefine(&e->e_macro, A_PERM,
3943 macid("{dsn_envid}"), e->e_envid);
3945 else if (sm_strcasecmp(kp, "ret") == 0)
3947 if (!bitset(SRV_OFFER_DSN, features))
3949 usrerr("504 5.7.0 Sorry, RET not supported, we do not allow DSN");
3954 usrerr("501 5.5.2 RET requires a value");
3957 if (bitset(EF_RET_PARAM, e->e_flags))
3959 usrerr("501 5.5.0 Duplicate RET parameter");
3962 e->e_flags |= EF_RET_PARAM;
3963 if (sm_strcasecmp(vp, "hdrs") == 0)
3964 e->e_flags |= EF_NO_BODY_RETN;
3965 else if (sm_strcasecmp(vp, "full") != 0)
3967 usrerr("501 5.5.2 Bad argument \"%s\" to RET", vp);
3970 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), vp);
3973 else if (sm_strcasecmp(kp, "auth") == 0)
3977 char *auth_param; /* the value of the AUTH=x */
3978 bool saveQuickAbort = QuickAbort;
3979 bool saveSuprErrs = SuprErrs;
3980 bool saveExitStat = ExitStat;
3984 usrerr("501 5.5.2 AUTH= requires a value");
3987 if (e->e_auth_param != NULL)
3989 usrerr("501 5.5.0 Duplicate AUTH parameter");
3992 if ((q = strchr(vp, ' ')) != NULL)
3995 len = strlen(vp) + 1;
3996 auth_param = xalloc(len);
3997 (void) sm_strlcpy(auth_param, vp, len);
3998 if (!xtextok(auth_param))
4000 usrerr("501 5.5.4 Syntax error in AUTH parameter value");
4001 /* just a warning? */
4005 /* XXX define this always or only if trusted? */
4006 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"),
4010 ** call Strust_auth to find out whether
4011 ** auth_param is acceptable (trusted)
4012 ** we shouldn't trust it if not authenticated
4013 ** (required by RFC, leave it to ruleset?)
4018 if (strcmp(auth_param, "<>") != 0 &&
4019 (rscheck("trust_auth", auth_param, NULL, e, RSF_RMCOMM,
4020 9, NULL, NOQID) != EX_OK || Errors > 0))
4024 q = e->e_auth_param;
4025 sm_dprintf("auth=\"%.100s\" not trusted user=\"%.100s\"\n",
4026 auth_param, (q == NULL) ? "" : q);
4030 e->e_auth_param = "<>";
4031 # if _FFR_AUTH_PASSING
4032 macdefine(&BlankEnvelope.e_macro, A_PERM,
4033 macid("{auth_author}"), NULL);
4034 # endif /* _FFR_AUTH_PASSING */
4039 sm_dprintf("auth=\"%.100s\" trusted\n", auth_param);
4040 e->e_auth_param = sm_rpool_strdup_x(e->e_rpool,
4043 sm_free(auth_param); /* XXX */
4047 QuickAbort = saveQuickAbort;
4048 SuprErrs = saveSuprErrs;
4049 ExitStat = saveExitStat;
4052 #define PRTCHAR(c) ((isascii(c) && isprint(c)) ? (c) : '?')
4055 ** "by" is only accepted if DeliverByMin >= 0.
4056 ** We maybe could add this to the list of server_features.
4059 else if (sm_strcasecmp(kp, "by") == 0 && DeliverByMin >= 0)
4065 usrerr("501 5.5.2 BY= requires a value");
4069 e->e_deliver_by = strtol(vp, &s, 10);
4070 if (e->e_deliver_by == LONG_MIN ||
4071 e->e_deliver_by == LONG_MAX ||
4072 e->e_deliver_by > 999999999l ||
4073 e->e_deliver_by < -999999999l)
4075 usrerr("501 5.5.2 BY=%s out of range", vp);
4078 if (s == NULL || *s != ';')
4080 usrerr("501 5.5.2 BY= missing ';'");
4084 ++s; /* XXX: spaces allowed? */
4086 switch (tolower(*s))
4089 e->e_dlvr_flag = DLVR_NOTIFY;
4092 e->e_dlvr_flag = DLVR_RETURN;
4093 if (e->e_deliver_by <= 0)
4095 usrerr("501 5.5.4 mode R requires BY time > 0");
4098 if (DeliverByMin > 0 && e->e_deliver_by > 0 &&
4099 e->e_deliver_by < DeliverByMin)
4101 usrerr("555 5.5.2 time %ld less than %ld",
4102 e->e_deliver_by, (long) DeliverByMin);
4107 usrerr("501 5.5.2 illegal by-mode '%c'", PRTCHAR(*s));
4110 ++s; /* XXX: spaces allowed? */
4112 switch (tolower(*s))
4115 e->e_dlvr_flag |= DLVR_TRACE;
4120 usrerr("501 5.5.2 illegal by-trace '%c'", PRTCHAR(*s));
4124 /* XXX: check whether more characters follow? */
4128 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4133 ** RCPT_ESMTP_ARGS -- process ESMTP arguments from RCPT line
4136 ** a -- the address corresponding to the To: parameter.
4137 ** kp -- the parameter key.
4138 ** vp -- the value of that parameter.
4139 ** e -- the envelope.
4140 ** features -- current server features
4147 rcpt_esmtp_args(a, kp, vp, e, features)
4152 unsigned int features;
4154 if (sm_strcasecmp(kp, "notify") == 0)
4158 if (!bitset(SRV_OFFER_DSN, features))
4160 usrerr("504 5.7.0 Sorry, NOTIFY not supported, we do not allow DSN");
4165 usrerr("501 5.5.2 NOTIFY requires a value");
4168 a->q_flags &= ~(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY);
4169 a->q_flags |= QHASNOTIFY;
4170 macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), vp);
4172 if (sm_strcasecmp(vp, "never") == 0)
4174 for (p = vp; p != NULL; vp = p)
4178 s = p = strchr(p, ',');
4181 if (sm_strcasecmp(vp, "success") == 0)
4182 a->q_flags |= QPINGONSUCCESS;
4183 else if (sm_strcasecmp(vp, "failure") == 0)
4184 a->q_flags |= QPINGONFAILURE;
4185 else if (sm_strcasecmp(vp, "delay") == 0)
4186 a->q_flags |= QPINGONDELAY;
4189 usrerr("501 5.5.4 Bad argument \"%s\" to NOTIFY",
4197 else if (sm_strcasecmp(kp, "orcpt") == 0)
4199 if (!bitset(SRV_OFFER_DSN, features))
4201 usrerr("504 5.7.0 Sorry, ORCPT not supported, we do not allow DSN");
4206 usrerr("501 5.5.2 ORCPT requires a value");
4209 if (strchr(vp, ';') == NULL || !xtextok(vp))
4211 usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4214 if (a->q_orcpt != NULL)
4216 usrerr("501 5.5.0 Duplicate ORCPT parameter");
4219 a->q_orcpt = sm_rpool_strdup_x(e->e_rpool, vp);
4223 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4228 ** PRINTVRFYADDR -- print an entry in the verify queue
4231 ** a -- the address to print.
4232 ** last -- set if this is the last one.
4233 ** vrfy -- set if this is a VRFY command.
4239 ** Prints the appropriate 250 codes.
4241 #define OFFF (3 + 1 + 5 + 1) /* offset in fmt: SMTP reply + enh. code */
4244 printvrfyaddr(a, last, vrfy)
4245 register ADDRESS *a;
4251 if (vrfy && a->q_mailer != NULL &&
4252 !bitnset(M_VRFY250, a->q_mailer->m_flags))
4253 (void) sm_strlcpy(fmtbuf, "252", sizeof fmtbuf);
4255 (void) sm_strlcpy(fmtbuf, "250", sizeof fmtbuf);
4256 fmtbuf[3] = last ? ' ' : '-';
4257 (void) sm_strlcpy(&fmtbuf[4], "2.1.5 ", sizeof fmtbuf - 4);
4258 if (a->q_fullname == NULL)
4260 if ((a->q_mailer == NULL ||
4261 a->q_mailer->m_addrtype == NULL ||
4262 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4263 strchr(a->q_user, '@') == NULL)
4264 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s@%s>",
4265 sizeof fmtbuf - OFFF);
4267 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s>",
4268 sizeof fmtbuf - OFFF);
4269 message(fmtbuf, a->q_user, MyHostName);
4273 if ((a->q_mailer == NULL ||
4274 a->q_mailer->m_addrtype == NULL ||
4275 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4276 strchr(a->q_user, '@') == NULL)
4277 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s@%s>",
4278 sizeof fmtbuf - OFFF);
4280 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s>",
4281 sizeof fmtbuf - OFFF);
4282 message(fmtbuf, a->q_fullname, a->q_user, MyHostName);
4288 ** SASLMECHS -- get list of possible AUTH mechanisms
4291 ** conn -- SASL connection info.
4292 ** mechlist -- output parameter for list of mechanisms.
4299 saslmechs(conn, mechlist)
4303 int len, num, result;
4305 /* "user" is currently unused */
4307 result = sasl_listmech(conn, NULL,
4308 "", " ", "", (const char **) mechlist,
4309 (unsigned int *)&len, &num);
4310 # else /* SASL >= 20000 */
4311 result = sasl_listmech(conn, "user", /* XXX */
4312 "", " ", "", mechlist,
4313 (unsigned int *)&len, (unsigned int *)&num);
4314 # endif /* SASL >= 20000 */
4315 if (result != SASL_OK)
4318 sm_syslog(LOG_WARNING, NOQID,
4319 "AUTH error: listmech=%d, num=%d",
4326 sm_syslog(LOG_INFO, NOQID,
4327 "AUTH: available mech=%s, allowed mech=%s",
4328 *mechlist, AuthMechanisms);
4329 *mechlist = intersect(AuthMechanisms, *mechlist, NULL);
4333 *mechlist = NULL; /* be paranoid... */
4334 if (result == SASL_OK && LogLevel > 9)
4335 sm_syslog(LOG_WARNING, NOQID,
4336 "AUTH warning: no mechanisms");
4343 ** PROXY_POLICY -- define proxy policy for AUTH
4347 ** context -- unused.
4348 ** requested_user -- authorization identity.
4349 ** rlen -- authorization identity length.
4350 ** auth_identity -- authentication identity.
4351 ** alen -- authentication identity length.
4352 ** def_realm -- default user realm.
4353 ** urlen -- user realm length.
4354 ** propctx -- unused.
4360 ** sets {auth_authen} macro.
4364 proxy_policy(conn, context, requested_user, rlen, auth_identity, alen,
4365 def_realm, urlen, propctx)
4368 const char *requested_user;
4370 const char *auth_identity;
4372 const char *def_realm;
4374 struct propctx *propctx;
4376 if (auth_identity == NULL)
4379 macdefine(&BlankEnvelope.e_macro, A_TEMP,
4380 macid("{auth_authen}"), (char *) auth_identity);
4384 # else /* SASL >= 20000 */
4387 ** PROXY_POLICY -- define proxy policy for AUTH
4390 ** context -- unused.
4391 ** auth_identity -- authentication identity.
4392 ** requested_user -- authorization identity.
4393 ** user -- allowed user (output).
4394 ** errstr -- possible error string (output).
4401 proxy_policy(context, auth_identity, requested_user, user, errstr)
4403 const char *auth_identity;
4404 const char *requested_user;
4406 const char **errstr;
4408 if (user == NULL || auth_identity == NULL)
4410 *user = newstr(auth_identity);
4413 # endif /* SASL >= 20000 */
4418 ** INITSRVTLS -- initialize server side TLS
4421 ** tls_ok -- should tls initialization be done?
4427 ** sets tls_ok_srv which is a static variable in this module.
4428 ** Do NOT remove assignments to it!
4438 /* do NOT remove assignment */
4439 tls_ok_srv = inittls(&srv_ctx, TLS_Srv_Opts, true, SrvCertFile,
4440 SrvKeyFile, CACertPath, CACertFile, DHParams);
4443 #endif /* STARTTLS */
4445 ** SRVFEATURES -- get features for SMTP server
4448 ** e -- envelope (should be session context).
4449 ** clientname -- name of client.
4450 ** features -- default features for this invocation.
4456 /* table with options: it uses just one character, how about strings? */
4460 unsigned int srvf_flag;
4461 } srv_feat_table[] =
4463 { 'A', SRV_OFFER_AUTH },
4464 { 'B', SRV_OFFER_VERB },
4465 { 'C', SRV_REQ_SEC },
4466 { 'D', SRV_OFFER_DSN },
4467 { 'E', SRV_OFFER_ETRN },
4468 { 'L', SRV_REQ_AUTH },
4471 { 'N', SRV_NO_PIPE },
4472 # endif /* _FFR_NO_PIPE */
4473 { 'P', SRV_OFFER_PIPE },
4474 #endif /* PIPELINING */
4475 { 'R', SRV_VRFY_CLT }, /* same as V; not documented */
4476 { 'S', SRV_OFFER_TLS },
4477 /* { 'T', SRV_TMP_FAIL }, */
4478 { 'V', SRV_VRFY_CLT },
4479 { 'X', SRV_OFFER_EXPN },
4480 /* { 'Y', SRV_OFFER_VRFY }, */
4485 srvfeatures(e, clientname, features)
4488 unsigned int features;
4492 char pvpbuf[PSBUFSIZE];
4495 r = rscap("srv_features", clientname, "", e, &pvp, pvpbuf,
4499 if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
4501 if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0)
4502 return SRV_TMP_FAIL;
4505 ** General rule (see sendmail.h, d_flags):
4506 ** lower case: required/offered, upper case: Not required/available
4508 ** Since we can change some features per daemon, we have both
4509 ** cases here: turn on/off a feature.
4512 for (i = 1; pvp[i] != NULL; i++)
4518 if ((opt = srv_feat_table[j].srvf_opt) == '\0')
4521 sm_syslog(LOG_WARNING, e->e_id,
4522 "srvfeatures: unknown feature %s",
4528 features &= ~(srv_feat_table[j].srvf_flag);
4531 if (c == tolower(opt))
4533 features |= srv_feat_table[j].srvf_flag;
4543 ** HELP -- implement the HELP command.
4546 ** topic -- the topic we want help for.
4553 ** outputs the help file to message output.
4555 #define HELPVSTR "#vers "
4556 #define HELPVERSION 2
4563 register SM_FILE_T *hf;
4568 long sff = SFF_OPENASROOT|SFF_REGONLY;
4571 static int foundvers = -1;
4572 extern char Version[];
4574 if (DontLockReadFiles)
4576 if (!bitnset(DBS_HELPFILEINUNSAFEDIRPATH, DontBlameSendmail))
4577 sff |= SFF_SAFEDIRPATH;
4579 if (HelpFile == NULL ||
4580 (hf = safefopen(HelpFile, O_RDONLY, 0444, sff)) == NULL)
4584 message("502 5.3.0 Sendmail %s -- HELP not implemented",
4589 if (topic == NULL || *topic == '\0')
4600 len = strlen(topic);
4602 while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof buf) != NULL)
4606 if (foundvers < 0 &&
4607 strncmp(buf, HELPVSTR, strlen(HELPVSTR)) == 0)
4611 if (sm_io_sscanf(buf + strlen(HELPVSTR), "%d",
4617 if (strncmp(buf, topic, len) == 0)
4623 /* print version if no/old vers# in file */
4624 if (foundvers < 2 && !noinfo)
4625 message("214-2.0.0 This is Sendmail version %s", Version);
4627 p = strpbrk(buf, " \t");
4629 p = buf + strlen(buf) - 1;
4635 translate_dollars(p);
4636 expand(p, inp, sizeof inp, e);
4639 message("214-2.0.0 %s", p);
4645 message("504 5.3.0 HELP topic \"%.10s\" unknown", topic);
4647 message("214 2.0.0 End of HELP info");
4649 if (foundvers != 0 && foundvers < HELPVERSION)
4652 sm_syslog(LOG_WARNING, e->e_id,
4653 "%s too old (require version %d)",
4654 HelpFile, HELPVERSION);
4656 /* avoid log next time */
4660 (void) sm_io_close(hf, SM_TIME_DEFAULT);
4665 ** RESET_SASLCONN -- reset SASL connection data
4668 ** conn -- SASL connection context
4669 ** hostname -- host name
4670 ** various connection data
4677 reset_saslconn(sasl_conn_t **conn, char *hostname,
4679 char *remoteip, char *localip,
4680 char *auth_id, sasl_ssf_t * ext_ssf)
4681 # else /* SASL >= 20000 */
4682 struct sockaddr_in *saddr_r, struct sockaddr_in *saddr_l,
4683 sasl_external_properties_t * ext_ssf)
4684 # endif /* SASL >= 20000 */
4690 result = sasl_server_new("smtp", hostname, NULL, NULL, NULL,
4693 /* use empty realm: only works in SASL > 1.5.5 */
4694 result = sasl_server_new("smtp", hostname, "", NULL, 0, conn);
4695 # else /* SASL >= 20000 */
4696 /* use no realm -> realm is set to hostname by SASL lib */
4697 result = sasl_server_new("smtp", hostname, NULL, NULL, 0,
4699 # endif /* SASL >= 20000 */
4700 if (result != SASL_OK)
4704 # if NETINET || NETINET6
4705 if (remoteip != NULL && *remoteip != '\0')
4706 result = sasl_setprop(*conn, SASL_IPREMOTEPORT, remoteip);
4707 if (result != SASL_OK)
4710 if (localip != NULL && *localip != '\0')
4711 result = sasl_setprop(*conn, SASL_IPLOCALPORT, localip);
4712 if (result != SASL_OK)
4714 # endif /* NETINET || NETINET6 */
4716 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
4717 if (result != SASL_OK)
4720 result = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, auth_id);
4721 if (result != SASL_OK)
4723 # else /* SASL >= 20000 */
4725 if (saddr_r != NULL)
4726 result = sasl_setprop(*conn, SASL_IP_REMOTE, saddr_r);
4727 if (result != SASL_OK)
4730 if (saddr_l != NULL)
4731 result = sasl_setprop(*conn, SASL_IP_LOCAL, saddr_l);
4732 if (result != SASL_OK)
4734 # endif /* NETINET */
4736 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
4737 if (result != SASL_OK)
4739 # endif /* SASL >= 20000 */