2 * Copyright (c) 1998-2010, 2012, 2013 Proofpoint, 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.1016 2013-11-22 20:51:56 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 <openssl/err.h>
34 # include <sysexits.h>
36 static SSL_CTX *srv_ctx = NULL; /* TLS server context */
37 static SSL *srv_ssl = NULL; /* per connection context */
39 static bool tls_ok_srv = false;
41 # define TLS_VERIFY_CLIENT() tls_set_verify(srv_ctx, srv_ssl, \
42 bitset(SRV_VRFY_CLT, features))
46 static bool NotFirstDelivery = false;
47 #endif /* _FFR_DM_ONE */
50 #define SRV_NONE 0x0000 /* none... */
51 #define SRV_OFFER_TLS 0x0001 /* offer STARTTLS */
52 #define SRV_VRFY_CLT 0x0002 /* request a cert */
53 #define SRV_OFFER_AUTH 0x0004 /* offer AUTH */
54 #define SRV_OFFER_ETRN 0x0008 /* offer ETRN */
55 #define SRV_OFFER_VRFY 0x0010 /* offer VRFY (not yet used) */
56 #define SRV_OFFER_EXPN 0x0020 /* offer EXPN */
57 #define SRV_OFFER_VERB 0x0040 /* offer VERB */
58 #define SRV_OFFER_DSN 0x0080 /* offer DSN */
60 # define SRV_OFFER_PIPE 0x0100 /* offer PIPELINING */
62 # define SRV_NO_PIPE 0x0200 /* disable PIPELINING, sleep if used */
63 # endif /* _FFR_NO_PIPE */
64 #endif /* PIPELINING */
65 #define SRV_REQ_AUTH 0x0400 /* require AUTH */
66 #define SRV_REQ_SEC 0x0800 /* require security - equiv to AuthOptions=p */
67 #define SRV_TMP_FAIL 0x1000 /* ruleset caused a temporary failure */
69 static unsigned int srvfeatures __P((ENVELOPE *, char *, unsigned int));
71 #define STOP_ATTACK ((time_t) -1)
72 static time_t checksmtpattack __P((volatile unsigned int *, unsigned int,
73 bool, char *, ENVELOPE *));
74 static void printvrfyaddr __P((ADDRESS *, bool, bool));
75 static char *skipword __P((char *volatile, char *));
76 static void setup_smtpd_io __P((void));
80 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
81 char *_remoteip, char *_localip,
82 char *_auth_id, sasl_ssf_t *_ext_ssf));
84 # define RESET_SASLCONN \
87 result = reset_saslconn(&conn, AuthRealm, remoteip, \
88 localip, auth_id, &ext_ssf); \
89 if (result != SASL_OK) \
93 # else /* SASL >= 20000 */
94 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
95 struct sockaddr_in *_saddr_r,
96 struct sockaddr_in *_saddr_l,
97 sasl_external_properties_t *_ext_ssf));
98 # define RESET_SASLCONN \
101 result = reset_saslconn(&conn, AuthRealm, &saddr_r, \
102 &saddr_l, &ext_ssf); \
103 if (result != SASL_OK) \
107 # endif /* SASL >= 20000 */
110 extern ENVELOPE BlankEnvelope;
116 (void) sm_snprintf(buf, sizeof(buf), "%d", \
117 BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle \
118 ? n_badrcpts - 1 : n_badrcpts); \
119 macdefine(&e->e_macro, A_TEMP, macid("{nbadrcpts}"), buf); \
122 #define SKIP_SPACE(s) while (isascii(*s) && isspace(*s)) \
126 ** PARSE_ESMTP_ARGS -- parse EMSTP arguments (for MAIL, RCPT)
130 ** addr_st -- address (RCPT only)
132 ** delimptr -- current position in read buffer
133 ** which -- MAIL/RCPT
134 ** args -- arguments (output)
135 ** esmtp_args -- function to process a single ESMTP argument
142 parse_esmtp_args(e, addr_st, p, delimptr, which, args, esmtp_args)
149 esmtp_args_F esmtp_args;
157 while (p != NULL && *p != '\0')
163 /* locate the beginning of the keyword */
169 /* skip to the value portion */
170 while ((isascii(*p) && isalnum(*p)) || *p == '-')
178 /* skip to the end of the value */
179 while (*p != '\0' && *p != ' ' &&
180 !(isascii(*p) && iscntrl(*p)) &&
189 sm_dprintf("%s: got arg %s=\"%s\"\n", which, kp,
190 vp == NULL ? "<null>" : vp);
192 esmtp_args(addr_st, kp, vp, e);
198 if (argno >= MAXSMTPARGS - 1)
199 usrerr("501 5.5.4 Too many parameters");
208 ** SMTP -- run the SMTP protocol.
211 ** nullserver -- if non-NULL, rejection message for
212 ** (almost) all SMTP commands.
213 ** d_flags -- daemon flags
214 ** e -- the envelope.
220 ** Reads commands from the input channel and processes them.
224 ** Notice: The smtp server doesn't have a session context like the client
225 ** side has (mci). Therefore some data (session oriented) is allocated
226 ** or assigned to the "wrong" structure (esp. STARTTLS, AUTH).
227 ** This should be fixed in a successor version.
232 char *cmd_name; /* command name */
233 int cmd_code; /* internal code, see below */
236 /* values for cmd_code */
237 #define CMDERROR 0 /* bad command */
238 #define CMDMAIL 1 /* mail -- designate sender */
239 #define CMDRCPT 2 /* rcpt -- designate recipient */
240 #define CMDDATA 3 /* data -- send message text */
241 #define CMDRSET 4 /* rset -- reset state */
242 #define CMDVRFY 5 /* vrfy -- verify address */
243 #define CMDEXPN 6 /* expn -- expand address */
244 #define CMDNOOP 7 /* noop -- do nothing */
245 #define CMDQUIT 8 /* quit -- close connection and die */
246 #define CMDHELO 9 /* helo -- be polite */
247 #define CMDHELP 10 /* help -- give usage info */
248 #define CMDEHLO 11 /* ehlo -- extended helo (RFC 1425) */
249 #define CMDETRN 12 /* etrn -- flush queue */
251 # define CMDAUTH 13 /* auth -- SASL authenticate */
254 # define CMDSTLS 14 /* STARTTLS -- start TLS session */
255 #endif /* STARTTLS */
256 /* non-standard commands */
257 #define CMDVERB 17 /* verb -- go into verbose mode */
258 /* unimplemented commands from RFC 821 */
259 #define CMDUNIMPL 19 /* unimplemented rfc821 commands */
260 /* use this to catch and log "door handle" attempts on your system */
261 #define CMDLOGBOGUS 23 /* bogus command that should be logged */
262 /* debugging-only commands, only enabled if SMTPDEBUG is defined */
263 #define CMDDBGQSHOW 24 /* showq -- show send queue */
264 #define CMDDBGDEBUG 25 /* debug -- set debug mode */
267 ** Note: If you change this list, remember to update 'helpfile'
270 static struct cmd CmdTab[] =
285 { "send", CMDUNIMPL },
286 { "saml", CMDUNIMPL },
287 { "soml", CMDUNIMPL },
288 { "turn", CMDUNIMPL },
290 { "auth", CMDAUTH, },
293 { "starttls", CMDSTLS, },
294 #endif /* STARTTLS */
295 /* remaining commands are here only to trap and log attempts to use them */
296 { "showq", CMDDBGQSHOW },
297 { "debug", CMDDBGDEBUG },
298 { "wiz", CMDLOGBOGUS },
303 static char *CurSmtpClient; /* who's at the other end of channel */
305 #ifndef MAXBADCOMMANDS
306 # define MAXBADCOMMANDS 25 /* maximum number of bad commands */
307 #endif /* ! MAXBADCOMMANDS */
308 #ifndef MAXHELOCOMMANDS
309 # define MAXHELOCOMMANDS 3 /* max HELO/EHLO commands before slowdown */
310 #endif /* ! MAXHELOCOMMANDS */
311 #ifndef MAXVRFYCOMMANDS
312 # define MAXVRFYCOMMANDS 6 /* max VRFY/EXPN commands before slowdown */
313 #endif /* ! MAXVRFYCOMMANDS */
314 #ifndef MAXETRNCOMMANDS
315 # define MAXETRNCOMMANDS 8 /* max ETRN commands before slowdown */
316 #endif /* ! MAXETRNCOMMANDS */
318 # define MAXTIMEOUT (4 * 60) /* max timeout for bad commands */
319 #endif /* ! MAXTIMEOUT */
322 ** Maximum shift value to compute timeout for bad commands.
323 ** This introduces an upper limit of 2^MAXSHIFT for the timeout.
328 #endif /* ! MAXSHIFT */
330 ERROR _MAXSHIFT > 31 is invalid
331 #endif /* MAXSHIFT */
334 #if MAXBADCOMMANDS > 0
335 # define STOP_IF_ATTACK(r) do \
337 if ((r) == STOP_ATTACK) \
341 #else /* MAXBADCOMMANDS > 0 */
342 # define STOP_IF_ATTACK(r) r
343 #endif /* MAXBADCOMMANDS > 0 */
347 static SM_DEBUG_T DebugLeakSmtp = SM_DEBUG_INITIALIZER("leak_smtp",
348 "@(#)$Debug: leak_smtp - trace memory leaks during SMTP processing $");
349 #endif /* SM_HEAP_CHECK */
353 bool sm_gotmail; /* mail command received */
354 unsigned int sm_nrcpts; /* number of successful RCPT commands */
358 bool sm_milterlist; /* any filters in the list? */
359 milters_T sm_milters;
361 /* e_nrcpts from envelope before recipient() call */
362 unsigned int sm_e_nrcpts_orig;
364 char *sm_quarmsg; /* carry quarantining across messages */
367 static bool smtp_data __P((SMTP_T *, ENVELOPE *));
369 #define MSG_TEMPFAIL "451 4.3.2 Please try again later"
372 # define MILTER_ABORT(e) milter_abort((e))
374 # define MILTER_REPLY(str) \
376 int savelogusrerrs = LogUsrErrs; \
378 milter_cmd_fail = true; \
381 case SMFIR_SHUTDOWN: \
382 if (MilterLogLevel > 3) \
384 sm_syslog(LOG_INFO, e->e_id, \
385 "Milter: %s=%s, reject=421, errormode=4", \
387 LogUsrErrs = false; \
390 bool tsave = QuickAbort; \
392 QuickAbort = false; \
393 usrerr("421 4.3.0 closing connection"); \
394 QuickAbort = tsave; \
395 e->e_sendqueue = NULL; \
399 case SMFIR_REPLYCODE: \
400 if (MilterLogLevel > 3) \
402 sm_syslog(LOG_INFO, e->e_id, \
403 "Milter: %s=%s, reject=%s", \
404 str, addr, response); \
405 LogUsrErrs = false; \
407 if (strncmp(response, "421 ", 4) == 0 \
408 || strncmp(response, "421-", 4) == 0) \
410 bool tsave = QuickAbort; \
412 QuickAbort = false; \
414 QuickAbort = tsave; \
415 e->e_sendqueue = NULL; \
423 if (MilterLogLevel > 3) \
425 sm_syslog(LOG_INFO, e->e_id, \
426 "Milter: %s=%s, reject=550 5.7.1 Command rejected", \
428 LogUsrErrs = false; \
430 usrerr("550 5.7.1 Command rejected"); \
433 case SMFIR_DISCARD: \
434 if (MilterLogLevel > 3) \
435 sm_syslog(LOG_INFO, e->e_id, \
436 "Milter: %s=%s, discard", \
438 e->e_flags |= EF_DISCARD; \
439 milter_cmd_fail = false; \
442 case SMFIR_TEMPFAIL: \
443 if (MilterLogLevel > 3) \
445 sm_syslog(LOG_INFO, e->e_id, \
446 "Milter: %s=%s, reject=%s", \
447 str, addr, MSG_TEMPFAIL); \
448 LogUsrErrs = false; \
450 usrerr(MSG_TEMPFAIL); \
453 milter_cmd_fail = false; \
456 LogUsrErrs = savelogusrerrs; \
457 if (response != NULL) \
458 sm_free(response); /* XXX */ \
462 # define MILTER_ABORT(e)
465 /* clear all SMTP state (for HELO/EHLO/RSET) */
466 #define CLEAR_STATE(cmd) \
469 /* abort milter filters */ \
472 if (smtp.sm_nrcpts > 0) \
474 logundelrcpts(e, cmd, 10, false); \
475 smtp.sm_nrcpts = 0; \
476 macdefine(&e->e_macro, A_PERM, \
477 macid("{nrcpts}"), "0"); \
480 e->e_sendqueue = NULL; \
481 e->e_flags |= EF_CLRQUEUE; \
484 sm_dprintf("CLEAR_STATE: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",\
485 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);\
486 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) \
487 logsender(e, NULL); \
488 e->e_flags &= ~EF_LOGSENDER; \
490 /* clean up a bit */ \
491 smtp.sm_gotmail = false; \
493 (void) dropenvelope(e, true, false); \
494 sm_rpool_free(e->e_rpool); \
495 e = newenvelope(e, CurEnv, sm_rpool_new_x(NULL)); \
497 e->e_features = features; \
499 /* put back discard bit */ \
500 if (smtp.sm_discard) \
501 e->e_flags |= EF_DISCARD; \
503 /* restore connection quarantining */ \
504 if (smtp.sm_quarmsg == NULL) \
506 e->e_quarmsg = NULL; \
507 macdefine(&e->e_macro, A_PERM, \
508 macid("{quarantine}"), ""); \
512 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \
514 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \
519 /* sleep to flatten out connection load */
520 #define MIN_DELAY_LOG 15 /* wait before logging this again */
522 /* is it worth setting the process title for 1s? */
523 #define DELAY_CONN(cmd) \
524 if (DelayLA > 0 && (CurrentLA = getla()) >= DelayLA) \
528 sm_setproctitle(true, e, \
529 "%s: %s: delaying %s: load average: %d", \
530 qid_printname(e), CurSmtpClient, \
532 if (LogLevel > 8 && (dnow = curtime()) > log_delay) \
534 sm_syslog(LOG_INFO, e->e_id, \
535 "delaying=%s, load average=%d >= %d", \
536 cmd, CurrentLA, DelayLA); \
537 log_delay = dnow + MIN_DELAY_LOG; \
540 sm_setproctitle(true, e, "%s %s: %.80s", \
541 qid_printname(e), CurSmtpClient, inp); \
544 static bool SevenBitInput_Saved; /* saved version of SevenBitInput */
547 smtp(nullserver, d_flags, e)
548 char *volatile nullserver;
550 register ENVELOPE *volatile e;
552 register char *volatile p;
553 register struct cmd *volatile c = NULL;
555 auto ADDRESS *vrfyqueue;
557 volatile bool gothello; /* helo command received */
558 bool vrfy; /* set if this is a vrfy command */
559 char *volatile protocol; /* sending protocol */
560 char *volatile sendinghost; /* sending hostname */
561 char *volatile peerhostname; /* name of SMTP peer or "localhost" */
564 volatile unsigned int n_badcmds = 0; /* count of bad commands */
565 volatile unsigned int n_badrcpts = 0; /* number of rejected RCPT */
566 volatile unsigned int n_verifies = 0; /* count of VRFY/EXPN */
567 volatile unsigned int n_etrn = 0; /* count of ETRN */
568 volatile unsigned int n_noop = 0; /* count of NOOP/VERB/etc */
569 volatile unsigned int n_helo = 0; /* count of HELO/EHLO */
572 volatile bool tempfail = false;
573 volatile time_t wt; /* timeout after too many commands */
574 volatile time_t previous; /* time after checksmtpattack() */
575 volatile bool lognullconnection = true;
579 char *greetcode = "220";
580 char *hostname; /* my hostname ($j) */
582 char *args[MAXSMTPARGS];
583 char inp[MAXINPLINE];
584 #if MAXINPLINE < MAXLINE
585 ERROR _MAXINPLINE must NOT be less than _MAXLINE: MAXINPLINE < MAXLINE
586 #endif /* MAXINPLINE < MAXLINE */
587 char cmdbuf[MAXLINE];
590 volatile bool sasl_ok;
591 volatile unsigned int n_auth = 0; /* count of AUTH commands */
594 volatile int authenticating;
598 char *auth_id = NULL;
601 char localip[60], remoteip[60];
602 # else /* SASL >= 20000 */
605 sasl_external_properties_t ext_ssf;
606 struct sockaddr_in saddr_l;
607 struct sockaddr_in saddr_r;
608 # endif /* SASL >= 20000 */
609 sasl_security_properties_t ssp;
611 unsigned int inlen, out2len;
613 char *volatile auth_type;
615 volatile unsigned int n_mechs;
622 volatile bool tls_active = false;
623 volatile bool smtps = bitnset(D_SMTPS, d_flags);
627 #endif /* STARTTLS */
628 volatile unsigned int features;
632 # endif /* _FFR_NO_PIPE */
633 #endif /* PIPELINING */
634 volatile time_t log_delay = (time_t) 0;
636 volatile bool milter_cmd_done, milter_cmd_safe;
637 volatile bool milter_rcpt_added, milter_cmd_fail;
639 # define p_addr_st &addr_st
641 # define p_addr_st NULL
644 #if _FFR_BADRCPT_SHUTDOWN
646 #endif /* _FFR_BADRCPT_SHUTDOWN */
648 SevenBitInput_Saved = SevenBitInput;
651 smtp.sm_milterize = (nullserver == NULL);
652 smtp.sm_milterlist = false;
656 /* setup I/O fd correctly for the SMTP server */
660 if (sm_debug_active(&DebugLeakSmtp, 1))
663 sm_dprintf("smtp() heap group #%d\n", sm_heap_group());
665 #endif /* SM_HEAP_CHECK */
667 /* XXX the rpool should be set when e is initialized in main() */
668 e->e_rpool = sm_rpool_new_x(NULL);
669 e->e_macro.mac_rpool = e->e_rpool;
673 peerhostname = RealHostName;
674 if (peerhostname == NULL)
675 peerhostname = "localhost";
676 CurHostName = peerhostname;
677 CurSmtpClient = macvalue('_', e);
678 if (CurSmtpClient == NULL)
679 CurSmtpClient = CurHostName;
681 /* check_relay may have set discard bit, save for later */
682 smtp.sm_discard = bitset(EF_DISCARD, e->e_flags);
685 /* auto-flush output when reading input */
686 (void) sm_io_autoflush(InChannel, OutChannel);
687 #endif /* PIPELINING */
689 sm_setproctitle(true, e, "server %s startup", CurSmtpClient);
691 /* Set default features for server. */
692 features = ((bitset(PRIV_NOETRN, PrivacyFlags) ||
693 bitnset(D_NOETRN, d_flags)) ? SRV_NONE : SRV_OFFER_ETRN)
694 | (bitnset(D_AUTHREQ, d_flags) ? SRV_REQ_AUTH : SRV_NONE)
695 | (bitset(PRIV_NOEXPN, PrivacyFlags) ? SRV_NONE
697 | (bitset(PRIV_NOVERB, PrivacyFlags)
698 ? SRV_NONE : SRV_OFFER_VERB)))
699 | ((bitset(PRIV_NORECEIPTS, PrivacyFlags) || !SendMIMEErrors)
700 ? SRV_NONE : SRV_OFFER_DSN)
702 | (bitnset(D_NOAUTH, d_flags) ? SRV_NONE : SRV_OFFER_AUTH)
703 | (bitset(SASL_SEC_NOPLAINTEXT, SASLOpts) ? SRV_REQ_SEC
708 #endif /* PIPELINING */
710 | (bitnset(D_NOTLS, d_flags) ? SRV_NONE : SRV_OFFER_TLS)
711 | (bitset(TLS_I_NO_VRFY, TLS_Srv_Opts) ? SRV_NONE
713 #endif /* STARTTLS */
715 if (nullserver == NULL)
717 features = srvfeatures(e, CurSmtpClient, features);
718 if (bitset(SRV_TMP_FAIL, features))
721 sm_syslog(LOG_ERR, NOQID,
722 "ERROR: srv_features=tempfail, relay=%.100s, access temporarily disabled",
724 nullserver = "450 4.3.0 Please try again later.";
730 if (bitset(SRV_NO_PIPE, features))
732 /* for consistency */
733 features &= ~SRV_OFFER_PIPE;
735 # endif /* _FFR_NO_PIPE */
736 #endif /* PIPELINING */
738 if (bitset(SRV_REQ_SEC, features))
739 SASLOpts |= SASL_SEC_NOPLAINTEXT;
741 SASLOpts &= ~SASL_SEC_NOPLAINTEXT;
745 else if (strncmp(nullserver, "421 ", 4) == 0)
751 e->e_features = features;
752 hostname = macvalue('j', e);
754 if (AuthRealm == NULL)
755 AuthRealm = hostname;
756 sasl_ok = bitset(SRV_OFFER_AUTH, features);
758 authenticating = SASL_NOT_AUTH;
760 /* SASL server new connection */
764 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, NULL,
767 /* use empty realm: only works in SASL > 1.5.5 */
768 result = sasl_server_new("smtp", AuthRealm, "", NULL, 0, &conn);
769 # else /* SASL >= 20000 */
770 /* use no realm -> realm is set to hostname by SASL lib */
771 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, 0,
773 # endif /* SASL >= 20000 */
774 sasl_ok = result == SASL_OK;
778 sm_syslog(LOG_WARNING, NOQID,
779 "AUTH error: sasl_server_new failed=%d",
786 ** SASL set properties for sasl
787 ** set local/remote IP
788 ** XXX Cyrus SASL v1 only supports IPv4
790 ** XXX where exactly are these used/required?
795 localip[0] = remoteip[0] = '\0';
796 # if NETINET || NETINET6
797 in = macvalue(macid("{daemon_family}"), e);
800 strcmp(in, "inet6") == 0 ||
801 # endif /* NETINET6 */
802 strcmp(in, "inet") == 0))
804 SOCKADDR_LEN_T addrsize;
808 addrsize = sizeof(saddr_r);
809 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
811 (struct sockaddr *) &saddr_r,
814 if (iptostring(&saddr_r, addrsize,
815 remoteip, sizeof(remoteip)))
817 sasl_setprop(conn, SASL_IPREMOTEPORT,
820 addrsize = sizeof(saddr_l);
821 if (getsockname(sm_io_getinfo(InChannel,
824 (struct sockaddr *) &saddr_l,
827 if (iptostring(&saddr_l, addrsize,
838 # endif /* NETINET || NETINET6 */
839 # else /* SASL >= 20000 */
841 in = macvalue(macid("{daemon_family}"), e);
842 if (in != NULL && strcmp(in, "inet") == 0)
844 SOCKADDR_LEN_T addrsize;
846 addrsize = sizeof(struct sockaddr_in);
847 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
849 (struct sockaddr *)&saddr_r,
852 sasl_setprop(conn, SASL_IP_REMOTE, &saddr_r);
853 addrsize = sizeof(struct sockaddr_in);
854 if (getsockname(sm_io_getinfo(InChannel,
857 (struct sockaddr *)&saddr_l,
859 sasl_setprop(conn, SASL_IP_LOCAL,
863 # endif /* NETINET */
864 # endif /* SASL >= 20000 */
870 macdefine(&BlankEnvelope.e_macro, A_PERM,
871 macid("{auth_author}"), NULL);
875 (void) memset(&ssp, '\0', sizeof(ssp));
877 /* XXX should these be options settable via .cf ? */
878 /* ssp.min_ssf = 0; is default due to memset() */
879 ssp.max_ssf = MaxSLBits;
880 ssp.maxbufsize = MAXOUTLEN;
881 ssp.security_flags = SASLOpts & SASL_SEC_MASK;
882 sasl_ok = sasl_setprop(conn, SASL_SEC_PROPS, &ssp) == SASL_OK;
887 ** external security strength factor;
888 ** currently we have none so zero
894 sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL,
895 &ext_ssf) == SASL_OK) &&
896 (sasl_setprop(conn, SASL_AUTH_EXTERNAL,
897 auth_id) == SASL_OK));
898 # else /* SASL >= 20000 */
900 ext_ssf.auth_id = NULL;
901 sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL,
902 &ext_ssf) == SASL_OK;
903 # endif /* SASL >= 20000 */
906 n_mechs = saslmechs(conn, &mechlist);
913 set_tls_rd_tmo(TimeOuts.to_nextcommand);
914 #endif /* STARTTLS */
917 if (smtp.sm_milterize)
921 /* initialize mail filter connection */
922 smtp.sm_milterlist = milter_init(e, &state, &smtp.sm_milters);
926 if (MilterLogLevel > 3)
927 sm_syslog(LOG_INFO, e->e_id,
928 "Milter: initialization failed, rejecting commands");
930 nullserver = "Command rejected";
931 smtp.sm_milterize = false;
935 if (MilterLogLevel > 3)
936 sm_syslog(LOG_INFO, e->e_id,
937 "Milter: initialization failed, temp failing commands");
939 smtp.sm_milterize = false;
943 if (MilterLogLevel > 3)
944 sm_syslog(LOG_INFO, e->e_id,
945 "Milter: initialization failed, closing connection");
947 smtp.sm_milterize = false;
948 message("421 4.7.0 %s closing connection",
951 /* arrange to ignore send list */
952 e->e_sendqueue = NULL;
953 lognullconnection = false;
958 if (smtp.sm_milterlist && smtp.sm_milterize &&
959 !bitset(EF_DISCARD, e->e_flags))
964 q = macvalue(macid("{client_name}"), e);
965 SM_ASSERT(q != NULL || OpMode == MD_SMTP);
968 response = milter_connect(q, RealHostAddr, e, &state);
971 case SMFIR_REPLYCODE: /* REPLYCODE shouldn't happen */
973 if (MilterLogLevel > 3)
974 sm_syslog(LOG_INFO, e->e_id,
975 "Milter: connect: host=%s, addr=%s, rejecting commands",
977 anynet_ntoa(&RealHostAddr));
979 nullserver = "Command rejected";
980 smtp.sm_milterize = false;
984 if (MilterLogLevel > 3)
985 sm_syslog(LOG_INFO, e->e_id,
986 "Milter: connect: host=%s, addr=%s, temp failing commands",
988 anynet_ntoa(&RealHostAddr));
990 smtp.sm_milterize = false;
994 if (MilterLogLevel > 3)
995 sm_syslog(LOG_INFO, e->e_id,
996 "Milter: connect: host=%s, addr=%s, shutdown",
998 anynet_ntoa(&RealHostAddr));
1000 smtp.sm_milterize = false;
1001 message("421 4.7.0 %s closing connection",
1004 /* arrange to ignore send list */
1005 e->e_sendqueue = NULL;
1008 if (response != NULL)
1009 sm_free(response); /* XXX */
1014 ** Broken proxies and SMTP slammers
1015 ** push data without waiting, catch them
1021 #endif /* STARTTLS */
1022 *greetcode == '2' && nullserver == NULL)
1026 char pvpbuf[PSBUFSIZE];
1028 /* Ask the rulesets how long to pause */
1030 r = rscap("greet_pause", peerhostname,
1031 anynet_ntoa(&RealHostAddr), e,
1032 &pvp, pvpbuf, sizeof(pvpbuf));
1033 if (r == EX_OK && pvp != NULL && pvp[0] != NULL &&
1034 (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL)
1036 msecs = strtol(pvp[1], NULL, 10);
1043 struct timeval timeout;
1044 struct timeval bp, ep, tp; /* {begin,end,total}pause */
1047 /* pause for a moment */
1048 timeout.tv_sec = msecs / 1000;
1049 timeout.tv_usec = (msecs % 1000) * 1000;
1051 /* Obey RFC 2821: 4.3.5.2: 220 timeout of 5 minutes */
1052 if (timeout.tv_sec >= 300)
1054 timeout.tv_sec = 300;
1055 timeout.tv_usec = 0;
1058 /* check if data is on the socket during the pause */
1059 fd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1061 SM_FD_SET(fd, &readfds);
1062 gettimeofday(&bp, NULL);
1063 if (select(fd + 1, FDSET_CAST &readfds,
1064 NULL, NULL, &timeout) > 0 &&
1065 FD_ISSET(fd, &readfds) &&
1066 (eoftest = sm_io_getc(InChannel, SM_TIME_DEFAULT))
1069 sm_io_ungetc(InChannel, SM_TIME_DEFAULT,
1071 gettimeofday(&ep, NULL);
1072 timersub(&ep, &bp, &tp);
1074 nullserver = "Command rejected";
1075 sm_syslog(LOG_INFO, e->e_id,
1076 "rejecting commands from %s [%s] due to pre-greeting traffic after %d seconds",
1078 anynet_ntoa(&RealHostAddr),
1080 (tp.tv_usec >= 500000 ? 1 : 0)
1087 /* If this an smtps connection, start TLS now */
1096 #endif /* STARTTLS */
1098 /* output the first line, inserting "ESMTP" as second word */
1099 if (*greetcode == '5')
1100 (void) sm_snprintf(inp, sizeof(inp),
1101 "%s not accepting messages", hostname);
1103 expand(SmtpGreeting, inp, sizeof(inp), e);
1105 p = strchr(inp, '\n');
1108 id = strchr(inp, ' ');
1110 id = &inp[strlen(inp)];
1112 (void) sm_snprintf(cmdbuf, sizeof(cmdbuf),
1113 "%s %%.*s ESMTP%%s", greetcode);
1115 (void) sm_snprintf(cmdbuf, sizeof(cmdbuf),
1116 "%s-%%.*s ESMTP%%s", greetcode);
1117 message(cmdbuf, (int) (id - inp), inp, id);
1119 /* output remaining lines */
1120 while ((id = p) != NULL && (p = strchr(id, '\n')) != NULL)
1123 if (isascii(*id) && isspace(*id))
1125 (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, "-%s");
1126 message(cmdbuf, id);
1130 if (isascii(*id) && isspace(*id))
1132 (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, " %s");
1133 message(cmdbuf, id);
1137 sendinghost = macvalue('s', e);
1139 /* If quarantining by a connect/ehlo action, save between messages */
1140 if (e->e_quarmsg == NULL)
1141 smtp.sm_quarmsg = NULL;
1143 smtp.sm_quarmsg = newstr(e->e_quarmsg);
1145 /* sendinghost's storage must outlive the current envelope */
1146 if (sendinghost != NULL)
1147 sendinghost = sm_strdup_x(sendinghost);
1150 smtp.sm_gotmail = false;
1159 OnlyOneError = true;
1160 e->e_flags &= ~(EF_VRFYONLY|EF_GLOBALERRS);
1162 milter_cmd_fail = false;
1165 /* setup for the read */
1169 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
1171 /* read the input line */
1172 SmtpPhase = "server cmd read";
1173 sm_setproctitle(true, e, "server %s cmd read", CurSmtpClient);
1176 if (sm_io_error(OutChannel) ||
1177 (p = sfgets(inp, sizeof(inp), InChannel,
1178 TimeOuts.to_nextcommand, SmtpPhase)) == NULL)
1182 d = macvalue(macid("{daemon_name}"), e);
1185 /* end of file, just die */
1189 /* close out milter filters */
1193 message("421 4.4.1 %s Lost input channel from %s",
1194 MyHostName, CurSmtpClient);
1195 if (LogLevel > (smtp.sm_gotmail ? 1 : 19))
1196 sm_syslog(LOG_NOTICE, e->e_id,
1197 "lost input channel from %s to %s after %s",
1199 (c == NULL || c->cmd_name == NULL) ? "startup" : c->cmd_name);
1201 ** If have not accepted mail (DATA), do not bounce
1202 ** bad addresses back to sender.
1205 if (bitset(EF_CLRQUEUE, e->e_flags))
1206 e->e_sendqueue = NULL;
1210 /* also used by "proxy" check below */
1211 inplen = strlen(inp);
1214 ** SMTP AUTH requires accepting any length,
1215 ** at least for challenge/response. However, not imposing
1216 ** a limit is a bad idea (denial of service).
1219 if (authenticating != SASL_PROC_AUTH
1220 && sm_strncasecmp(inp, "AUTH ", 5) != 0
1221 && inplen > MAXLINE)
1223 message("421 4.7.0 %s Command too long, possible attack %s",
1224 MyHostName, CurSmtpClient);
1225 sm_syslog(LOG_INFO, e->e_id,
1226 "%s: SMTP violation, input too long: %lu",
1227 CurSmtpClient, (unsigned long) inplen);
1237 static char *http_cmds[] = { "GET", "POST",
1238 "CONNECT", "USER", NULL };
1240 for (idx = 0; (http_cmd = http_cmds[idx]) != NULL;
1243 cmdlen = strlen(http_cmd);
1244 if (cmdlen < inplen &&
1245 sm_strncasecmp(inp, http_cmd, cmdlen) == 0 &&
1246 isascii(inp[cmdlen]) && isspace(inp[cmdlen]))
1248 /* Open proxy, drop it */
1249 message("421 4.7.0 %s Rejecting open proxy %s",
1250 MyHostName, CurSmtpClient);
1251 sm_syslog(LOG_INFO, e->e_id,
1252 "%s: probable open proxy: command=%.40s",
1253 CurSmtpClient, inp);
1260 /* clean up end of line */
1266 ** if there is more input and pipelining is disabled:
1267 ** delay ... (and maybe discard the input?)
1268 ** XXX this doesn't really work, at least in tests using
1269 ** telnet SM_IO_IS_READABLE only returns 1 if there were
1270 ** more than 2 input lines available.
1273 if (bitset(SRV_NO_PIPE, features) &&
1274 sm_io_getinfo(InChannel, SM_IO_IS_READABLE, NULL) > 0)
1277 sm_syslog(LOG_INFO, NOQID,
1278 "unauthorized PIPELINING, sleeping, relay=%.100s",
1283 # endif /* _FFR_NO_PIPE */
1284 #endif /* PIPELINING */
1287 if (authenticating == SASL_PROC_AUTH)
1292 authenticating = SASL_NOT_AUTH;
1293 message("501 5.5.2 missing input");
1298 if (*inp == '*' && *(inp + 1) == '\0')
1300 authenticating = SASL_NOT_AUTH;
1303 message("501 5.0.0 AUTH aborted");
1308 /* could this be shorter? XXX */
1310 in = xalloc(strlen(inp) + 1);
1311 result = sasl_decode64(inp, strlen(inp), in,
1312 strlen(inp), &inlen);
1313 # else /* SASL >= 20000 */
1314 out = xalloc(strlen(inp));
1315 result = sasl_decode64(inp, strlen(inp), out, &outlen);
1316 # endif /* SASL >= 20000 */
1317 if (result != SASL_OK)
1319 authenticating = SASL_NOT_AUTH;
1322 message("501 5.5.4 cannot decode AUTH parameter %s",
1326 # endif /* SASL >= 20000 */
1332 result = sasl_server_step(conn, in, inlen,
1335 # else /* SASL >= 20000 */
1336 result = sasl_server_step(conn, out, outlen,
1337 &out, &outlen, &errstr);
1338 # endif /* SASL >= 20000 */
1340 /* get an OK if we're done */
1341 if (result == SASL_OK)
1344 message("235 2.0.0 OK Authenticated");
1345 authenticating = SASL_IS_AUTH;
1346 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1347 macid("{auth_type}"), auth_type);
1350 user = macvalue(macid("{auth_authen}"), e);
1352 /* get security strength (features) */
1353 result = sasl_getprop(conn, SASL_SSF,
1354 (const void **) &ssf);
1355 # else /* SASL >= 20000 */
1356 result = sasl_getprop(conn, SASL_USERNAME,
1358 if (result != SASL_OK)
1361 macdefine(&BlankEnvelope.e_macro,
1363 macid("{auth_authen}"), NULL);
1367 macdefine(&BlankEnvelope.e_macro,
1369 macid("{auth_authen}"),
1370 xtextify(user, "<>\")"));
1375 sasl_getprop(conn, SASL_REALM, (void **) &data);
1378 /* get security strength (features) */
1379 result = sasl_getprop(conn, SASL_SSF,
1381 # endif /* SASL >= 20000 */
1382 if (result != SASL_OK)
1384 macdefine(&BlankEnvelope.e_macro,
1386 macid("{auth_ssf}"), "0");
1393 (void) sm_snprintf(pbuf, sizeof(pbuf),
1395 macdefine(&BlankEnvelope.e_macro,
1397 macid("{auth_ssf}"), pbuf);
1399 sm_dprintf("AUTH auth_ssf: %u\n",
1404 ** Only switch to encrypted connection
1405 ** if a security layer has been negotiated
1408 if (ssf != NULL && *ssf > 0)
1413 ** Convert I/O layer to use SASL.
1414 ** If the call fails, the connection
1418 tmo = TimeOuts.to_datablock * 1000;
1419 if (sfdcsasl(&InChannel, &OutChannel,
1422 /* restart dialogue */
1425 (void) sm_io_autoflush(InChannel,
1427 # endif /* PIPELINING */
1430 syserr("503 5.3.3 SASL TLS failed");
1433 /* NULL pointer ok since it's our function */
1435 sm_syslog(LOG_INFO, NOQID,
1436 "AUTH=server, relay=%s, authid=%.128s, mech=%.16s, bits=%d",
1438 shortenstring(user, 128),
1441 else if (result == SASL_CONTINUE)
1443 len = ENC64LEN(outlen);
1445 result = sasl_encode64(out, outlen, out2, len,
1447 if (result != SASL_OK)
1449 /* correct code? XXX */
1450 /* 454 Temp. authentication failure */
1451 message("454 4.5.4 Internal error: unable to encode64");
1453 sm_syslog(LOG_WARNING, e->e_id,
1454 "AUTH encode64 error [%d for \"%s\"], relay=%.100s",
1458 authenticating = SASL_NOT_AUTH;
1462 message("334 %s", out2);
1464 sm_dprintf("AUTH continue: msg='%s' len=%u\n",
1469 # endif /* SASL >= 20000 */
1473 /* not SASL_OK or SASL_CONT */
1474 message("535 5.7.0 authentication failed");
1476 sm_syslog(LOG_WARNING, e->e_id,
1477 "AUTH failure (%s): %s (%d) %s, relay=%.100s",
1479 sasl_errstring(result, NULL,
1483 sasl_errdetail(conn),
1484 # else /* SASL >= 20000 */
1485 errstr == NULL ? "" : errstr,
1486 # endif /* SASL >= 20000 */
1489 authenticating = SASL_NOT_AUTH;
1494 /* don't want to do any of this if authenticating */
1497 /* echo command to transcript */
1498 if (e->e_xfp != NULL)
1499 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1503 sm_syslog(LOG_INFO, e->e_id, "<-- %s", inp);
1505 /* break off command */
1506 for (p = inp; isascii(*p) && isspace(*p); p++)
1509 while (*p != '\0' &&
1510 !(isascii(*p) && isspace(*p)) &&
1511 cmd < &cmdbuf[sizeof(cmdbuf) - 2])
1515 /* throw away leading whitespace */
1518 /* decode command */
1519 for (c = CmdTab; c->cmd_name != NULL; c++)
1521 if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0)
1528 /* check whether a "non-null" command has been used */
1529 switch (c->cmd_code)
1533 /* avoid information leak; take first two words? */
1542 lognullconnection = false;
1549 if (e->e_id == NULL)
1550 sm_setproctitle(true, e, "%s: %.80s",
1553 sm_setproctitle(true, e, "%s %s: %.80s",
1560 ** If we are running as a null server, return 550
1561 ** to almost everything.
1564 if (nullserver != NULL || bitnset(D_ETRNONLY, d_flags))
1566 switch (c->cmd_code)
1574 /* process normally */
1578 if (bitnset(D_ETRNONLY, d_flags) &&
1585 #if MAXBADCOMMANDS > 0
1586 /* theoretically this could overflow */
1587 if (nullserver != NULL &&
1588 ++n_badcmds > MAXBADCOMMANDS)
1590 message("421 4.7.0 %s Too many bad commands; closing connection",
1593 /* arrange to ignore send list */
1594 e->e_sendqueue = NULL;
1597 #endif /* MAXBADCOMMANDS > 0 */
1598 if (nullserver != NULL)
1600 if (ISSMTPREPLY(nullserver))
1603 usrerr("550 5.0.0 %s",
1607 usrerr("452 4.4.5 Insufficient disk space; try again later");
1612 switch (c->cmd_code)
1615 case CMDAUTH: /* sasl */
1617 if (!sasl_ok || n_mechs <= 0)
1619 message("503 5.3.3 AUTH not available");
1622 if (authenticating == SASL_IS_AUTH)
1624 message("503 5.5.0 Already Authenticated");
1627 if (smtp.sm_gotmail)
1629 message("503 5.5.0 AUTH not permitted during a mail transaction");
1635 sm_syslog(LOG_INFO, e->e_id,
1636 "SMTP AUTH command (%.100s) from %s tempfailed (due to previous checks)",
1638 usrerr("454 4.3.0 Please try again later");
1644 /* crude way to avoid crack attempts */
1645 STOP_IF_ATTACK(checksmtpattack(&n_auth, n_mechs + 1,
1648 /* make sure mechanism (p) is a valid string */
1649 for (q = p; *q != '\0' && isascii(*q); q++)
1654 while (*++q != '\0' &&
1655 isascii(*q) && isspace(*q))
1658 ismore = (*q != '\0');
1665 message("501 5.5.2 AUTH mechanism must be specified");
1669 /* check whether mechanism is available */
1670 if (iteminlist(p, mechlist, " ") == NULL)
1672 message("504 5.3.3 AUTH mechanism %.32s not available",
1679 ** Unlike a zero-length client answer to a
1680 ** 334 reply, a zero- length initial response
1681 ** is sent as a single equals sign ("=").
1684 if (ismore && *q == '=' && *(q + 1) == '\0')
1686 /* will be free()d, don't use in=""; */
1693 /* could this be shorter? XXX */
1695 in = xalloc(strlen(q) + 1);
1696 result = sasl_decode64(q, strlen(q), in,
1698 # else /* SASL >= 20000 */
1699 in = sm_rpool_malloc(e->e_rpool, strlen(q));
1700 result = sasl_decode64(q, strlen(q), in,
1702 # endif /* SASL >= 20000 */
1703 if (result != SASL_OK)
1705 message("501 5.5.4 cannot BASE64 decode '%s'",
1708 sm_syslog(LOG_WARNING, e->e_id,
1709 "AUTH decode64 error [%d for \"%s\"], relay=%.100s",
1713 authenticating = SASL_NOT_AUTH;
1716 # endif /* SASL >= 20000 */
1728 /* see if that auth type exists */
1730 result = sasl_server_start(conn, p, in, inlen,
1734 # else /* SASL >= 20000 */
1735 result = sasl_server_start(conn, p, in, inlen,
1736 &out, &outlen, &errstr);
1737 # endif /* SASL >= 20000 */
1739 if (result != SASL_OK && result != SASL_CONTINUE)
1741 message("535 5.7.0 authentication failed");
1743 sm_syslog(LOG_ERR, e->e_id,
1744 "AUTH failure (%s): %s (%d) %s, relay=%.100s",
1746 sasl_errstring(result, NULL,
1750 sasl_errdetail(conn),
1751 # else /* SASL >= 20000 */
1753 # endif /* SASL >= 20000 */
1758 auth_type = newstr(p);
1760 if (result == SASL_OK)
1762 /* ugly, but same code */
1764 /* authenticated by the initial response */
1767 /* len is at least 2 */
1768 len = ENC64LEN(outlen);
1770 result = sasl_encode64(out, outlen, out2, len,
1773 if (result != SASL_OK)
1775 message("454 4.5.4 Temporary authentication failure");
1777 sm_syslog(LOG_WARNING, e->e_id,
1778 "AUTH encode64 error [%d for \"%s\"]",
1782 authenticating = SASL_NOT_AUTH;
1787 message("334 %s", out2);
1788 authenticating = SASL_PROC_AUTH;
1792 # endif /* SASL >= 20000 */
1797 case CMDSTLS: /* starttls */
1798 DELAY_CONN("STARTTLS");
1801 message("501 5.5.2 Syntax error (no parameters allowed)");
1804 if (!bitset(SRV_OFFER_TLS, features))
1806 message("503 5.5.0 TLS not available");
1811 message("454 4.3.3 TLS not available after start");
1814 if (smtp.sm_gotmail)
1816 message("503 5.5.0 TLS not permitted during a mail transaction");
1822 sm_syslog(LOG_INFO, e->e_id,
1823 "SMTP STARTTLS command (%.100s) from %s tempfailed (due to previous checks)",
1825 usrerr("454 4.7.0 Please try again later");
1829 # if USE_OPENSSL_ENGINE
1830 if (!SSLEngineInitialized)
1832 if (!SSL_set_engine(NULL))
1834 sm_syslog(LOG_ERR, NOQID,
1835 "STARTTLS=server, SSL_set_engine=failed");
1837 message("454 4.3.3 TLS not available right now");
1841 SSLEngineInitialized = true;
1843 # endif /* USE_OPENSSL_ENGINE */
1846 ** XXX do we need a temp key ?
1848 # else /* TLS_NO_RSA */
1849 # endif /* TLS_NO_RSA */
1851 # if TLS_VRFY_PER_CTX
1853 ** Note: this sets the verification globally
1855 ** it's ok since it applies only to one transaction
1858 TLS_VERIFY_CLIENT();
1859 # endif /* TLS_VRFY_PER_CTX */
1861 if (srv_ssl != NULL)
1863 else if ((srv_ssl = SSL_new(srv_ctx)) == NULL)
1865 message("454 4.3.3 TLS not available: error generating SSL handle");
1867 tlslogerr(LOG_WARNING, "server");
1871 # if !TLS_VRFY_PER_CTX
1873 ** this could be used if it were possible to set
1874 ** verification per SSL (connection)
1875 ** not just per SSL_CTX (global)
1878 TLS_VERIFY_CLIENT();
1879 # endif /* !TLS_VRFY_PER_CTX */
1881 rfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1882 wfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
1884 if (rfd < 0 || wfd < 0 ||
1885 SSL_set_rfd(srv_ssl, rfd) <= 0 ||
1886 SSL_set_wfd(srv_ssl, wfd) <= 0)
1888 message("454 4.3.3 TLS not available: error set fd");
1894 message("220 2.0.0 Ready to start TLS");
1896 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
1897 # endif /* PIPELINING */
1899 SSL_set_accept_state(srv_ssl);
1901 # define SSL_ACC(s) SSL_accept(s)
1903 tlsstart = curtime();
1905 if ((r = SSL_ACC(srv_ssl)) <= 0)
1909 ssl_err = SSL_get_error(srv_ssl, r);
1910 i = tls_retry(srv_ssl, rfd, wfd, tlsstart,
1911 TimeOuts.to_starttls, ssl_err,
1921 l = ERR_peek_error();
1922 sr = ERR_reason_error_string(l);
1923 sm_syslog(LOG_WARNING, NOQID,
1924 "STARTTLS=server, error: accept failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d, relay=%.100s",
1925 r, sr == NULL ? "unknown"
1930 tlslogerr(LOG_WARNING, "server");
1937 ** according to the next draft of
1938 ** RFC 2487 the connection should be dropped
1941 /* arrange to ignore any current send list */
1942 e->e_sendqueue = NULL;
1946 /* ignore return code for now, it's in {verify} */
1947 (void) tls_get_info(srv_ssl, true,
1949 &BlankEnvelope.e_macro,
1950 bitset(SRV_VRFY_CLT, features));
1953 ** call Stls_client to find out whether
1954 ** to accept the connection from the client
1957 saveQuickAbort = QuickAbort;
1958 saveSuprErrs = SuprErrs;
1961 if (rscheck("tls_client",
1962 macvalue(macid("{verify}"), e),
1964 RSF_RMCOMM|RSF_COUNT,
1965 5, NULL, NOQID, NULL) != EX_OK ||
1968 extern char MsgBuf[];
1970 if (MsgBuf[0] != '\0' && ISSMTPREPLY(MsgBuf))
1971 nullserver = newstr(MsgBuf);
1973 nullserver = "503 5.7.0 Authentication required.";
1975 QuickAbort = saveQuickAbort;
1976 SuprErrs = saveSuprErrs;
1978 tls_ok_srv = false; /* don't offer STARTTLS again */
1987 s = macvalue(macid("{cipher_bits}"), e);
1988 v = macvalue(macid("{verify}"), e);
1989 c = macvalue(macid("{cert_subject}"), e);
1990 verified = (v != NULL && strcmp(v, "OK") == 0);
1991 if (s != NULL && (cipher_bits = atoi(s)) > 0)
1994 ext_ssf = cipher_bits;
1995 auth_id = verified ? c : NULL;
1996 sasl_ok = ((sasl_setprop(conn,
1998 &ext_ssf) == SASL_OK) &&
2001 auth_id) == SASL_OK));
2002 # else /* SASL >= 20000 */
2003 ext_ssf.ssf = cipher_bits;
2004 ext_ssf.auth_id = verified ? c : NULL;
2005 sasl_ok = sasl_setprop(conn,
2007 &ext_ssf) == SASL_OK;
2008 # endif /* SASL >= 20000 */
2011 n_mechs = saslmechs(conn,
2017 /* switch to secure connection */
2018 if (sfdctls(&InChannel, &OutChannel, srv_ssl) == 0)
2022 (void) sm_io_autoflush(InChannel, OutChannel);
2023 # endif /* PIPELINING */
2028 ** XXX this is an internal error
2029 ** how to deal with it?
2030 ** we can't generate an error message
2031 ** since the other side switched to an
2032 ** encrypted layer, but we could not...
2036 nullserver = "454 4.3.3 TLS not available: can't switch to encrypted layer";
2037 syserr("STARTTLS: can't switch to encrypted layer");
2048 #endif /* STARTTLS */
2050 case CMDHELO: /* hello -- introduce yourself */
2051 case CMDEHLO: /* extended hello */
2053 if (c->cmd_code == CMDEHLO)
2056 SmtpPhase = "server EHLO";
2061 SmtpPhase = "server HELO";
2064 /* avoid denial-of-service */
2065 STOP_IF_ATTACK(checksmtpattack(&n_helo, MAXHELOCOMMANDS,
2066 true, "HELO/EHLO", e));
2069 /* RFC2821 4.1.4 allows duplicate HELO/EHLO */
2070 /* check for duplicate HELO/EHLO per RFC 1651 4.2 */
2073 usrerr("503 %s Duplicate HELO/EHLO",
2079 /* check for valid domain name (re 1123 5.2.5) */
2080 if (*p == '\0' && !AllowBogusHELO)
2082 usrerr("501 %s requires domain address",
2087 /* check for long domain name (hides Received: info) */
2088 if (strlen(p) > MAXNAME)
2090 usrerr("501 Invalid domain name");
2092 sm_syslog(LOG_INFO, CurEnv->e_id,
2093 "invalid domain name (too long) from %s",
2099 for (q = p; *q != '\0'; q++)
2109 /* only complain if strict check */
2110 ok = AllowBogusHELO;
2112 /* allow trailing whitespace */
2113 while (!ok && *++q != '\0' &&
2120 if (strchr("[].-_#:", *q) == NULL)
2124 if (*q == '\0' && ok)
2126 q = "pleased to meet you";
2127 sendinghost = sm_strdup_x(p);
2129 else if (!AllowBogusHELO)
2131 usrerr("501 Invalid domain name");
2133 sm_syslog(LOG_INFO, CurEnv->e_id,
2134 "invalid domain name (%s) from %.100s",
2140 q = "accepting invalid domain name";
2143 if (gothello || smtp.sm_gotmail)
2144 CLEAR_STATE(cmdbuf);
2147 if (smtp.sm_milterlist && smtp.sm_milterize &&
2148 !bitset(EF_DISCARD, e->e_flags))
2153 response = milter_helo(p, e, &state);
2157 if (MilterLogLevel > 3)
2158 sm_syslog(LOG_INFO, e->e_id,
2159 "Milter: helo=%s, reject=Command rejected",
2161 nullserver = "Command rejected";
2162 smtp.sm_milterize = false;
2165 case SMFIR_TEMPFAIL:
2166 if (MilterLogLevel > 3)
2167 sm_syslog(LOG_INFO, e->e_id,
2168 "Milter: helo=%s, reject=%s",
2171 smtp.sm_milterize = false;
2174 case SMFIR_REPLYCODE:
2175 if (MilterLogLevel > 3)
2176 sm_syslog(LOG_INFO, e->e_id,
2177 "Milter: helo=%s, reject=%s",
2179 if (strncmp(response, "421 ", 4) != 0
2180 && strncmp(response, "421-", 4) != 0)
2182 nullserver = newstr(response);
2183 smtp.sm_milterize = false;
2188 case SMFIR_SHUTDOWN:
2189 if (MilterLogLevel > 3 &&
2191 sm_syslog(LOG_INFO, e->e_id,
2192 "Milter: helo=%s, reject=421 4.7.0 %s closing connection",
2195 smtp.sm_milterize = false;
2196 if (response != NULL)
2199 message("421 4.7.0 %s closing connection",
2201 /* arrange to ignore send list */
2202 e->e_sendqueue = NULL;
2203 lognullconnection = false;
2206 if (response != NULL)
2210 ** If quarantining by a connect/ehlo action,
2211 ** save between messages
2214 if (smtp.sm_quarmsg == NULL &&
2215 e->e_quarmsg != NULL)
2216 smtp.sm_quarmsg = newstr(e->e_quarmsg);
2221 /* print HELO response message */
2222 if (c->cmd_code != CMDEHLO)
2224 message("250 %s Hello %s, %s",
2225 MyHostName, CurSmtpClient, q);
2229 message("250-%s Hello %s, %s",
2230 MyHostName, CurSmtpClient, q);
2232 /* offer ENHSC even for nullserver */
2233 if (nullserver != NULL)
2235 message("250 ENHANCEDSTATUSCODES");
2240 ** print EHLO features list
2242 ** Note: If you change this list,
2243 ** remember to update 'helpfile'
2246 message("250-ENHANCEDSTATUSCODES");
2248 if (bitset(SRV_OFFER_PIPE, features))
2249 message("250-PIPELINING");
2250 #endif /* PIPELINING */
2251 if (bitset(SRV_OFFER_EXPN, features))
2253 message("250-EXPN");
2254 if (bitset(SRV_OFFER_VERB, features))
2255 message("250-VERB");
2258 message("250-8BITMIME");
2259 #endif /* MIME8TO7 */
2260 if (MaxMessageSize > 0)
2261 message("250-SIZE %ld", MaxMessageSize);
2263 message("250-SIZE");
2265 if (SendMIMEErrors && bitset(SRV_OFFER_DSN, features))
2268 if (bitset(SRV_OFFER_ETRN, features))
2269 message("250-ETRN");
2271 if (sasl_ok && mechlist != NULL && *mechlist != '\0')
2272 message("250-AUTH %s", mechlist);
2275 if (tls_ok_srv && bitset(SRV_OFFER_TLS, features))
2276 message("250-STARTTLS");
2277 #endif /* STARTTLS */
2278 if (DeliverByMin > 0)
2279 message("250-DELIVERBY %ld",
2280 (long) DeliverByMin);
2281 else if (DeliverByMin == 0)
2282 message("250-DELIVERBY");
2284 /* < 0: no deliver-by */
2286 message("250 HELP");
2289 case CMDMAIL: /* mail -- designate sender */
2290 SmtpPhase = "server MAIL";
2293 /* check for validity of this command */
2294 if (!gothello && bitset(PRIV_NEEDMAILHELO, PrivacyFlags))
2296 usrerr("503 5.0.0 Polite people say HELO first");
2299 if (smtp.sm_gotmail)
2301 usrerr("503 5.5.0 Sender already specified");
2305 if (bitset(SRV_REQ_AUTH, features) &&
2306 authenticating != SASL_IS_AUTH)
2308 usrerr("530 5.7.0 Authentication required");
2313 p = skipword(p, "from");
2319 sm_syslog(LOG_INFO, e->e_id,
2320 "SMTP MAIL command (%.100s) from %s tempfailed (due to previous checks)",
2322 usrerr(MSG_TEMPFAIL);
2326 /* make sure we know who the sending host is */
2327 if (sendinghost == NULL)
2328 sendinghost = peerhostname;
2332 if (sm_debug_active(&DebugLeakSmtp, 1))
2335 sm_dprintf("smtp() heap group #%d\n",
2338 #endif /* SM_HEAP_CHECK */
2344 auth_warning(e, "%s didn't use HELO protocol",
2347 #ifdef PICKY_HELO_CHECK
2348 if (sm_strcasecmp(sendinghost, peerhostname) != 0 &&
2349 (sm_strcasecmp(peerhostname, "localhost") != 0 ||
2350 sm_strcasecmp(sendinghost, MyHostName) != 0))
2352 auth_warning(e, "Host %s claimed to be %s",
2353 CurSmtpClient, sendinghost);
2355 #endif /* PICKY_HELO_CHECK */
2357 if (protocol == NULL)
2359 macdefine(&e->e_macro, A_PERM, 'r', protocol);
2360 macdefine(&e->e_macro, A_PERM, 's', sendinghost);
2366 macdefine(&e->e_macro, A_PERM, macid("{ntries}"), "0");
2367 macdefine(&e->e_macro, A_PERM, macid("{nrcpts}"), "0");
2368 macdefine(&e->e_macro, A_PERM, macid("{nbadrcpts}"),
2370 e->e_flags |= EF_CLRQUEUE;
2371 sm_setproctitle(true, e, "%s %s: %.80s",
2373 CurSmtpClient, inp);
2375 /* do the processing */
2378 extern char *FullName;
2381 SM_FREE_CLR(FullName);
2383 /* must parse sender first */
2385 setsender(p, e, &delimptr, ' ', false);
2386 if (delimptr != NULL && *delimptr != '\0')
2389 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2391 /* Successfully set e_from, allow logging */
2392 e->e_flags |= EF_LOGSENDER;
2394 /* put resulting triple from parseaddr() into macros */
2395 if (e->e_from.q_mailer != NULL)
2396 macdefine(&e->e_macro, A_PERM,
2397 macid("{mail_mailer}"),
2398 e->e_from.q_mailer->m_name);
2400 macdefine(&e->e_macro, A_PERM,
2401 macid("{mail_mailer}"), NULL);
2402 if (e->e_from.q_host != NULL)
2403 macdefine(&e->e_macro, A_PERM,
2404 macid("{mail_host}"),
2407 macdefine(&e->e_macro, A_PERM,
2408 macid("{mail_host}"), "localhost");
2409 if (e->e_from.q_user != NULL)
2410 macdefine(&e->e_macro, A_PERM,
2411 macid("{mail_addr}"),
2414 macdefine(&e->e_macro, A_PERM,
2415 macid("{mail_addr}"), NULL);
2417 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2419 /* check for possible spoofing */
2420 if (RealUid != 0 && OpMode == MD_SMTP &&
2421 !wordinclass(RealUserName, 't') &&
2422 (!bitnset(M_LOCALMAILER,
2423 e->e_from.q_mailer->m_flags) ||
2424 strcmp(e->e_from.q_user, RealUserName) != 0))
2426 auth_warning(e, "%s owned process doing -bs",
2430 /* reset to default value */
2431 SevenBitInput = SevenBitInput_Saved;
2433 /* now parse ESMTP arguments */
2436 parse_esmtp_args(e, NULL, p, delimptr, "MAIL", args,
2439 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2442 # if _FFR_AUTH_PASSING
2443 /* set the default AUTH= if the sender didn't */
2444 if (e->e_auth_param == NULL)
2446 /* XXX only do this for an MSA? */
2447 e->e_auth_param = macvalue(macid("{auth_authen}"),
2449 if (e->e_auth_param == NULL)
2450 e->e_auth_param = "<>";
2453 ** XXX should we invoke Strust_auth now?
2454 ** authorizing as the client that just
2455 ** authenticated, so we'll trust implicitly
2458 # endif /* _FFR_AUTH_PASSING */
2461 /* do config file checking of the sender */
2462 macdefine(&e->e_macro, A_PERM,
2463 macid("{addr_type}"), "e s");
2465 /* make the "real" sender address available */
2466 macdefine(&e->e_macro, A_TEMP, macid("{mail_from}"),
2468 #endif /* _FFR_MAIL_MACRO */
2469 if (rscheck("check_mail", addr,
2470 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2471 NULL, e->e_id, NULL) != EX_OK ||
2473 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2474 macdefine(&e->e_macro, A_PERM,
2475 macid("{addr_type}"), NULL);
2477 if (MaxMessageSize > 0 &&
2478 (e->e_msgsize > MaxMessageSize ||
2481 usrerr("552 5.2.3 Message size exceeds fixed maximum message size (%ld)",
2483 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2487 ** XXX always check whether there is at least one fs
2488 ** with enough space?
2489 ** However, this may not help much: the queue group
2490 ** selection may later on select a FS that hasn't
2494 if ((NumFileSys == 1 || NumQueue == 1) &&
2495 !enoughdiskspace(e->e_msgsize, e)
2496 #if _FFR_ANY_FREE_FS
2497 && !filesys_free(e->e_msgsize)
2498 #endif /* _FFR_ANY_FREE_FS */
2502 ** We perform this test again when the
2503 ** queue directory is selected, in collect.
2506 usrerr("452 4.4.5 Insufficient disk space; try again later");
2507 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2510 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2514 if (smtp.sm_milterlist && smtp.sm_milterize &&
2515 !bitset(EF_DISCARD, e->e_flags))
2520 response = milter_envfrom(args, e, &state);
2521 MILTER_REPLY("from");
2525 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2527 message("250 2.1.0 Sender ok");
2528 smtp.sm_gotmail = true;
2530 SM_EXCEPT(exc, "[!F]*")
2533 ** An error occurred while processing a MAIL command.
2534 ** Jump to the common error handling code.
2544 e->e_flags &= ~EF_PM_NOTIFY;
2548 case CMDRCPT: /* rcpt -- designate recipient */
2550 macdefine(&e->e_macro, A_PERM,
2551 macid("{rcpt_mailer}"), NULL);
2552 macdefine(&e->e_macro, A_PERM,
2553 macid("{rcpt_host}"), NULL);
2554 macdefine(&e->e_macro, A_PERM,
2555 macid("{rcpt_addr}"), NULL);
2557 (void) memset(&addr_st, '\0', sizeof(addr_st));
2559 milter_rcpt_added = false;
2560 smtp.sm_e_nrcpts_orig = e->e_nrcpts;
2562 #if _FFR_BADRCPT_SHUTDOWN
2564 ** hack to deal with hack, see below:
2565 ** n_badrcpts is increased if limit is reached.
2568 n_badrcpts_adj = (BadRcptThrottle > 0 &&
2569 n_badrcpts > BadRcptThrottle &&
2571 ? n_badrcpts - 1 : n_badrcpts;
2572 if (BadRcptShutdown > 0 &&
2573 n_badrcpts_adj >= BadRcptShutdown &&
2574 (BadRcptShutdownGood == 0 ||
2575 smtp.sm_nrcpts == 0 ||
2576 (n_badrcpts_adj * 100 /
2577 (smtp.sm_nrcpts + n_badrcpts) >=
2578 BadRcptShutdownGood)))
2581 sm_syslog(LOG_INFO, e->e_id,
2582 "%s: Possible SMTP RCPT flood, shutting down connection.",
2584 message("421 4.7.0 %s Too many bad recipients; closing connection",
2587 /* arrange to ignore any current send list */
2588 e->e_sendqueue = NULL;
2591 #endif /* _FFR_BADRCPT_SHUTDOWN */
2592 if (BadRcptThrottle > 0 &&
2593 n_badrcpts >= BadRcptThrottle)
2596 n_badrcpts == BadRcptThrottle)
2598 sm_syslog(LOG_INFO, e->e_id,
2599 "%s: Possible SMTP RCPT flood, throttling.",
2602 /* To avoid duplicated message */
2608 ** Don't use exponential backoff for now.
2609 ** Some systems will open more connections
2610 ** and actually overload the receiver even
2614 (void) sleep(BadRcptThrottleDelay);
2616 if (!smtp.sm_gotmail)
2618 usrerr("503 5.0.0 Need MAIL before RCPT");
2621 SmtpPhase = "server RCPT";
2627 /* limit flooding of our machine */
2628 if (MaxRcptPerMsg > 0 &&
2629 smtp.sm_nrcpts >= MaxRcptPerMsg)
2631 /* sleep(1); / * slow down? */
2632 usrerr("452 4.5.3 Too many recipients");
2636 if (!SM_IS_INTERACTIVE(e->e_sendmode)
2638 && (NotFirstDelivery || SM_DM_ONE != e->e_sendmode)
2639 #endif /* _FFR_DM_ONE */
2641 e->e_flags |= EF_VRFYONLY;
2645 ** Do not expand recipients at RCPT time (in the call
2646 ** to recipient()) if a milter can delete or reject
2647 ** a RCPT. If they are expanded, it is impossible
2648 ** for removefromlist() to figure out the expanded
2649 ** members of the original recipient and mark them
2653 if (!(smtp.sm_milterlist && smtp.sm_milterize &&
2654 !bitset(EF_DISCARD, e->e_flags)) &&
2655 (smtp.sm_milters.mis_flags &
2656 (MIS_FL_DEL_RCPT|MIS_FL_REJ_RCPT)) != 0)
2657 e->e_flags |= EF_VRFYONLY;
2658 milter_cmd_done = false;
2659 milter_cmd_safe = false;
2662 p = skipword(p, "to");
2665 macdefine(&e->e_macro, A_PERM,
2666 macid("{addr_type}"), "e r");
2667 a = parseaddr(p, NULLADDR, RF_COPYALL, ' ', &delimptr,
2669 macdefine(&e->e_macro, A_PERM,
2670 macid("{addr_type}"), NULL);
2675 usrerr("501 5.0.0 Missing recipient");
2679 if (delimptr != NULL && *delimptr != '\0')
2682 /* put resulting triple from parseaddr() into macros */
2683 if (a->q_mailer != NULL)
2684 macdefine(&e->e_macro, A_PERM,
2685 macid("{rcpt_mailer}"),
2686 a->q_mailer->m_name);
2688 macdefine(&e->e_macro, A_PERM,
2689 macid("{rcpt_mailer}"), NULL);
2690 if (a->q_host != NULL)
2691 macdefine(&e->e_macro, A_PERM,
2692 macid("{rcpt_host}"), a->q_host);
2694 macdefine(&e->e_macro, A_PERM,
2695 macid("{rcpt_host}"), "localhost");
2696 if (a->q_user != NULL)
2697 macdefine(&e->e_macro, A_PERM,
2698 macid("{rcpt_addr}"), a->q_user);
2700 macdefine(&e->e_macro, A_PERM,
2701 macid("{rcpt_addr}"), NULL);
2705 /* now parse ESMTP arguments */
2707 parse_esmtp_args(e, a, p, delimptr, "RCPT", args,
2714 ** rscheck() can trigger an "exception"
2715 ** in which case the execution continues at
2716 ** SM_EXCEPT(exc, "[!F]*")
2717 ** This means milter_cmd_safe is not set
2718 ** and hence milter is not invoked.
2719 ** Would it be "safe" to change that, i.e., use
2720 ** milter_cmd_safe = true;
2721 ** here so a milter is informed (if requested)
2722 ** about RCPTs that are rejected by check_rcpt?
2724 # if _FFR_MILTER_CHECK_REJECTIONS_TOO
2725 milter_cmd_safe = true;
2729 /* do config file checking of the recipient */
2730 macdefine(&e->e_macro, A_PERM,
2731 macid("{addr_type}"), "e r");
2732 if (rscheck("check_rcpt", addr,
2733 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2734 NULL, e->e_id, p_addr_st) != EX_OK ||
2737 macdefine(&e->e_macro, A_PERM,
2738 macid("{addr_type}"), NULL);
2740 /* If discarding, don't bother to verify user */
2741 if (bitset(EF_DISCARD, e->e_flags))
2742 a->q_state = QS_VERIFIED;
2744 milter_cmd_safe = true;
2747 /* save in recipient list after ESMTP mods */
2748 a = recipient(a, &e->e_sendqueue, 0, e);
2749 /* may trigger exception... */
2752 milter_rcpt_added = true;
2755 if(!(Errors > 0) && QS_IS_BADADDR(a->q_state))
2757 /* punt -- should keep message in ADDRESS.... */
2758 usrerr("550 5.1.1 Addressee unknown");
2763 if (smtp.sm_milterlist && smtp.sm_milterize &&
2764 !bitset(EF_DISCARD, e->e_flags))
2769 /* how to get the error codes? */
2772 macdefine(&e->e_macro, A_PERM,
2773 macid("{rcpt_mailer}"),
2776 a->q_status != NULL &&
2777 a->q_rstatus != NULL)
2779 macdefine(&e->e_macro, A_PERM,
2780 macid("{rcpt_host}"),
2782 macdefine(&e->e_macro, A_PERM,
2783 macid("{rcpt_addr}"),
2788 if (addr_st.q_host != NULL)
2789 macdefine(&e->e_macro,
2791 macid("{rcpt_host}"),
2793 if (addr_st.q_user != NULL)
2794 macdefine(&e->e_macro,
2796 macid("{rcpt_addr}"),
2801 response = milter_envrcpt(args, e, &state,
2803 milter_cmd_done = true;
2808 /* no errors during parsing, but might be a duplicate */
2809 e->e_to = a->q_paddr;
2810 if (!(Errors > 0) && !QS_IS_BADADDR(a->q_state))
2812 if (smtp.sm_nrcpts == 0)
2814 message("250 2.1.5 Recipient ok%s",
2815 QS_IS_QUEUEUP(a->q_state) ?
2816 " (will queue)" : "");
2820 /* Is this needed? */
2823 #endif /* !MILTER */
2824 macdefine(&e->e_macro, A_PERM,
2825 macid("{rcpt_mailer}"), NULL);
2826 macdefine(&e->e_macro, A_PERM,
2827 macid("{rcpt_host}"), NULL);
2828 macdefine(&e->e_macro, A_PERM,
2829 macid("{rcpt_addr}"), NULL);
2830 macdefine(&e->e_macro, A_PERM,
2831 macid("{dsn_notify}"), NULL);
2839 SM_EXCEPT(exc, "[!F]*")
2841 /* An exception occurred while processing RCPT */
2842 e->e_flags &= ~(EF_FATALERRS|EF_PM_NOTIFY);
2846 if (smtp.sm_milterlist && smtp.sm_milterize &&
2847 !bitset(EF_DISCARD, e->e_flags) &&
2848 !milter_cmd_done && milter_cmd_safe)
2853 macdefine(&e->e_macro, A_PERM,
2854 macid("{rcpt_mailer}"), "error");
2856 /* how to get the error codes? */
2857 if (addr_st.q_host != NULL)
2858 macdefine(&e->e_macro, A_PERM,
2859 macid("{rcpt_host}"),
2861 else if (a != NULL && a->q_status != NULL)
2862 macdefine(&e->e_macro, A_PERM,
2863 macid("{rcpt_host}"),
2866 if (addr_st.q_user != NULL)
2867 macdefine(&e->e_macro, A_PERM,
2868 macid("{rcpt_addr}"),
2870 else if (a != NULL && a->q_rstatus != NULL)
2871 macdefine(&e->e_macro, A_PERM,
2872 macid("{rcpt_addr}"),
2875 response = milter_envrcpt(args, e, &state,
2877 milter_cmd_done = true;
2879 macdefine(&e->e_macro, A_PERM,
2880 macid("{rcpt_mailer}"), NULL);
2881 macdefine(&e->e_macro, A_PERM,
2882 macid("{rcpt_host}"), NULL);
2883 macdefine(&e->e_macro, A_PERM,
2884 macid("{rcpt_addr}"), NULL);
2886 if (smtp.sm_milterlist && smtp.sm_milterize &&
2887 milter_rcpt_added && milter_cmd_done &&
2890 (void) removefromlist(addr, &e->e_sendqueue, e);
2891 milter_cmd_fail = false;
2892 if (smtp.sm_e_nrcpts_orig < e->e_nrcpts)
2893 e->e_nrcpts = smtp.sm_e_nrcpts_orig;
2900 case CMDDATA: /* data -- text of mail */
2902 if (!smtp_data(&smtp, e))
2906 case CMDRSET: /* rset -- reset state */
2908 message("451 4.0.0 Test failure");
2910 message("250 2.0.0 Reset state");
2911 CLEAR_STATE(cmdbuf);
2914 case CMDVRFY: /* vrfy -- verify address */
2915 case CMDEXPN: /* expn -- expand address */
2916 vrfy = c->cmd_code == CMDVRFY;
2917 DELAY_CONN(vrfy ? "VRFY" : "EXPN");
2921 sm_syslog(LOG_INFO, e->e_id,
2922 "SMTP %s command (%.100s) from %s tempfailed (due to previous checks)",
2923 vrfy ? "VRFY" : "EXPN",
2926 /* RFC 821 doesn't allow 4xy reply code */
2927 usrerr("550 5.7.1 Please try again later");
2930 wt = checksmtpattack(&n_verifies, MAXVRFYCOMMANDS,
2931 false, vrfy ? "VRFY" : "EXPN", e);
2933 previous = curtime();
2934 if ((vrfy && bitset(PRIV_NOVRFY, PrivacyFlags)) ||
2935 (!vrfy && !bitset(SRV_OFFER_EXPN, features)))
2938 message("252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)");
2940 message("502 5.7.0 Sorry, we do not allow this operation");
2942 sm_syslog(LOG_INFO, e->e_id,
2943 "%s: %s [rejected]",
2945 shortenstring(inp, MAXSHORTSTR));
2948 else if (!gothello &&
2949 bitset(vrfy ? PRIV_NEEDVRFYHELO : PRIV_NEEDEXPNHELO,
2952 usrerr("503 5.0.0 I demand that you introduce yourself first");
2958 sm_syslog(LOG_INFO, e->e_id, "%s: %s",
2960 shortenstring(inp, MAXSHORTSTR));
2966 e->e_flags |= EF_VRFYONLY;
2967 while (*p != '\0' && isascii(*p) && isspace(*p))
2971 usrerr("501 5.5.2 Argument required");
2975 /* do config file checking of the address */
2976 if (rscheck(vrfy ? "check_vrfy" : "check_expn",
2977 p, NULL, e, RSF_RMCOMM,
2978 3, NULL, NOQID, NULL) != EX_OK ||
2980 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2981 (void) sendtolist(p, NULLADDR, &vrfyqueue, 0, e);
2987 t = wt - (curtime() - previous);
2992 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2993 if (vrfyqueue == NULL)
2995 usrerr("554 5.5.2 Nothing to %s", vrfy ? "VRFY" : "EXPN");
2997 while (vrfyqueue != NULL)
2999 if (!QS_IS_UNDELIVERED(vrfyqueue->q_state))
3001 vrfyqueue = vrfyqueue->q_next;
3005 /* see if there is more in the vrfy list */
3007 while ((a = a->q_next) != NULL &&
3008 (!QS_IS_UNDELIVERED(a->q_state)))
3010 printvrfyaddr(vrfyqueue, a == NULL, vrfy);
3014 SM_EXCEPT(exc, "[!F]*")
3017 ** An exception occurred while processing VRFY/EXPN
3026 case CMDETRN: /* etrn -- force queue flush */
3029 /* Don't leak queue information via debug flags */
3030 if (!bitset(SRV_OFFER_ETRN, features) || UseMSP ||
3031 (RealUid != 0 && RealUid != TrustedUid &&
3034 /* different message for MSA ? */
3035 message("502 5.7.0 Sorry, we do not allow this operation");
3037 sm_syslog(LOG_INFO, e->e_id,
3038 "%s: %s [rejected]",
3040 shortenstring(inp, MAXSHORTSTR));
3046 sm_syslog(LOG_INFO, e->e_id,
3047 "SMTP ETRN command (%.100s) from %s tempfailed (due to previous checks)",
3049 usrerr(MSG_TEMPFAIL);
3055 usrerr("500 5.5.2 Parameter required");
3059 /* crude way to avoid denial-of-service attacks */
3060 STOP_IF_ATTACK(checksmtpattack(&n_etrn, MAXETRNCOMMANDS,
3064 ** Do config file checking of the parameter.
3065 ** Even though we have srv_features now, we still
3066 ** need this ruleset because the former is called
3067 ** when the connection has been established, while
3068 ** this ruleset is called when the command is
3069 ** actually issued and therefore has all information
3070 ** available to make a decision.
3073 if (rscheck("check_etrn", p, NULL, e,
3074 RSF_RMCOMM, 3, NULL, NOQID, NULL)
3080 sm_syslog(LOG_INFO, e->e_id,
3081 "%s: ETRN %s", CurSmtpClient,
3082 shortenstring(p, MAXSHORTSTR));
3090 qgrp = name2qid(id);
3091 if (!ISVALIDQGRP(qgrp))
3093 usrerr("459 4.5.4 Queue %s unknown",
3097 for (i = 0; i < NumQueue && Queue[i] != NULL;
3099 Queue[i]->qg_nextrun = (time_t) -1;
3100 Queue[qgrp]->qg_nextrun = 0;
3101 ok = run_work_group(Queue[qgrp]->qg_wgrp,
3102 RWG_FORK|RWG_FORCE);
3103 if (ok && Errors == 0)
3104 message("250 2.0.0 Queuing for queue group %s started", id);
3113 new = (QUEUE_CHAR *) sm_malloc(sizeof(QUEUE_CHAR));
3116 syserr("500 5.5.0 ETRN out of memory");
3119 new->queue_match = id;
3120 new->queue_negate = false;
3121 new->queue_next = NULL;
3122 QueueLimitRecipient = new;
3123 ok = runqueue(true, false, false, true);
3124 sm_free(QueueLimitRecipient); /* XXX */
3125 QueueLimitRecipient = NULL;
3126 if (ok && Errors == 0)
3127 message("250 2.0.0 Queuing for node %s started", p);
3130 case CMDHELP: /* help -- give user info */
3135 case CMDNOOP: /* noop -- do nothing */
3137 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
3139 message("250 2.0.0 OK");
3142 case CMDQUIT: /* quit -- leave mail */
3143 message("221 2.0.0 %s closing connection", MyHostName);
3145 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3146 #endif /* PIPELINING */
3148 if (smtp.sm_nrcpts > 0)
3149 logundelrcpts(e, "aborted by sender", 9, false);
3151 /* arrange to ignore any current send list */
3152 e->e_sendqueue = NULL;
3155 /* shutdown TLS connection */
3158 (void) endtls(srv_ssl, "server");
3161 #endif /* STARTTLS */
3163 if (authenticating == SASL_IS_AUTH)
3165 sasl_dispose(&conn);
3166 authenticating = SASL_NOT_AUTH;
3167 /* XXX sasl_done(); this is a child */
3172 /* avoid future 050 messages */
3176 /* close out milter filters */
3181 sm_dprintf("QUIT: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",
3183 bitset(EF_LOGSENDER, e->e_flags),
3185 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3187 e->e_flags &= ~EF_LOGSENDER;
3189 if (lognullconnection && LogLevel > 5 &&
3194 d = macvalue(macid("{daemon_name}"), e);
3199 ** even though this id is "bogus", it makes
3200 ** it simpler to "grep" related events, e.g.,
3201 ** timeouts for the same connection.
3204 sm_syslog(LOG_INFO, e->e_id,
3205 "%s did not issue MAIL/EXPN/VRFY/ETRN during connection to %s",
3210 /* return to handle next connection */
3213 finis(true, true, ExitStat);
3216 /* just to avoid bogus warning from some compilers */
3219 case CMDVERB: /* set verbose mode */
3221 if (!bitset(SRV_OFFER_EXPN, features) ||
3222 !bitset(SRV_OFFER_VERB, features))
3224 /* this would give out the same info */
3225 message("502 5.7.0 Verbose unavailable");
3228 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
3231 set_delivery_mode(SM_DELIVER, e);
3232 message("250 2.0.0 Verbose mode");
3236 case CMDDBGQSHOW: /* show queues */
3237 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3239 printaddr(smioout, e->e_sendqueue, true);
3242 case CMDDBGDEBUG: /* set debug mode */
3243 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1");
3245 message("200 2.0.0 Debug set");
3248 #else /* SMTPDEBUG */
3249 case CMDDBGQSHOW: /* show queues */
3250 case CMDDBGDEBUG: /* set debug mode */
3251 #endif /* SMTPDEBUG */
3252 case CMDLOGBOGUS: /* bogus command */
3253 DELAY_CONN("Bogus");
3255 sm_syslog(LOG_CRIT, e->e_id,
3256 "\"%s\" command from %s (%.100s)",
3257 c->cmd_name, CurSmtpClient,
3258 anynet_ntoa(&RealHostAddr));
3261 case CMDERROR: /* unknown command */
3262 #if MAXBADCOMMANDS > 0
3263 if (++n_badcmds > MAXBADCOMMANDS)
3266 message("421 4.7.0 %s Too many bad commands; closing connection",
3269 /* arrange to ignore any current send list */
3270 e->e_sendqueue = NULL;
3273 #endif /* MAXBADCOMMANDS > 0 */
3275 #if MILTER && SMFI_VERSION > 2
3276 if (smtp.sm_milterlist && smtp.sm_milterize &&
3277 !bitset(EF_DISCARD, e->e_flags))
3282 if (MilterLogLevel > 9)
3283 sm_syslog(LOG_INFO, e->e_id,
3284 "Sending \"%s\" to Milter", inp);
3285 response = milter_unknown(inp, e, &state);
3286 MILTER_REPLY("unknown");
3287 if (state == SMFIR_REPLYCODE ||
3288 state == SMFIR_REJECT ||
3289 state == SMFIR_TEMPFAIL ||
3290 state == SMFIR_SHUTDOWN)
3292 /* MILTER_REPLY already gave an error */
3296 #endif /* MILTER && SMFI_VERSION > 2 */
3298 usrerr("500 5.5.1 Command unrecognized: \"%s\"",
3299 shortenstring(inp, MAXSHORTSTR));
3303 DELAY_CONN("Unimpl");
3304 usrerr("502 5.5.1 Command not implemented: \"%s\"",
3305 shortenstring(inp, MAXSHORTSTR));
3309 DELAY_CONN("default");
3311 syserr("500 5.5.0 smtp: unknown code %d", c->cmd_code);
3318 SM_EXCEPT(exc, "[!F]*")
3321 ** The only possible exception is "E:mta.quickabort".
3322 ** There is nothing to do except fall through and loop.
3329 ** SMTP_DATA -- implement the SMTP DATA command.
3332 ** smtp -- status of SMTP connection.
3336 ** true iff SMTP session can continue.
3339 ** possibly sends message.
3357 unsigned int features;
3360 SmtpPhase = "server DATA";
3361 if (!smtp->sm_gotmail)
3363 usrerr("503 5.0.0 Need MAIL command");
3366 else if (smtp->sm_nrcpts <= 0)
3368 usrerr("503 5.0.0 Need RCPT (recipient)");
3371 (void) sm_snprintf(buf, sizeof(buf), "%u", smtp->sm_nrcpts);
3372 if (rscheck("check_data", buf, NULL, e,
3373 RSF_RMCOMM|RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL,
3374 e->e_id, NULL) != EX_OK)
3377 #if MILTER && SMFI_VERSION > 3
3378 if (smtp->sm_milterlist && smtp->sm_milterize &&
3379 !bitset(EF_DISCARD, e->e_flags))
3383 int savelogusrerrs = LogUsrErrs;
3385 response = milter_data_cmd(e, &state);
3388 case SMFIR_REPLYCODE:
3389 if (MilterLogLevel > 3)
3391 sm_syslog(LOG_INFO, e->e_id,
3392 "Milter: cmd=data, reject=%s",
3396 #if _FFR_MILTER_ENHSC
3397 if (ISSMTPCODE(response))
3398 (void) extenhsc(response + 4, ' ', e->e_enhsc);
3399 #endif /* _FFR_MILTER_ENHSC */
3402 if (strncmp(response, "421 ", 4) == 0
3403 || strncmp(response, "421-", 4) == 0)
3405 e->e_sendqueue = NULL;
3411 if (MilterLogLevel > 3)
3413 sm_syslog(LOG_INFO, e->e_id,
3414 "Milter: cmd=data, reject=550 5.7.1 Command rejected");
3417 #if _FFR_MILTER_ENHSC
3418 (void) sm_strlcpy(e->e_enhsc, "5.7.1",
3419 sizeof(e->e_enhsc));
3420 #endif /* _FFR_MILTER_ENHSC */
3421 usrerr("550 5.7.1 Command rejected");
3425 if (MilterLogLevel > 3)
3426 sm_syslog(LOG_INFO, e->e_id,
3427 "Milter: cmd=data, discard");
3428 e->e_flags |= EF_DISCARD;
3431 case SMFIR_TEMPFAIL:
3432 if (MilterLogLevel > 3)
3434 sm_syslog(LOG_INFO, e->e_id,
3435 "Milter: cmd=data, reject=%s",
3439 #if _FFR_MILTER_ENHSC
3440 (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc);
3441 #endif /* _FFR_MILTER_ENHSC */
3442 usrerr(MSG_TEMPFAIL);
3445 case SMFIR_SHUTDOWN:
3446 if (MilterLogLevel > 3)
3448 sm_syslog(LOG_INFO, e->e_id,
3449 "Milter: cmd=data, reject=421 4.7.0 %s closing connection",
3453 usrerr("421 4.7.0 %s closing connection", MyHostName);
3454 e->e_sendqueue = NULL;
3457 LogUsrErrs = savelogusrerrs;
3458 if (response != NULL)
3459 sm_free(response); /* XXX */
3461 #endif /* MILTER && SMFI_VERSION > 3 */
3463 /* put back discard bit */
3464 if (smtp->sm_discard)
3465 e->e_flags |= EF_DISCARD;
3467 /* check to see if we need to re-expand aliases */
3468 /* also reset QS_BADADDR on already-diagnosted addrs */
3469 doublequeue = false;
3470 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3472 if (QS_IS_VERIFIED(a->q_state) &&
3473 !bitset(EF_DISCARD, e->e_flags))
3475 /* need to re-expand aliases */
3478 if (QS_IS_BADADDR(a->q_state))
3480 /* make this "go away" */
3481 a->q_state = QS_DONTSEND;
3485 /* collect the text of the message */
3486 SmtpPhase = "collect";
3489 collect(InChannel, true, NULL, e, true);
3491 /* redefine message size */
3492 (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize));
3493 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3495 /* rscheck() will set Errors or EF_DISCARD if it trips */
3496 (void) rscheck("check_eom", buf, NULL, e, RSF_UNSTRUCTURED|RSF_COUNT,
3497 3, NULL, e->e_id, NULL);
3500 milteraccept = true;
3501 if (smtp->sm_milterlist && smtp->sm_milterize &&
3503 !bitset(EF_DISCARD, e->e_flags))
3508 response = milter_data(e, &state);
3511 case SMFIR_REPLYCODE:
3512 if (MilterLogLevel > 3)
3513 sm_syslog(LOG_INFO, e->e_id,
3514 "Milter: data, reject=%s",
3516 milteraccept = false;
3517 #if _FFR_MILTER_ENHSC
3518 if (ISSMTPCODE(response))
3519 (void) extenhsc(response + 4, ' ', e->e_enhsc);
3520 #endif /* _FFR_MILTER_ENHSC */
3522 if (strncmp(response, "421 ", 4) == 0
3523 || strncmp(response, "421-", 4) == 0)
3528 milteraccept = false;
3529 if (MilterLogLevel > 3)
3530 sm_syslog(LOG_INFO, e->e_id,
3531 "Milter: data, reject=554 5.7.1 Command rejected");
3532 usrerr("554 5.7.1 Command rejected");
3536 if (MilterLogLevel > 3)
3537 sm_syslog(LOG_INFO, e->e_id,
3538 "Milter: data, discard");
3539 milteraccept = false;
3540 e->e_flags |= EF_DISCARD;
3543 case SMFIR_TEMPFAIL:
3544 if (MilterLogLevel > 3)
3545 sm_syslog(LOG_INFO, e->e_id,
3546 "Milter: data, reject=%s",
3548 milteraccept = false;
3549 #if _FFR_MILTER_ENHSC
3550 (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc);
3551 #endif /* _FFR_MILTER_ENHSC */
3552 usrerr(MSG_TEMPFAIL);
3555 case SMFIR_SHUTDOWN:
3556 if (MilterLogLevel > 3)
3557 sm_syslog(LOG_INFO, e->e_id,
3558 "Milter: data, reject=421 4.7.0 %s closing connection",
3560 milteraccept = false;
3561 usrerr("421 4.7.0 %s closing connection", MyHostName);
3565 if (response != NULL)
3569 /* Milter may have changed message size */
3570 (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize));
3571 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3573 /* abort message filters that didn't get the body & log msg is OK */
3574 if (smtp->sm_milterlist && smtp->sm_milterize)
3577 if (milteraccept && MilterLogLevel > 9)
3578 sm_syslog(LOG_INFO, e->e_id, "Milter accept: message");
3582 ** If SuperSafe is SAFE_REALLY_POSTMILTER, and we don't have milter or
3583 ** milter accepted message, sync it now
3585 ** XXX This is almost a copy of the code in collect(): put it into
3586 ** a function that is called from both places?
3589 if (milteraccept && SuperSafe == SAFE_REALLY_POSTMILTER)
3592 SM_FILE_T *volatile df;
3596 dfname = queuename(e, DATAFL_LETTER);
3597 if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0
3603 if (save_errno == EEXIST)
3608 if (stat(dfname, &st) < 0)
3611 syserr("@collect: bfcommit(%s): already on disk, size=%ld",
3612 dfname, (long) st.st_size);
3613 dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
3615 dumpfd(dfd, true, true);
3618 dferror(df, "bfcommit", e);
3620 finis(save_errno != EEXIST, true, ExitStat);
3622 else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0)
3624 dferror(df, "sm_io_getinfo", e);
3626 finis(true, true, ExitStat);
3629 else if (fsync(afd) < 0)
3631 dferror(df, "fsync", e);
3633 finis(true, true, ExitStat);
3636 else if (sm_io_close(df, SM_TIME_DEFAULT) < 0)
3638 dferror(df, "sm_io_close", e);
3640 finis(true, true, ExitStat);
3644 /* Now reopen the df file */
3645 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
3646 SM_IO_RDONLY, NULL);
3647 if (e->e_dfp == NULL)
3649 /* we haven't acked receipt yet, so just chuck this */
3650 syserr("@Cannot reopen %s", dfname);
3651 finis(true, true, ExitStat);
3657 /* Check if quarantining stats should be updated */
3658 if (e->e_quarmsg != NULL)
3659 markstats(e, NULL, STATS_QUARANTINE);
3662 ** If a header/body check (header checks or milter)
3663 ** set EF_DISCARD, don't queueup the message --
3664 ** that would lose the EF_DISCARD bit and deliver
3668 if (bitset(EF_DISCARD, e->e_flags))
3669 doublequeue = false;
3671 aborting = Errors > 0;
3672 if (!(aborting || bitset(EF_DISCARD, e->e_flags)) &&
3673 (QueueMode == QM_QUARANTINE || e->e_quarmsg == NULL) &&
3674 !split_by_recipient(e))
3675 aborting = bitset(EF_FATALERRS, e->e_flags);
3681 /* Log who the mail would have gone to */
3682 logundelrcpts(e, e->e_message, 8, false);
3685 ** If something above refused the message, we still haven't
3686 ** accepted responsibility for it. Don't send DSNs.
3689 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
3690 q->q_flags &= ~Q_PINGFLAGS;
3697 /* from now on, we have to operate silently */
3702 ** Clear message, it may contain an error from the SMTP dialogue.
3703 ** This error must not show up in the queue.
3704 ** Some error message should show up, e.g., alias database
3705 ** not available, but others shouldn't, e.g., from check_rcpt.
3708 e->e_message = NULL;
3712 ** Arrange to send to everyone.
3713 ** If sending to multiple people, mail back
3714 ** errors rather than reporting directly.
3715 ** In any case, don't mail back errors for
3716 ** anything that has happened up to
3717 ** now (the other end will do this).
3718 ** Truncate our transcript -- the mail has gotten
3719 ** to us successfully, and if we have
3720 ** to mail this back, it will be easier
3722 ** Then send to everyone.
3723 ** Finally give a reply code. If an error has
3724 ** already been given, don't mail a
3726 ** We goose error returns by clearing error bit.
3729 SmtpPhase = "delivery";
3730 (void) sm_io_setinfo(e->e_xfp, SM_BF_TRUNCATE, NULL);
3734 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
3735 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
3736 #endif /* NAMED_BIND */
3739 for (ee = e; ee != NULL; ee = ee->e_sibling)
3741 /* make sure we actually do delivery */
3742 ee->e_flags &= ~EF_CLRQUEUE;
3744 /* from now on, operate silently */
3745 ee->e_errormode = EM_MAIL;
3749 /* make sure it is in the queue */
3750 queueup(ee, false, true);
3756 /* send to all recipients */
3759 if (SM_DM_ONE == e->e_sendmode)
3761 if (NotFirstDelivery)
3764 e->e_sendmode = SM_QUEUE;
3769 NotFirstDelivery = true;
3772 #endif /* _FFR_DM_ONE */
3778 /* put back id for SMTP logging in putoutmsg() */
3779 oldid = CurEnv->e_id;
3782 /* issue success message */
3784 if (MessageAccept != NULL && *MessageAccept != '\0')
3788 expand(MessageAccept, msg, sizeof(msg), e);
3789 message("250 2.0.0 %s", msg);
3792 #endif /* _FFR_MSG_ACCEPT */
3793 message("250 2.0.0 %s Message accepted for delivery", id);
3794 CurEnv->e_id = oldid;
3796 /* if we just queued, poke it */
3799 bool anything_to_send = false;
3802 for (ee = e; ee != NULL; ee = ee->e_sibling)
3804 if (WILL_BE_QUEUED(ee->e_sendmode))
3806 if (shouldqueue(ee->e_msgpriority, ee->e_ctime))
3808 ee->e_sendmode = SM_QUEUE;
3811 else if (QueueMode != QM_QUARANTINE &&
3812 ee->e_quarmsg != NULL)
3814 ee->e_sendmode = SM_QUEUE;
3817 anything_to_send = true;
3819 /* close all the queue files */
3821 if (ee->e_dfp != NULL)
3823 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
3828 if (anything_to_send)
3832 ** XXX if we don't do this, we get 250 twice
3833 ** because it is also flushed in the child.
3836 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3837 #endif /* PIPELINING */
3838 (void) doworklist(e, true, true);
3844 sm_dprintf("abortmessage: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",
3845 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);
3846 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3848 e->e_flags &= ~EF_LOGSENDER;
3850 /* clean up a bit */
3851 smtp->sm_gotmail = false;
3854 ** Call dropenvelope if and only if the envelope is *not*
3855 ** being processed by the child process forked by doworklist().
3858 if (aborting || bitset(EF_DISCARD, e->e_flags))
3859 (void) dropenvelope(e, true, false);
3862 for (ee = e; ee != NULL; ee = ee->e_sibling)
3865 QueueMode != QM_QUARANTINE &&
3866 ee->e_quarmsg != NULL)
3868 (void) dropenvelope(ee, true, false);
3871 if (WILL_BE_QUEUED(ee->e_sendmode))
3872 (void) dropenvelope(ee, true, false);
3877 features = e->e_features;
3878 sm_rpool_free(e->e_rpool);
3879 newenvelope(e, e, sm_rpool_new_x(NULL));
3880 e->e_flags = BlankEnvelope.e_flags;
3881 e->e_features = features;
3883 /* restore connection quarantining */
3884 if (smtp->sm_quarmsg == NULL)
3886 e->e_quarmsg = NULL;
3887 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
3891 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, smtp->sm_quarmsg);
3892 macdefine(&e->e_macro, A_PERM,
3893 macid("{quarantine}"), e->e_quarmsg);
3898 ** LOGUNDELRCPTS -- log undelivered (or all) recipients.
3902 ** msg -- message for Stat=
3903 ** level -- log level.
3904 ** all -- log all recipients.
3910 ** logs undelivered (or all) recipients
3914 logundelrcpts(e, msg, level, all)
3922 if (LogLevel <= level || msg == NULL || *msg == '\0')
3925 /* Clear $h so relay= doesn't get mislogged by logdelivery() */
3926 macdefine(&e->e_macro, A_PERM, 'h', NULL);
3928 /* Log who the mail would have gone to */
3929 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3931 if (!QS_IS_UNDELIVERED(a->q_state) && !all)
3933 e->e_to = a->q_paddr;
3934 logdelivery(NULL, NULL,
3935 #if _FFR_MILTER_ENHSC
3936 (a->q_status == NULL && e->e_enhsc[0] != '\0')
3938 #endif /* _FFR_MILTER_ENHSC */
3940 msg, NULL, (time_t) 0, e);
3945 ** CHECKSMTPATTACK -- check for denial-of-service attack by repetition
3948 ** pcounter -- pointer to a counter for this command.
3949 ** maxcount -- maximum value for this counter before we
3951 ** waitnow -- sleep now (in this routine)?
3952 ** cname -- command name for logging.
3953 ** e -- the current envelope.
3957 ** STOP_ATTACK if twice as many commands as allowed and
3961 ** Slows down if we seem to be under attack.
3965 checksmtpattack(pcounter, maxcount, waitnow, cname, e)
3966 volatile unsigned int *pcounter;
3967 unsigned int maxcount;
3972 if (maxcount <= 0) /* no limit */
3975 if (++(*pcounter) >= maxcount)
3980 if (*pcounter == maxcount && LogLevel > 5)
3982 sm_syslog(LOG_INFO, e->e_id,
3983 "%s: possible SMTP attack: command=%.40s, count=%u",
3984 CurSmtpClient, cname, *pcounter);
3986 shift = *pcounter - maxcount;
3988 if (shift > MAXSHIFT || s >= MAXTIMEOUT || s <= 0)
3991 #define IS_ATTACK(s) ((MaxChildren > 0 && *pcounter >= maxcount * 2) \
3992 ? STOP_ATTACK : (time_t) s)
3994 /* sleep at least 1 second before returning */
3995 (void) sleep(*pcounter / maxcount);
3996 s -= *pcounter / maxcount;
3997 if (s >= MAXTIMEOUT || s < 0)
3999 if (waitnow && s > 0)
4002 return IS_ATTACK(0);
4004 return IS_ATTACK(s);
4009 ** SETUP_SMTPD_IO -- setup I/O fd correctly for the SMTP server
4018 ** may change I/O fd.
4024 int inchfd, outchfd, outfd;
4026 inchfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
4027 outchfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
4028 outfd = sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL);
4029 if (outchfd != outfd)
4031 /* arrange for debugging output to go to remote host */
4032 (void) dup2(outchfd, outfd);
4036 ** if InChannel and OutChannel are stdin/stdout
4037 ** and connected to ttys
4038 ** and fcntl(STDIN, F_SETFL, O_NONBLOCKING) also changes STDOUT,
4039 ** then "chain" them together.
4042 if (inchfd == STDIN_FILENO && outchfd == STDOUT_FILENO &&
4043 isatty(inchfd) && isatty(outchfd))
4045 int inmode, outmode;
4047 inmode = fcntl(inchfd, F_GETFL, 0);
4051 sm_syslog(LOG_INFO, NOQID,
4052 "fcntl(inchfd, F_GETFL) failed: %s",
4053 sm_errstring(errno));
4056 outmode = fcntl(outchfd, F_GETFL, 0);
4060 sm_syslog(LOG_INFO, NOQID,
4061 "fcntl(outchfd, F_GETFL) failed: %s",
4062 sm_errstring(errno));
4065 if (bitset(O_NONBLOCK, inmode) ||
4066 bitset(O_NONBLOCK, outmode) ||
4067 fcntl(inchfd, F_SETFL, inmode | O_NONBLOCK) == -1)
4069 outmode = fcntl(outchfd, F_GETFL, 0);
4070 if (outmode != -1 && bitset(O_NONBLOCK, outmode))
4072 /* changing InChannel also changes OutChannel */
4073 sm_io_automode(OutChannel, InChannel);
4074 if (tTd(97, 4) && LogLevel > 9)
4075 sm_syslog(LOG_INFO, NOQID,
4076 "set automode for I (%d)/O (%d) in SMTP server",
4080 /* undo change of inchfd */
4081 (void) fcntl(inchfd, F_SETFL, inmode);
4085 ** SKIPWORD -- skip a fixed word.
4088 ** p -- place to start looking.
4089 ** w -- word to skip.
4096 ** clobbers the p data area.
4101 register char *volatile p;
4107 /* find beginning of word */
4111 /* find end of word */
4112 while (*p != '\0' && *p != ':' && !(isascii(*p) && isspace(*p)))
4114 while (isascii(*p) && isspace(*p))
4119 usrerr("501 5.5.2 Syntax error in parameters scanning \"%s\"",
4120 shortenstring(firstp, MAXSHORTSTR));
4129 /* see if the input word matches desired word */
4130 if (sm_strcasecmp(q, w))
4137 ** RESET_MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
4140 ** e -- the envelope.
4147 reset_mail_esmtp_args(e)
4150 /* "size": no reset */
4153 SevenBitInput = SevenBitInput_Saved;
4154 e->e_bodytype = NULL;
4158 macdefine(&e->e_macro, A_PERM, macid("{dsn_envid}"), NULL);
4161 e->e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
4162 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), NULL);
4166 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"), NULL);
4167 e->e_auth_param = "";
4168 # if _FFR_AUTH_PASSING
4169 macdefine(&BlankEnvelope.e_macro, A_PERM,
4170 macid("{auth_author}"), NULL);
4171 # endif /* _FFR_AUTH_PASSING */
4175 e->e_deliver_by = 0;
4180 ** MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
4183 ** a -- address (unused, for compatibility with rcpt_esmtp_args)
4184 ** kp -- the parameter key.
4185 ** vp -- the value of that parameter.
4186 ** e -- the envelope.
4193 mail_esmtp_args(a, kp, vp, e)
4199 if (sm_strcasecmp(kp, "size") == 0)
4203 usrerr("501 5.5.2 SIZE requires a value");
4206 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), vp);
4208 e->e_msgsize = strtol(vp, (char **) NULL, 10);
4209 if (e->e_msgsize == LONG_MAX && errno == ERANGE)
4211 usrerr("552 5.2.3 Message size exceeds maximum value");
4214 if (e->e_msgsize < 0)
4216 usrerr("552 5.2.3 Message size invalid");
4220 else if (sm_strcasecmp(kp, "body") == 0)
4224 usrerr("501 5.5.2 BODY requires a value");
4227 else if (sm_strcasecmp(vp, "8bitmime") == 0)
4229 SevenBitInput = false;
4231 else if (sm_strcasecmp(vp, "7bit") == 0)
4233 SevenBitInput = true;
4237 usrerr("501 5.5.4 Unknown BODY type %s", vp);
4240 e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, vp);
4242 else if (sm_strcasecmp(kp, "envid") == 0)
4244 if (!bitset(SRV_OFFER_DSN, e->e_features))
4246 usrerr("504 5.7.0 Sorry, ENVID not supported, we do not allow DSN");
4251 usrerr("501 5.5.2 ENVID requires a value");
4256 usrerr("501 5.5.4 Syntax error in ENVID parameter value");
4259 if (e->e_envid != NULL)
4261 usrerr("501 5.5.0 Duplicate ENVID parameter");
4264 e->e_envid = sm_rpool_strdup_x(e->e_rpool, vp);
4265 macdefine(&e->e_macro, A_PERM,
4266 macid("{dsn_envid}"), e->e_envid);
4268 else if (sm_strcasecmp(kp, "ret") == 0)
4270 if (!bitset(SRV_OFFER_DSN, e->e_features))
4272 usrerr("504 5.7.0 Sorry, RET not supported, we do not allow DSN");
4277 usrerr("501 5.5.2 RET requires a value");
4280 if (bitset(EF_RET_PARAM, e->e_flags))
4282 usrerr("501 5.5.0 Duplicate RET parameter");
4285 e->e_flags |= EF_RET_PARAM;
4286 if (sm_strcasecmp(vp, "hdrs") == 0)
4287 e->e_flags |= EF_NO_BODY_RETN;
4288 else if (sm_strcasecmp(vp, "full") != 0)
4290 usrerr("501 5.5.2 Bad argument \"%s\" to RET", vp);
4293 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), vp);
4296 else if (sm_strcasecmp(kp, "auth") == 0)
4300 char *auth_param; /* the value of the AUTH=x */
4301 bool saveQuickAbort = QuickAbort;
4302 bool saveSuprErrs = SuprErrs;
4303 bool saveExitStat = ExitStat;
4307 usrerr("501 5.5.2 AUTH= requires a value");
4310 if (e->e_auth_param != NULL)
4312 usrerr("501 5.5.0 Duplicate AUTH parameter");
4315 if ((q = strchr(vp, ' ')) != NULL)
4318 len = strlen(vp) + 1;
4319 auth_param = xalloc(len);
4320 (void) sm_strlcpy(auth_param, vp, len);
4321 if (!xtextok(auth_param))
4323 usrerr("501 5.5.4 Syntax error in AUTH parameter value");
4324 /* just a warning? */
4328 /* XXX define this always or only if trusted? */
4329 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"),
4333 ** call Strust_auth to find out whether
4334 ** auth_param is acceptable (trusted)
4335 ** we shouldn't trust it if not authenticated
4336 ** (required by RFC, leave it to ruleset?)
4341 if (strcmp(auth_param, "<>") != 0 &&
4342 (rscheck("trust_auth", auth_param, NULL, e, RSF_RMCOMM,
4343 9, NULL, NOQID, NULL) != EX_OK || Errors > 0))
4347 q = e->e_auth_param;
4348 sm_dprintf("auth=\"%.100s\" not trusted user=\"%.100s\"\n",
4349 auth_param, (q == NULL) ? "" : q);
4353 e->e_auth_param = "<>";
4354 # if _FFR_AUTH_PASSING
4355 macdefine(&BlankEnvelope.e_macro, A_PERM,
4356 macid("{auth_author}"), NULL);
4357 # endif /* _FFR_AUTH_PASSING */
4362 sm_dprintf("auth=\"%.100s\" trusted\n", auth_param);
4363 e->e_auth_param = sm_rpool_strdup_x(e->e_rpool,
4366 sm_free(auth_param); /* XXX */
4370 QuickAbort = saveQuickAbort;
4371 SuprErrs = saveSuprErrs;
4372 ExitStat = saveExitStat;
4375 #define PRTCHAR(c) ((isascii(c) && isprint(c)) ? (c) : '?')
4378 ** "by" is only accepted if DeliverByMin >= 0.
4379 ** We maybe could add this to the list of server_features.
4382 else if (sm_strcasecmp(kp, "by") == 0 && DeliverByMin >= 0)
4388 usrerr("501 5.5.2 BY= requires a value");
4392 e->e_deliver_by = strtol(vp, &s, 10);
4393 if (e->e_deliver_by == LONG_MIN ||
4394 e->e_deliver_by == LONG_MAX ||
4395 e->e_deliver_by > 999999999l ||
4396 e->e_deliver_by < -999999999l)
4398 usrerr("501 5.5.2 BY=%s out of range", vp);
4401 if (s == NULL || *s != ';')
4403 usrerr("501 5.5.2 BY= missing ';'");
4407 ++s; /* XXX: spaces allowed? */
4409 switch (tolower(*s))
4412 e->e_dlvr_flag = DLVR_NOTIFY;
4415 e->e_dlvr_flag = DLVR_RETURN;
4416 if (e->e_deliver_by <= 0)
4418 usrerr("501 5.5.4 mode R requires BY time > 0");
4421 if (DeliverByMin > 0 && e->e_deliver_by > 0 &&
4422 e->e_deliver_by < DeliverByMin)
4424 usrerr("555 5.5.2 time %ld less than %ld",
4425 e->e_deliver_by, (long) DeliverByMin);
4430 usrerr("501 5.5.2 illegal by-mode '%c'", PRTCHAR(*s));
4433 ++s; /* XXX: spaces allowed? */
4435 switch (tolower(*s))
4438 e->e_dlvr_flag |= DLVR_TRACE;
4443 usrerr("501 5.5.2 illegal by-trace '%c'", PRTCHAR(*s));
4447 /* XXX: check whether more characters follow? */
4451 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4457 ** RCPT_ESMTP_ARGS -- process ESMTP arguments from RCPT line
4460 ** a -- the address corresponding to the To: parameter.
4461 ** kp -- the parameter key.
4462 ** vp -- the value of that parameter.
4463 ** e -- the envelope.
4470 rcpt_esmtp_args(a, kp, vp, e)
4476 if (sm_strcasecmp(kp, "notify") == 0)
4480 if (!bitset(SRV_OFFER_DSN, e->e_features))
4482 usrerr("504 5.7.0 Sorry, NOTIFY not supported, we do not allow DSN");
4487 usrerr("501 5.5.2 NOTIFY requires a value");
4490 a->q_flags &= ~(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY);
4491 a->q_flags |= QHASNOTIFY;
4492 macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), vp);
4494 if (sm_strcasecmp(vp, "never") == 0)
4496 for (p = vp; p != NULL; vp = p)
4500 s = p = strchr(p, ',');
4503 if (sm_strcasecmp(vp, "success") == 0)
4504 a->q_flags |= QPINGONSUCCESS;
4505 else if (sm_strcasecmp(vp, "failure") == 0)
4506 a->q_flags |= QPINGONFAILURE;
4507 else if (sm_strcasecmp(vp, "delay") == 0)
4508 a->q_flags |= QPINGONDELAY;
4511 usrerr("501 5.5.4 Bad argument \"%s\" to NOTIFY",
4519 else if (sm_strcasecmp(kp, "orcpt") == 0)
4523 if (!bitset(SRV_OFFER_DSN, e->e_features))
4525 usrerr("504 5.7.0 Sorry, ORCPT not supported, we do not allow DSN");
4530 usrerr("501 5.5.2 ORCPT requires a value");
4533 if (a->q_orcpt != NULL)
4535 usrerr("501 5.5.0 Duplicate ORCPT parameter");
4538 p = strchr(vp, ';');
4541 usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4545 if (!isatom(vp) || !xtextok(p + 1))
4548 usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4552 a->q_orcpt = sm_rpool_strdup_x(e->e_rpool, vp);
4556 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4561 ** PRINTVRFYADDR -- print an entry in the verify queue
4564 ** a -- the address to print.
4565 ** last -- set if this is the last one.
4566 ** vrfy -- set if this is a VRFY command.
4572 ** Prints the appropriate 250 codes.
4574 #define OFFF (3 + 1 + 5 + 1) /* offset in fmt: SMTP reply + enh. code */
4577 printvrfyaddr(a, last, vrfy)
4578 register ADDRESS *a;
4584 if (vrfy && a->q_mailer != NULL &&
4585 !bitnset(M_VRFY250, a->q_mailer->m_flags))
4586 (void) sm_strlcpy(fmtbuf, "252", sizeof(fmtbuf));
4588 (void) sm_strlcpy(fmtbuf, "250", sizeof(fmtbuf));
4589 fmtbuf[3] = last ? ' ' : '-';
4590 (void) sm_strlcpy(&fmtbuf[4], "2.1.5 ", sizeof(fmtbuf) - 4);
4591 if (a->q_fullname == NULL)
4593 if ((a->q_mailer == NULL ||
4594 a->q_mailer->m_addrtype == NULL ||
4595 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4596 strchr(a->q_user, '@') == NULL)
4597 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s@%s>",
4598 sizeof(fmtbuf) - OFFF);
4600 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s>",
4601 sizeof(fmtbuf) - OFFF);
4602 message(fmtbuf, a->q_user, MyHostName);
4606 if ((a->q_mailer == NULL ||
4607 a->q_mailer->m_addrtype == NULL ||
4608 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4609 strchr(a->q_user, '@') == NULL)
4610 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s@%s>",
4611 sizeof(fmtbuf) - OFFF);
4613 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s>",
4614 sizeof(fmtbuf) - OFFF);
4615 message(fmtbuf, a->q_fullname, a->q_user, MyHostName);
4621 ** SASLMECHS -- get list of possible AUTH mechanisms
4624 ** conn -- SASL connection info.
4625 ** mechlist -- output parameter for list of mechanisms.
4632 saslmechs(conn, mechlist)
4636 int len, num, result;
4638 /* "user" is currently unused */
4640 result = sasl_listmech(conn, NULL,
4641 "", " ", "", (const char **) mechlist,
4642 (unsigned int *)&len, &num);
4643 # else /* SASL >= 20000 */
4644 result = sasl_listmech(conn, "user", /* XXX */
4645 "", " ", "", mechlist,
4646 (unsigned int *)&len, (unsigned int *)&num);
4647 # endif /* SASL >= 20000 */
4648 if (result != SASL_OK)
4651 sm_syslog(LOG_WARNING, NOQID,
4652 "AUTH error: listmech=%d, num=%d",
4659 sm_syslog(LOG_INFO, NOQID,
4660 "AUTH: available mech=%s, allowed mech=%s",
4661 *mechlist, AuthMechanisms);
4662 *mechlist = intersect(AuthMechanisms, *mechlist, NULL);
4666 *mechlist = NULL; /* be paranoid... */
4667 if (result == SASL_OK && LogLevel > 9)
4668 sm_syslog(LOG_WARNING, NOQID,
4669 "AUTH warning: no mechanisms");
4676 ** PROXY_POLICY -- define proxy policy for AUTH
4680 ** context -- unused.
4681 ** requested_user -- authorization identity.
4682 ** rlen -- authorization identity length.
4683 ** auth_identity -- authentication identity.
4684 ** alen -- authentication identity length.
4685 ** def_realm -- default user realm.
4686 ** urlen -- user realm length.
4687 ** propctx -- unused.
4693 ** sets {auth_authen} macro.
4697 proxy_policy(conn, context, requested_user, rlen, auth_identity, alen,
4698 def_realm, urlen, propctx)
4701 const char *requested_user;
4703 const char *auth_identity;
4705 const char *def_realm;
4707 struct propctx *propctx;
4709 if (auth_identity == NULL)
4712 macdefine(&BlankEnvelope.e_macro, A_TEMP,
4713 macid("{auth_authen}"),
4714 xtextify((char *) auth_identity, "=<>\")"));
4718 # else /* SASL >= 20000 */
4721 ** PROXY_POLICY -- define proxy policy for AUTH
4724 ** context -- unused.
4725 ** auth_identity -- authentication identity.
4726 ** requested_user -- authorization identity.
4727 ** user -- allowed user (output).
4728 ** errstr -- possible error string (output).
4735 proxy_policy(context, auth_identity, requested_user, user, errstr)
4737 const char *auth_identity;
4738 const char *requested_user;
4740 const char **errstr;
4742 if (user == NULL || auth_identity == NULL)
4744 *user = newstr(auth_identity);
4747 # endif /* SASL >= 20000 */
4752 ** INITSRVTLS -- initialize server side TLS
4755 ** tls_ok -- should tls initialization be done?
4761 ** sets tls_ok_srv which is a static variable in this module.
4762 ** Do NOT remove assignments to it!
4772 /* do NOT remove assignment */
4773 tls_ok_srv = inittls(&srv_ctx, TLS_Srv_Opts, Srv_SSL_Options, true,
4774 SrvCertFile, SrvKeyFile,
4775 CACertPath, CACertFile, DHParams);
4778 #endif /* STARTTLS */
4780 ** SRVFEATURES -- get features for SMTP server
4783 ** e -- envelope (should be session context).
4784 ** clientname -- name of client.
4785 ** features -- default features for this invocation.
4791 /* table with options: it uses just one character, how about strings? */
4795 unsigned int srvf_flag;
4796 } srv_feat_table[] =
4798 { 'A', SRV_OFFER_AUTH },
4799 { 'B', SRV_OFFER_VERB },
4800 { 'C', SRV_REQ_SEC },
4801 { 'D', SRV_OFFER_DSN },
4802 { 'E', SRV_OFFER_ETRN },
4803 { 'L', SRV_REQ_AUTH },
4806 { 'N', SRV_NO_PIPE },
4807 # endif /* _FFR_NO_PIPE */
4808 { 'P', SRV_OFFER_PIPE },
4809 #endif /* PIPELINING */
4810 { 'R', SRV_VRFY_CLT }, /* same as V; not documented */
4811 { 'S', SRV_OFFER_TLS },
4812 /* { 'T', SRV_TMP_FAIL }, */
4813 { 'V', SRV_VRFY_CLT },
4814 { 'X', SRV_OFFER_EXPN },
4815 /* { 'Y', SRV_OFFER_VRFY }, */
4820 srvfeatures(e, clientname, features)
4823 unsigned int features;
4827 char pvpbuf[PSBUFSIZE];
4830 r = rscap("srv_features", clientname, "", e, &pvp, pvpbuf,
4834 if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
4836 if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0)
4837 return SRV_TMP_FAIL;
4840 ** General rule (see sendmail.h, d_flags):
4841 ** lower case: required/offered, upper case: Not required/available
4843 ** Since we can change some features per daemon, we have both
4844 ** cases here: turn on/off a feature.
4847 for (i = 1; pvp[i] != NULL; i++)
4853 if ((opt = srv_feat_table[j].srvf_opt) == '\0')
4856 sm_syslog(LOG_WARNING, e->e_id,
4857 "srvfeatures: unknown feature %s",
4863 features &= ~(srv_feat_table[j].srvf_flag);
4866 if (c == tolower(opt))
4868 features |= srv_feat_table[j].srvf_flag;
4878 ** HELP -- implement the HELP command.
4881 ** topic -- the topic we want help for.
4888 ** outputs the help file to message output.
4890 #define HELPVSTR "#vers "
4891 #define HELPVERSION 2
4898 register SM_FILE_T *hf;
4903 long sff = SFF_OPENASROOT|SFF_REGONLY;
4906 static int foundvers = -1;
4907 extern char Version[];
4909 if (DontLockReadFiles)
4911 if (!bitnset(DBS_HELPFILEINUNSAFEDIRPATH, DontBlameSendmail))
4912 sff |= SFF_SAFEDIRPATH;
4914 if (HelpFile == NULL ||
4915 (hf = safefopen(HelpFile, O_RDONLY, 0444, sff)) == NULL)
4919 message("502 5.3.0 Sendmail %s -- HELP not implemented",
4924 if (topic == NULL || *topic == '\0')
4935 len = strlen(topic);
4937 while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0)
4941 if (foundvers < 0 &&
4942 strncmp(buf, HELPVSTR, strlen(HELPVSTR)) == 0)
4946 if (sm_io_sscanf(buf + strlen(HELPVSTR), "%d",
4952 if (strncmp(buf, topic, len) == 0)
4958 /* print version if no/old vers# in file */
4959 if (foundvers < 2 && !noinfo)
4960 message("214-2.0.0 This is Sendmail version %s", Version);
4962 p = strpbrk(buf, " \t");
4964 p = buf + strlen(buf) - 1;
4971 int lbs = sizeof(buf) - (p - buf);
4973 lbp = translate_dollars(p, p, &lbs);
4974 expand(lbp, inp, sizeof(inp), e);
4979 message("214-2.0.0 %s", p);
4985 message("504 5.3.0 HELP topic \"%.10s\" unknown", topic);
4987 message("214 2.0.0 End of HELP info");
4989 if (foundvers != 0 && foundvers < HELPVERSION)
4992 sm_syslog(LOG_WARNING, e->e_id,
4993 "%s too old (require version %d)",
4994 HelpFile, HELPVERSION);
4996 /* avoid log next time */
5000 (void) sm_io_close(hf, SM_TIME_DEFAULT);
5005 ** RESET_SASLCONN -- reset SASL connection data
5008 ** conn -- SASL connection context
5009 ** hostname -- host name
5010 ** various connection data
5017 reset_saslconn(sasl_conn_t **conn, char *hostname,
5019 char *remoteip, char *localip,
5020 char *auth_id, sasl_ssf_t * ext_ssf)
5021 # else /* SASL >= 20000 */
5022 struct sockaddr_in *saddr_r, struct sockaddr_in *saddr_l,
5023 sasl_external_properties_t * ext_ssf)
5024 # endif /* SASL >= 20000 */
5030 result = sasl_server_new("smtp", hostname, NULL, NULL, NULL,
5033 /* use empty realm: only works in SASL > 1.5.5 */
5034 result = sasl_server_new("smtp", hostname, "", NULL, 0, conn);
5035 # else /* SASL >= 20000 */
5036 /* use no realm -> realm is set to hostname by SASL lib */
5037 result = sasl_server_new("smtp", hostname, NULL, NULL, 0,
5039 # endif /* SASL >= 20000 */
5040 if (result != SASL_OK)
5044 # if NETINET || NETINET6
5045 if (remoteip != NULL && *remoteip != '\0')
5046 result = sasl_setprop(*conn, SASL_IPREMOTEPORT, remoteip);
5047 if (result != SASL_OK)
5050 if (localip != NULL && *localip != '\0')
5051 result = sasl_setprop(*conn, SASL_IPLOCALPORT, localip);
5052 if (result != SASL_OK)
5054 # endif /* NETINET || NETINET6 */
5056 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
5057 if (result != SASL_OK)
5060 result = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, auth_id);
5061 if (result != SASL_OK)
5063 # else /* SASL >= 20000 */
5065 if (saddr_r != NULL)
5066 result = sasl_setprop(*conn, SASL_IP_REMOTE, saddr_r);
5067 if (result != SASL_OK)
5070 if (saddr_l != NULL)
5071 result = sasl_setprop(*conn, SASL_IP_LOCAL, saddr_l);
5072 if (result != SASL_OK)
5074 # endif /* NETINET */
5076 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
5077 if (result != SASL_OK)
5079 # endif /* SASL >= 20000 */