2 * Copyright (c) 1998-2008 Sendmail, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 # include <libmilter/mfapi.h>
17 # include <libmilter/mfdef.h>
20 SM_RCSID("@(#)$Id: srvrsmtp.c,v 8.989 2009/12/18 17:08:01 ca Exp $")
27 #endif /* SASL || STARTTLS */
29 # define ENC64LEN(l) (((l) + 2) * 4 / 3 + 1)
30 static int saslmechs __P((sasl_conn_t *, char **));
33 # include <sysexits.h>
35 static SSL_CTX *srv_ctx = NULL; /* TLS server context */
36 static SSL *srv_ssl = NULL; /* per connection context */
38 static bool tls_ok_srv = false;
40 # define TLS_VERIFY_CLIENT() tls_set_verify(srv_ctx, srv_ssl, \
41 bitset(SRV_VRFY_CLT, features))
45 static bool NotFirstDelivery = false;
46 #endif /* _FFR_DM_ONE */
49 #define SRV_NONE 0x0000 /* none... */
50 #define SRV_OFFER_TLS 0x0001 /* offer STARTTLS */
51 #define SRV_VRFY_CLT 0x0002 /* request a cert */
52 #define SRV_OFFER_AUTH 0x0004 /* offer AUTH */
53 #define SRV_OFFER_ETRN 0x0008 /* offer ETRN */
54 #define SRV_OFFER_VRFY 0x0010 /* offer VRFY (not yet used) */
55 #define SRV_OFFER_EXPN 0x0020 /* offer EXPN */
56 #define SRV_OFFER_VERB 0x0040 /* offer VERB */
57 #define SRV_OFFER_DSN 0x0080 /* offer DSN */
59 # define SRV_OFFER_PIPE 0x0100 /* offer PIPELINING */
61 # define SRV_NO_PIPE 0x0200 /* disable PIPELINING, sleep if used */
62 # endif /* _FFR_NO_PIPE */
63 #endif /* PIPELINING */
64 #define SRV_REQ_AUTH 0x0400 /* require AUTH */
65 #define SRV_REQ_SEC 0x0800 /* require security - equiv to AuthOptions=p */
66 #define SRV_TMP_FAIL 0x1000 /* ruleset caused a temporary failure */
68 static unsigned int srvfeatures __P((ENVELOPE *, char *, unsigned int));
70 #define STOP_ATTACK ((time_t) -1)
71 static time_t checksmtpattack __P((volatile unsigned int *, unsigned int,
72 bool, char *, ENVELOPE *));
73 static void printvrfyaddr __P((ADDRESS *, bool, bool));
74 static char *skipword __P((char *volatile, char *));
75 static void setup_smtpd_io __P((void));
79 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
80 char *_remoteip, char *_localip,
81 char *_auth_id, sasl_ssf_t *_ext_ssf));
83 # define RESET_SASLCONN \
86 result = reset_saslconn(&conn, AuthRealm, remoteip, \
87 localip, auth_id, &ext_ssf); \
88 if (result != SASL_OK) \
92 # else /* SASL >= 20000 */
93 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
94 struct sockaddr_in *_saddr_r,
95 struct sockaddr_in *_saddr_l,
96 sasl_external_properties_t *_ext_ssf));
97 # define RESET_SASLCONN \
100 result = reset_saslconn(&conn, AuthRealm, &saddr_r, \
101 &saddr_l, &ext_ssf); \
102 if (result != SASL_OK) \
106 # endif /* SASL >= 20000 */
109 extern ENVELOPE BlankEnvelope;
115 (void) sm_snprintf(buf, sizeof(buf), "%d", \
116 BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle \
117 ? n_badrcpts - 1 : n_badrcpts); \
118 macdefine(&e->e_macro, A_TEMP, macid("{nbadrcpts}"), buf); \
121 #define SKIP_SPACE(s) while (isascii(*s) && isspace(*s)) \
125 ** PARSE_ESMTP_ARGS -- parse EMSTP arguments (for MAIL, RCPT)
129 ** addr_st -- address (RCPT only)
131 ** delimptr -- current position in read buffer
132 ** which -- MAIL/RCPT
133 ** args -- arguments (output)
134 ** esmtp_args -- function to process a single ESMTP argument
141 parse_esmtp_args(e, addr_st, p, delimptr, which, args, esmtp_args)
148 esmtp_args_F esmtp_args;
156 while (p != NULL && *p != '\0')
162 /* locate the beginning of the keyword */
168 /* skip to the value portion */
169 while ((isascii(*p) && isalnum(*p)) || *p == '-')
177 /* skip to the end of the value */
178 while (*p != '\0' && *p != ' ' &&
179 !(isascii(*p) && iscntrl(*p)) &&
188 sm_dprintf("%s: got arg %s=\"%s\"\n", which, kp,
189 vp == NULL ? "<null>" : vp);
191 esmtp_args(addr_st, kp, vp, e);
197 if (argno >= MAXSMTPARGS - 1)
198 usrerr("501 5.5.4 Too many parameters");
207 ** SMTP -- run the SMTP protocol.
210 ** nullserver -- if non-NULL, rejection message for
211 ** (almost) all SMTP commands.
212 ** d_flags -- daemon flags
213 ** e -- the envelope.
219 ** Reads commands from the input channel and processes them.
223 ** Notice: The smtp server doesn't have a session context like the client
224 ** side has (mci). Therefore some data (session oriented) is allocated
225 ** or assigned to the "wrong" structure (esp. STARTTLS, AUTH).
226 ** This should be fixed in a successor version.
231 char *cmd_name; /* command name */
232 int cmd_code; /* internal code, see below */
235 /* values for cmd_code */
236 #define CMDERROR 0 /* bad command */
237 #define CMDMAIL 1 /* mail -- designate sender */
238 #define CMDRCPT 2 /* rcpt -- designate recipient */
239 #define CMDDATA 3 /* data -- send message text */
240 #define CMDRSET 4 /* rset -- reset state */
241 #define CMDVRFY 5 /* vrfy -- verify address */
242 #define CMDEXPN 6 /* expn -- expand address */
243 #define CMDNOOP 7 /* noop -- do nothing */
244 #define CMDQUIT 8 /* quit -- close connection and die */
245 #define CMDHELO 9 /* helo -- be polite */
246 #define CMDHELP 10 /* help -- give usage info */
247 #define CMDEHLO 11 /* ehlo -- extended helo (RFC 1425) */
248 #define CMDETRN 12 /* etrn -- flush queue */
250 # define CMDAUTH 13 /* auth -- SASL authenticate */
253 # define CMDSTLS 14 /* STARTTLS -- start TLS session */
254 #endif /* STARTTLS */
255 /* non-standard commands */
256 #define CMDVERB 17 /* verb -- go into verbose mode */
257 /* unimplemented commands from RFC 821 */
258 #define CMDUNIMPL 19 /* unimplemented rfc821 commands */
259 /* use this to catch and log "door handle" attempts on your system */
260 #define CMDLOGBOGUS 23 /* bogus command that should be logged */
261 /* debugging-only commands, only enabled if SMTPDEBUG is defined */
262 #define CMDDBGQSHOW 24 /* showq -- show send queue */
263 #define CMDDBGDEBUG 25 /* debug -- set debug mode */
266 ** Note: If you change this list, remember to update 'helpfile'
269 static struct cmd CmdTab[] =
284 { "send", CMDUNIMPL },
285 { "saml", CMDUNIMPL },
286 { "soml", CMDUNIMPL },
287 { "turn", CMDUNIMPL },
289 { "auth", CMDAUTH, },
292 { "starttls", CMDSTLS, },
293 #endif /* STARTTLS */
294 /* remaining commands are here only to trap and log attempts to use them */
295 { "showq", CMDDBGQSHOW },
296 { "debug", CMDDBGDEBUG },
297 { "wiz", CMDLOGBOGUS },
302 static char *CurSmtpClient; /* who's at the other end of channel */
304 #ifndef MAXBADCOMMANDS
305 # define MAXBADCOMMANDS 25 /* maximum number of bad commands */
306 #endif /* ! MAXBADCOMMANDS */
307 #ifndef MAXHELOCOMMANDS
308 # define MAXHELOCOMMANDS 3 /* max HELO/EHLO commands before slowdown */
309 #endif /* ! MAXHELOCOMMANDS */
310 #ifndef MAXVRFYCOMMANDS
311 # define MAXVRFYCOMMANDS 6 /* max VRFY/EXPN commands before slowdown */
312 #endif /* ! MAXVRFYCOMMANDS */
313 #ifndef MAXETRNCOMMANDS
314 # define MAXETRNCOMMANDS 8 /* max ETRN commands before slowdown */
315 #endif /* ! MAXETRNCOMMANDS */
317 # define MAXTIMEOUT (4 * 60) /* max timeout for bad commands */
318 #endif /* ! MAXTIMEOUT */
321 ** Maximum shift value to compute timeout for bad commands.
322 ** This introduces an upper limit of 2^MAXSHIFT for the timeout.
327 #endif /* ! MAXSHIFT */
329 ERROR _MAXSHIFT > 31 is invalid
330 #endif /* MAXSHIFT */
333 #if MAXBADCOMMANDS > 0
334 # define STOP_IF_ATTACK(r) do \
336 if ((r) == STOP_ATTACK) \
340 #else /* MAXBADCOMMANDS > 0 */
341 # define STOP_IF_ATTACK(r) r
342 #endif /* MAXBADCOMMANDS > 0 */
346 static SM_DEBUG_T DebugLeakSmtp = SM_DEBUG_INITIALIZER("leak_smtp",
347 "@(#)$Debug: leak_smtp - trace memory leaks during SMTP processing $");
348 #endif /* SM_HEAP_CHECK */
352 bool sm_gotmail; /* mail command received */
353 unsigned int sm_nrcpts; /* number of successful RCPT commands */
357 bool sm_milterlist; /* any filters in the list? */
358 milters_T sm_milters;
360 /* e_nrcpts from envelope before recipient() call */
361 unsigned int sm_e_nrcpts_orig;
363 char *sm_quarmsg; /* carry quarantining across messages */
366 static bool smtp_data __P((SMTP_T *, ENVELOPE *));
368 #define MSG_TEMPFAIL "451 4.3.2 Please try again later"
371 # define MILTER_ABORT(e) milter_abort((e))
373 # define MILTER_REPLY(str) \
375 int savelogusrerrs = LogUsrErrs; \
377 milter_cmd_fail = true; \
380 case SMFIR_SHUTDOWN: \
381 if (MilterLogLevel > 3) \
383 sm_syslog(LOG_INFO, e->e_id, \
384 "Milter: %s=%s, reject=421, errormode=4", \
386 LogUsrErrs = false; \
389 bool tsave = QuickAbort; \
391 QuickAbort = false; \
392 usrerr("421 4.3.0 closing connection"); \
393 QuickAbort = tsave; \
394 e->e_sendqueue = NULL; \
398 case SMFIR_REPLYCODE: \
399 if (MilterLogLevel > 3) \
401 sm_syslog(LOG_INFO, e->e_id, \
402 "Milter: %s=%s, reject=%s", \
403 str, addr, response); \
404 LogUsrErrs = false; \
406 if (strncmp(response, "421 ", 4) == 0 \
407 || strncmp(response, "421-", 4) == 0) \
409 bool tsave = QuickAbort; \
411 QuickAbort = false; \
413 QuickAbort = tsave; \
414 e->e_sendqueue = NULL; \
422 if (MilterLogLevel > 3) \
424 sm_syslog(LOG_INFO, e->e_id, \
425 "Milter: %s=%s, reject=550 5.7.1 Command rejected", \
427 LogUsrErrs = false; \
429 usrerr("550 5.7.1 Command rejected"); \
432 case SMFIR_DISCARD: \
433 if (MilterLogLevel > 3) \
434 sm_syslog(LOG_INFO, e->e_id, \
435 "Milter: %s=%s, discard", \
437 e->e_flags |= EF_DISCARD; \
438 milter_cmd_fail = false; \
441 case SMFIR_TEMPFAIL: \
442 if (MilterLogLevel > 3) \
444 sm_syslog(LOG_INFO, e->e_id, \
445 "Milter: %s=%s, reject=%s", \
446 str, addr, MSG_TEMPFAIL); \
447 LogUsrErrs = false; \
449 usrerr(MSG_TEMPFAIL); \
452 milter_cmd_fail = false; \
455 LogUsrErrs = savelogusrerrs; \
456 if (response != NULL) \
457 sm_free(response); /* XXX */ \
461 # define MILTER_ABORT(e)
464 /* clear all SMTP state (for HELO/EHLO/RSET) */
465 #define CLEAR_STATE(cmd) \
468 /* abort milter filters */ \
471 if (smtp.sm_nrcpts > 0) \
473 logundelrcpts(e, cmd, 10, false); \
474 smtp.sm_nrcpts = 0; \
475 macdefine(&e->e_macro, A_PERM, \
476 macid("{nrcpts}"), "0"); \
479 e->e_sendqueue = NULL; \
480 e->e_flags |= EF_CLRQUEUE; \
483 sm_dprintf("CLEAR_STATE: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",\
484 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);\
485 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) \
486 logsender(e, NULL); \
487 e->e_flags &= ~EF_LOGSENDER; \
489 /* clean up a bit */ \
490 smtp.sm_gotmail = false; \
492 (void) dropenvelope(e, true, false); \
493 sm_rpool_free(e->e_rpool); \
494 e = newenvelope(e, CurEnv, sm_rpool_new_x(NULL)); \
496 e->e_features = features; \
498 /* put back discard bit */ \
499 if (smtp.sm_discard) \
500 e->e_flags |= EF_DISCARD; \
502 /* restore connection quarantining */ \
503 if (smtp.sm_quarmsg == NULL) \
505 e->e_quarmsg = NULL; \
506 macdefine(&e->e_macro, A_PERM, \
507 macid("{quarantine}"), ""); \
511 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \
513 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \
518 /* sleep to flatten out connection load */
519 #define MIN_DELAY_LOG 15 /* wait before logging this again */
521 /* is it worth setting the process title for 1s? */
522 #define DELAY_CONN(cmd) \
523 if (DelayLA > 0 && (CurrentLA = getla()) >= DelayLA) \
527 sm_setproctitle(true, e, \
528 "%s: %s: delaying %s: load average: %d", \
529 qid_printname(e), CurSmtpClient, \
531 if (LogLevel > 8 && (dnow = curtime()) > log_delay) \
533 sm_syslog(LOG_INFO, e->e_id, \
534 "delaying=%s, load average=%d >= %d", \
535 cmd, CurrentLA, DelayLA); \
536 log_delay = dnow + MIN_DELAY_LOG; \
539 sm_setproctitle(true, e, "%s %s: %.80s", \
540 qid_printname(e), CurSmtpClient, inp); \
543 static bool SevenBitInput_Saved; /* saved version of SevenBitInput */
546 smtp(nullserver, d_flags, e)
547 char *volatile nullserver;
549 register ENVELOPE *volatile e;
551 register char *volatile p;
552 register struct cmd *volatile c = NULL;
554 auto ADDRESS *vrfyqueue;
556 volatile bool gothello; /* helo command received */
557 bool vrfy; /* set if this is a vrfy command */
558 char *volatile protocol; /* sending protocol */
559 char *volatile sendinghost; /* sending hostname */
560 char *volatile peerhostname; /* name of SMTP peer or "localhost" */
563 volatile unsigned int n_badcmds = 0; /* count of bad commands */
564 volatile unsigned int n_badrcpts = 0; /* number of rejected RCPT */
565 volatile unsigned int n_verifies = 0; /* count of VRFY/EXPN */
566 volatile unsigned int n_etrn = 0; /* count of ETRN */
567 volatile unsigned int n_noop = 0; /* count of NOOP/VERB/etc */
568 volatile unsigned int n_helo = 0; /* count of HELO/EHLO */
571 volatile bool tempfail = false;
572 volatile time_t wt; /* timeout after too many commands */
573 volatile time_t previous; /* time after checksmtpattack() */
574 volatile bool lognullconnection = true;
578 char *greetcode = "220";
579 char *hostname; /* my hostname ($j) */
581 char *args[MAXSMTPARGS];
582 char inp[MAXINPLINE];
583 #if MAXINPLINE < MAXLINE
584 ERROR _MAXINPLINE must NOT be less than _MAXLINE: MAXINPLINE < MAXLINE
585 #endif /* MAXINPLINE < MAXLINE */
586 char cmdbuf[MAXLINE];
589 volatile bool sasl_ok;
590 volatile unsigned int n_auth = 0; /* count of AUTH commands */
593 volatile int authenticating;
597 char *auth_id = NULL;
600 char localip[60], remoteip[60];
601 # else /* SASL >= 20000 */
604 sasl_external_properties_t ext_ssf;
605 struct sockaddr_in saddr_l;
606 struct sockaddr_in saddr_r;
607 # endif /* SASL >= 20000 */
608 sasl_security_properties_t ssp;
610 unsigned int inlen, out2len;
612 char *volatile auth_type;
614 volatile unsigned int n_mechs;
621 volatile bool tls_active = false;
622 volatile bool smtps = bitnset(D_SMTPS, d_flags);
626 #endif /* STARTTLS */
627 volatile unsigned int features;
631 # endif /* _FFR_NO_PIPE */
632 #endif /* PIPELINING */
633 volatile time_t log_delay = (time_t) 0;
635 volatile bool milter_cmd_done, milter_cmd_safe;
636 volatile bool milter_rcpt_added, milter_cmd_fail;
638 # define p_addr_st &addr_st
640 # define p_addr_st NULL
643 #if _FFR_BADRCPT_SHUTDOWN
645 #endif /* _FFR_BADRCPT_SHUTDOWN */
647 SevenBitInput_Saved = SevenBitInput;
650 smtp.sm_milterize = (nullserver == NULL);
651 smtp.sm_milterlist = false;
655 /* setup I/O fd correctly for the SMTP server */
659 if (sm_debug_active(&DebugLeakSmtp, 1))
662 sm_dprintf("smtp() heap group #%d\n", sm_heap_group());
664 #endif /* SM_HEAP_CHECK */
666 /* XXX the rpool should be set when e is initialized in main() */
667 e->e_rpool = sm_rpool_new_x(NULL);
668 e->e_macro.mac_rpool = e->e_rpool;
672 peerhostname = RealHostName;
673 if (peerhostname == NULL)
674 peerhostname = "localhost";
675 CurHostName = peerhostname;
676 CurSmtpClient = macvalue('_', e);
677 if (CurSmtpClient == NULL)
678 CurSmtpClient = CurHostName;
680 /* check_relay may have set discard bit, save for later */
681 smtp.sm_discard = bitset(EF_DISCARD, e->e_flags);
684 /* auto-flush output when reading input */
685 (void) sm_io_autoflush(InChannel, OutChannel);
686 #endif /* PIPELINING */
688 sm_setproctitle(true, e, "server %s startup", CurSmtpClient);
690 /* Set default features for server. */
691 features = ((bitset(PRIV_NOETRN, PrivacyFlags) ||
692 bitnset(D_NOETRN, d_flags)) ? SRV_NONE : SRV_OFFER_ETRN)
693 | (bitnset(D_AUTHREQ, d_flags) ? SRV_REQ_AUTH : SRV_NONE)
694 | (bitset(PRIV_NOEXPN, PrivacyFlags) ? SRV_NONE
696 | (bitset(PRIV_NOVERB, PrivacyFlags)
697 ? SRV_NONE : SRV_OFFER_VERB)))
698 | ((bitset(PRIV_NORECEIPTS, PrivacyFlags) || !SendMIMEErrors)
699 ? SRV_NONE : SRV_OFFER_DSN)
701 | (bitnset(D_NOAUTH, d_flags) ? SRV_NONE : SRV_OFFER_AUTH)
702 | (bitset(SASL_SEC_NOPLAINTEXT, SASLOpts) ? SRV_REQ_SEC
707 #endif /* PIPELINING */
709 | (bitnset(D_NOTLS, d_flags) ? SRV_NONE : SRV_OFFER_TLS)
710 | (bitset(TLS_I_NO_VRFY, TLS_Srv_Opts) ? SRV_NONE
712 #endif /* STARTTLS */
714 if (nullserver == NULL)
716 features = srvfeatures(e, CurSmtpClient, features);
717 if (bitset(SRV_TMP_FAIL, features))
720 sm_syslog(LOG_ERR, NOQID,
721 "ERROR: srv_features=tempfail, relay=%.100s, access temporarily disabled",
723 nullserver = "450 4.3.0 Please try again later.";
729 if (bitset(SRV_NO_PIPE, features))
731 /* for consistency */
732 features &= ~SRV_OFFER_PIPE;
734 # endif /* _FFR_NO_PIPE */
735 #endif /* PIPELINING */
737 if (bitset(SRV_REQ_SEC, features))
738 SASLOpts |= SASL_SEC_NOPLAINTEXT;
740 SASLOpts &= ~SASL_SEC_NOPLAINTEXT;
744 else if (strncmp(nullserver, "421 ", 4) == 0)
750 e->e_features = features;
751 hostname = macvalue('j', e);
753 if (AuthRealm == NULL)
754 AuthRealm = hostname;
755 sasl_ok = bitset(SRV_OFFER_AUTH, features);
757 authenticating = SASL_NOT_AUTH;
759 /* SASL server new connection */
763 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, NULL,
766 /* use empty realm: only works in SASL > 1.5.5 */
767 result = sasl_server_new("smtp", AuthRealm, "", NULL, 0, &conn);
768 # else /* SASL >= 20000 */
769 /* use no realm -> realm is set to hostname by SASL lib */
770 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, 0,
772 # endif /* SASL >= 20000 */
773 sasl_ok = result == SASL_OK;
777 sm_syslog(LOG_WARNING, NOQID,
778 "AUTH error: sasl_server_new failed=%d",
785 ** SASL set properties for sasl
786 ** set local/remote IP
787 ** XXX Cyrus SASL v1 only supports IPv4
789 ** XXX where exactly are these used/required?
794 localip[0] = remoteip[0] = '\0';
795 # if NETINET || NETINET6
796 in = macvalue(macid("{daemon_family}"), e);
799 strcmp(in, "inet6") == 0 ||
800 # endif /* NETINET6 */
801 strcmp(in, "inet") == 0))
803 SOCKADDR_LEN_T addrsize;
807 addrsize = sizeof(saddr_r);
808 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
810 (struct sockaddr *) &saddr_r,
813 if (iptostring(&saddr_r, addrsize,
814 remoteip, sizeof(remoteip)))
816 sasl_setprop(conn, SASL_IPREMOTEPORT,
819 addrsize = sizeof(saddr_l);
820 if (getsockname(sm_io_getinfo(InChannel,
823 (struct sockaddr *) &saddr_l,
826 if (iptostring(&saddr_l, addrsize,
837 # endif /* NETINET || NETINET6 */
838 # else /* SASL >= 20000 */
840 in = macvalue(macid("{daemon_family}"), e);
841 if (in != NULL && strcmp(in, "inet") == 0)
843 SOCKADDR_LEN_T addrsize;
845 addrsize = sizeof(struct sockaddr_in);
846 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
848 (struct sockaddr *)&saddr_r,
851 sasl_setprop(conn, SASL_IP_REMOTE, &saddr_r);
852 addrsize = sizeof(struct sockaddr_in);
853 if (getsockname(sm_io_getinfo(InChannel,
856 (struct sockaddr *)&saddr_l,
858 sasl_setprop(conn, SASL_IP_LOCAL,
862 # endif /* NETINET */
863 # endif /* SASL >= 20000 */
869 macdefine(&BlankEnvelope.e_macro, A_PERM,
870 macid("{auth_author}"), NULL);
874 (void) memset(&ssp, '\0', sizeof(ssp));
876 /* XXX should these be options settable via .cf ? */
877 /* ssp.min_ssf = 0; is default due to memset() */
879 ssp.max_ssf = MaxSLBits;
880 ssp.maxbufsize = MAXOUTLEN;
882 ssp.security_flags = SASLOpts & SASL_SEC_MASK;
883 sasl_ok = sasl_setprop(conn, SASL_SEC_PROPS, &ssp) == SASL_OK;
888 ** external security strength factor;
889 ** currently we have none so zero
895 sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL,
896 &ext_ssf) == SASL_OK) &&
897 (sasl_setprop(conn, SASL_AUTH_EXTERNAL,
898 auth_id) == SASL_OK));
899 # else /* SASL >= 20000 */
901 ext_ssf.auth_id = NULL;
902 sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL,
903 &ext_ssf) == SASL_OK;
904 # endif /* SASL >= 20000 */
907 n_mechs = saslmechs(conn, &mechlist);
912 # if USE_OPENSSL_ENGINE
913 if (tls_ok_srv && bitset(SRV_OFFER_TLS, features) &&
914 !SSL_set_engine(NULL))
916 sm_syslog(LOG_ERR, NOQID,
917 "STARTTLS=server, SSL_set_engine=failed");
920 # endif /* USE_OPENSSL_ENGINE */
923 set_tls_rd_tmo(TimeOuts.to_nextcommand);
924 #endif /* STARTTLS */
927 if (smtp.sm_milterize)
931 /* initialize mail filter connection */
932 smtp.sm_milterlist = milter_init(e, &state, &smtp.sm_milters);
936 if (MilterLogLevel > 3)
937 sm_syslog(LOG_INFO, e->e_id,
938 "Milter: initialization failed, rejecting commands");
940 nullserver = "Command rejected";
941 smtp.sm_milterize = false;
945 if (MilterLogLevel > 3)
946 sm_syslog(LOG_INFO, e->e_id,
947 "Milter: initialization failed, temp failing commands");
949 smtp.sm_milterize = false;
953 if (MilterLogLevel > 3)
954 sm_syslog(LOG_INFO, e->e_id,
955 "Milter: initialization failed, closing connection");
957 smtp.sm_milterize = false;
958 message("421 4.7.0 %s closing connection",
961 /* arrange to ignore send list */
962 e->e_sendqueue = NULL;
963 lognullconnection = false;
968 if (smtp.sm_milterlist && smtp.sm_milterize &&
969 !bitset(EF_DISCARD, e->e_flags))
974 q = macvalue(macid("{client_name}"), e);
975 SM_ASSERT(q != NULL || OpMode == MD_SMTP);
978 response = milter_connect(q, RealHostAddr, e, &state);
981 case SMFIR_REPLYCODE: /* REPLYCODE shouldn't happen */
983 if (MilterLogLevel > 3)
984 sm_syslog(LOG_INFO, e->e_id,
985 "Milter: connect: host=%s, addr=%s, rejecting commands",
987 anynet_ntoa(&RealHostAddr));
989 nullserver = "Command rejected";
990 smtp.sm_milterize = false;
994 if (MilterLogLevel > 3)
995 sm_syslog(LOG_INFO, e->e_id,
996 "Milter: connect: host=%s, addr=%s, temp failing commands",
998 anynet_ntoa(&RealHostAddr));
1000 smtp.sm_milterize = false;
1003 case SMFIR_SHUTDOWN:
1004 if (MilterLogLevel > 3)
1005 sm_syslog(LOG_INFO, e->e_id,
1006 "Milter: connect: host=%s, addr=%s, shutdown",
1008 anynet_ntoa(&RealHostAddr));
1010 smtp.sm_milterize = false;
1011 message("421 4.7.0 %s closing connection",
1014 /* arrange to ignore send list */
1015 e->e_sendqueue = NULL;
1018 if (response != NULL)
1019 sm_free(response); /* XXX */
1024 ** Broken proxies and SMTP slammers
1025 ** push data without waiting, catch them
1031 #endif /* STARTTLS */
1032 *greetcode == '2' && nullserver == NULL)
1036 char pvpbuf[PSBUFSIZE];
1038 /* Ask the rulesets how long to pause */
1040 r = rscap("greet_pause", peerhostname,
1041 anynet_ntoa(&RealHostAddr), e,
1042 &pvp, pvpbuf, sizeof(pvpbuf));
1043 if (r == EX_OK && pvp != NULL && pvp[0] != NULL &&
1044 (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL)
1046 msecs = strtol(pvp[1], NULL, 10);
1053 struct timeval timeout;
1054 struct timeval bp, ep, tp; /* {begin,end,total}pause */
1057 /* pause for a moment */
1058 timeout.tv_sec = msecs / 1000;
1059 timeout.tv_usec = (msecs % 1000) * 1000;
1061 /* Obey RFC 2821: 4.3.5.2: 220 timeout of 5 minutes */
1062 if (timeout.tv_sec >= 300)
1064 timeout.tv_sec = 300;
1065 timeout.tv_usec = 0;
1068 /* check if data is on the socket during the pause */
1069 fd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1071 SM_FD_SET(fd, &readfds);
1072 gettimeofday(&bp, NULL);
1073 if (select(fd + 1, FDSET_CAST &readfds,
1074 NULL, NULL, &timeout) > 0 &&
1075 FD_ISSET(fd, &readfds) &&
1076 (eoftest = sm_io_getc(InChannel, SM_TIME_DEFAULT))
1079 sm_io_ungetc(InChannel, SM_TIME_DEFAULT,
1081 gettimeofday(&ep, NULL);
1082 timersub(&ep, &bp, &tp);
1084 nullserver = "Command rejected";
1085 sm_syslog(LOG_INFO, e->e_id,
1086 "rejecting commands from %s [%s] due to pre-greeting traffic after %d seconds",
1088 anynet_ntoa(&RealHostAddr),
1090 (tp.tv_usec >= 500000 ? 1 : 0)
1097 /* If this an smtps connection, start TLS now */
1106 #endif /* STARTTLS */
1108 /* output the first line, inserting "ESMTP" as second word */
1109 if (*greetcode == '5')
1110 (void) sm_snprintf(inp, sizeof(inp),
1111 "%s not accepting messages", hostname);
1113 expand(SmtpGreeting, inp, sizeof(inp), e);
1115 p = strchr(inp, '\n');
1118 id = strchr(inp, ' ');
1120 id = &inp[strlen(inp)];
1122 (void) sm_snprintf(cmdbuf, sizeof(cmdbuf),
1123 "%s %%.*s ESMTP%%s", greetcode);
1125 (void) sm_snprintf(cmdbuf, sizeof(cmdbuf),
1126 "%s-%%.*s ESMTP%%s", greetcode);
1127 message(cmdbuf, (int) (id - inp), inp, id);
1129 /* output remaining lines */
1130 while ((id = p) != NULL && (p = strchr(id, '\n')) != NULL)
1133 if (isascii(*id) && isspace(*id))
1135 (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, "-%s");
1136 message(cmdbuf, id);
1140 if (isascii(*id) && isspace(*id))
1142 (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, " %s");
1143 message(cmdbuf, id);
1147 sendinghost = macvalue('s', e);
1149 /* If quarantining by a connect/ehlo action, save between messages */
1150 if (e->e_quarmsg == NULL)
1151 smtp.sm_quarmsg = NULL;
1153 smtp.sm_quarmsg = newstr(e->e_quarmsg);
1155 /* sendinghost's storage must outlive the current envelope */
1156 if (sendinghost != NULL)
1157 sendinghost = sm_strdup_x(sendinghost);
1160 smtp.sm_gotmail = false;
1169 OnlyOneError = true;
1170 e->e_flags &= ~(EF_VRFYONLY|EF_GLOBALERRS);
1172 milter_cmd_fail = false;
1175 /* setup for the read */
1179 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
1181 /* read the input line */
1182 SmtpPhase = "server cmd read";
1183 sm_setproctitle(true, e, "server %s cmd read", CurSmtpClient);
1186 if (sm_io_error(OutChannel) ||
1187 (p = sfgets(inp, sizeof(inp), InChannel,
1188 TimeOuts.to_nextcommand, SmtpPhase)) == NULL)
1192 d = macvalue(macid("{daemon_name}"), e);
1195 /* end of file, just die */
1199 /* close out milter filters */
1203 message("421 4.4.1 %s Lost input channel from %s",
1204 MyHostName, CurSmtpClient);
1205 if (LogLevel > (smtp.sm_gotmail ? 1 : 19))
1206 sm_syslog(LOG_NOTICE, e->e_id,
1207 "lost input channel from %s to %s after %s",
1209 (c == NULL || c->cmd_name == NULL) ? "startup" : c->cmd_name);
1211 ** If have not accepted mail (DATA), do not bounce
1212 ** bad addresses back to sender.
1215 if (bitset(EF_CLRQUEUE, e->e_flags))
1216 e->e_sendqueue = NULL;
1220 /* also used by "proxy" check below */
1221 inplen = strlen(inp);
1224 ** SMTP AUTH requires accepting any length,
1225 ** at least for challenge/response. However, not imposing
1226 ** a limit is a bad idea (denial of service).
1229 if (authenticating != SASL_PROC_AUTH
1230 && sm_strncasecmp(inp, "AUTH ", 5) != 0
1231 && inplen > MAXLINE)
1233 message("421 4.7.0 %s Command too long, possible attack %s",
1234 MyHostName, CurSmtpClient);
1235 sm_syslog(LOG_INFO, e->e_id,
1236 "%s: SMTP violation, input too long: %lu",
1237 CurSmtpClient, (unsigned long) inplen);
1247 static char *http_cmds[] = { "GET", "POST",
1248 "CONNECT", "USER", NULL };
1250 for (idx = 0; (http_cmd = http_cmds[idx]) != NULL;
1253 cmdlen = strlen(http_cmd);
1254 if (cmdlen < inplen &&
1255 sm_strncasecmp(inp, http_cmd, cmdlen) == 0 &&
1256 isascii(inp[cmdlen]) && isspace(inp[cmdlen]))
1258 /* Open proxy, drop it */
1259 message("421 4.7.0 %s Rejecting open proxy %s",
1260 MyHostName, CurSmtpClient);
1261 sm_syslog(LOG_INFO, e->e_id,
1262 "%s: probable open proxy: command=%.40s",
1263 CurSmtpClient, inp);
1270 /* clean up end of line */
1276 ** if there is more input and pipelining is disabled:
1277 ** delay ... (and maybe discard the input?)
1278 ** XXX this doesn't really work, at least in tests using
1279 ** telnet SM_IO_IS_READABLE only returns 1 if there were
1280 ** more than 2 input lines available.
1283 if (bitset(SRV_NO_PIPE, features) &&
1284 sm_io_getinfo(InChannel, SM_IO_IS_READABLE, NULL) > 0)
1287 sm_syslog(LOG_INFO, NOQID,
1288 "unauthorized PIPELINING, sleeping, relay=%.100s",
1293 # endif /* _FFR_NO_PIPE */
1294 #endif /* PIPELINING */
1297 if (authenticating == SASL_PROC_AUTH)
1302 authenticating = SASL_NOT_AUTH;
1303 message("501 5.5.2 missing input");
1308 if (*inp == '*' && *(inp + 1) == '\0')
1310 authenticating = SASL_NOT_AUTH;
1313 message("501 5.0.0 AUTH aborted");
1318 /* could this be shorter? XXX */
1320 in = xalloc(strlen(inp) + 1);
1321 result = sasl_decode64(inp, strlen(inp), in,
1322 strlen(inp), &inlen);
1323 # else /* SASL >= 20000 */
1324 out = xalloc(strlen(inp));
1325 result = sasl_decode64(inp, strlen(inp), out, &outlen);
1326 # endif /* SASL >= 20000 */
1327 if (result != SASL_OK)
1329 authenticating = SASL_NOT_AUTH;
1332 message("501 5.5.4 cannot decode AUTH parameter %s",
1336 # endif /* SASL >= 20000 */
1342 result = sasl_server_step(conn, in, inlen,
1345 # else /* SASL >= 20000 */
1346 result = sasl_server_step(conn, out, outlen,
1347 &out, &outlen, &errstr);
1348 # endif /* SASL >= 20000 */
1350 /* get an OK if we're done */
1351 if (result == SASL_OK)
1354 message("235 2.0.0 OK Authenticated");
1355 authenticating = SASL_IS_AUTH;
1356 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1357 macid("{auth_type}"), auth_type);
1360 user = macvalue(macid("{auth_authen}"), e);
1362 /* get security strength (features) */
1363 result = sasl_getprop(conn, SASL_SSF,
1364 (const void **) &ssf);
1365 # else /* SASL >= 20000 */
1366 result = sasl_getprop(conn, SASL_USERNAME,
1368 if (result != SASL_OK)
1371 macdefine(&BlankEnvelope.e_macro,
1373 macid("{auth_authen}"), NULL);
1377 macdefine(&BlankEnvelope.e_macro,
1379 macid("{auth_authen}"),
1380 xtextify(user, "<>\")"));
1385 sasl_getprop(conn, SASL_REALM, (void **) &data);
1388 /* get security strength (features) */
1389 result = sasl_getprop(conn, SASL_SSF,
1391 # endif /* SASL >= 20000 */
1392 if (result != SASL_OK)
1394 macdefine(&BlankEnvelope.e_macro,
1396 macid("{auth_ssf}"), "0");
1403 (void) sm_snprintf(pbuf, sizeof(pbuf),
1405 macdefine(&BlankEnvelope.e_macro,
1407 macid("{auth_ssf}"), pbuf);
1409 sm_dprintf("AUTH auth_ssf: %u\n",
1414 ** Only switch to encrypted connection
1415 ** if a security layer has been negotiated
1418 if (ssf != NULL && *ssf > 0)
1423 ** Convert I/O layer to use SASL.
1424 ** If the call fails, the connection
1428 tmo = TimeOuts.to_datablock * 1000;
1429 if (sfdcsasl(&InChannel, &OutChannel,
1432 /* restart dialogue */
1435 (void) sm_io_autoflush(InChannel,
1437 # endif /* PIPELINING */
1440 syserr("503 5.3.3 SASL TLS failed");
1443 /* NULL pointer ok since it's our function */
1445 sm_syslog(LOG_INFO, NOQID,
1446 "AUTH=server, relay=%s, authid=%.128s, mech=%.16s, bits=%d",
1448 shortenstring(user, 128),
1451 else if (result == SASL_CONTINUE)
1453 len = ENC64LEN(outlen);
1455 result = sasl_encode64(out, outlen, out2, len,
1457 if (result != SASL_OK)
1459 /* correct code? XXX */
1460 /* 454 Temp. authentication failure */
1461 message("454 4.5.4 Internal error: unable to encode64");
1463 sm_syslog(LOG_WARNING, e->e_id,
1464 "AUTH encode64 error [%d for \"%s\"], relay=%.100s",
1468 authenticating = SASL_NOT_AUTH;
1472 message("334 %s", out2);
1474 sm_dprintf("AUTH continue: msg='%s' len=%u\n",
1479 # endif /* SASL >= 20000 */
1483 /* not SASL_OK or SASL_CONT */
1484 message("535 5.7.0 authentication failed");
1486 sm_syslog(LOG_WARNING, e->e_id,
1487 "AUTH failure (%s): %s (%d) %s, relay=%.100s",
1489 sasl_errstring(result, NULL,
1493 sasl_errdetail(conn),
1494 # else /* SASL >= 20000 */
1495 errstr == NULL ? "" : errstr,
1496 # endif /* SASL >= 20000 */
1499 authenticating = SASL_NOT_AUTH;
1504 /* don't want to do any of this if authenticating */
1507 /* echo command to transcript */
1508 if (e->e_xfp != NULL)
1509 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1513 sm_syslog(LOG_INFO, e->e_id, "<-- %s", inp);
1515 /* break off command */
1516 for (p = inp; isascii(*p) && isspace(*p); p++)
1519 while (*p != '\0' &&
1520 !(isascii(*p) && isspace(*p)) &&
1521 cmd < &cmdbuf[sizeof(cmdbuf) - 2])
1525 /* throw away leading whitespace */
1528 /* decode command */
1529 for (c = CmdTab; c->cmd_name != NULL; c++)
1531 if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0)
1538 /* check whether a "non-null" command has been used */
1539 switch (c->cmd_code)
1543 /* avoid information leak; take first two words? */
1552 lognullconnection = false;
1559 if (e->e_id == NULL)
1560 sm_setproctitle(true, e, "%s: %.80s",
1563 sm_setproctitle(true, e, "%s %s: %.80s",
1570 ** If we are running as a null server, return 550
1571 ** to almost everything.
1574 if (nullserver != NULL || bitnset(D_ETRNONLY, d_flags))
1576 switch (c->cmd_code)
1584 /* process normally */
1588 if (bitnset(D_ETRNONLY, d_flags) &&
1595 #if MAXBADCOMMANDS > 0
1596 /* theoretically this could overflow */
1597 if (nullserver != NULL &&
1598 ++n_badcmds > MAXBADCOMMANDS)
1600 message("421 4.7.0 %s Too many bad commands; closing connection",
1603 /* arrange to ignore send list */
1604 e->e_sendqueue = NULL;
1607 #endif /* MAXBADCOMMANDS > 0 */
1608 if (nullserver != NULL)
1610 if (ISSMTPREPLY(nullserver))
1613 usrerr("550 5.0.0 %s",
1617 usrerr("452 4.4.5 Insufficient disk space; try again later");
1622 switch (c->cmd_code)
1625 case CMDAUTH: /* sasl */
1627 if (!sasl_ok || n_mechs <= 0)
1629 message("503 5.3.3 AUTH not available");
1632 if (authenticating == SASL_IS_AUTH)
1634 message("503 5.5.0 Already Authenticated");
1637 if (smtp.sm_gotmail)
1639 message("503 5.5.0 AUTH not permitted during a mail transaction");
1645 sm_syslog(LOG_INFO, e->e_id,
1646 "SMTP AUTH command (%.100s) from %s tempfailed (due to previous checks)",
1648 usrerr("454 4.3.0 Please try again later");
1654 /* crude way to avoid crack attempts */
1655 STOP_IF_ATTACK(checksmtpattack(&n_auth, n_mechs + 1,
1658 /* make sure mechanism (p) is a valid string */
1659 for (q = p; *q != '\0' && isascii(*q); q++)
1664 while (*++q != '\0' &&
1665 isascii(*q) && isspace(*q))
1668 ismore = (*q != '\0');
1675 message("501 5.5.2 AUTH mechanism must be specified");
1679 /* check whether mechanism is available */
1680 if (iteminlist(p, mechlist, " ") == NULL)
1682 message("504 5.3.3 AUTH mechanism %.32s not available",
1689 ** Unlike a zero-length client answer to a
1690 ** 334 reply, a zero- length initial response
1691 ** is sent as a single equals sign ("=").
1694 if (ismore && *q == '=' && *(q + 1) == '\0')
1696 /* will be free()d, don't use in=""; */
1703 /* could this be shorter? XXX */
1705 in = xalloc(strlen(q) + 1);
1706 result = sasl_decode64(q, strlen(q), in,
1708 # else /* SASL >= 20000 */
1709 in = sm_rpool_malloc(e->e_rpool, strlen(q));
1710 result = sasl_decode64(q, strlen(q), in,
1712 # endif /* SASL >= 20000 */
1713 if (result != SASL_OK)
1715 message("501 5.5.4 cannot BASE64 decode '%s'",
1718 sm_syslog(LOG_WARNING, e->e_id,
1719 "AUTH decode64 error [%d for \"%s\"], relay=%.100s",
1723 authenticating = SASL_NOT_AUTH;
1726 # endif /* SASL >= 20000 */
1738 /* see if that auth type exists */
1740 result = sasl_server_start(conn, p, in, inlen,
1744 # else /* SASL >= 20000 */
1745 result = sasl_server_start(conn, p, in, inlen,
1746 &out, &outlen, &errstr);
1747 # endif /* SASL >= 20000 */
1749 if (result != SASL_OK && result != SASL_CONTINUE)
1751 message("535 5.7.0 authentication failed");
1753 sm_syslog(LOG_ERR, e->e_id,
1754 "AUTH failure (%s): %s (%d) %s, relay=%.100s",
1756 sasl_errstring(result, NULL,
1760 sasl_errdetail(conn),
1761 # else /* SASL >= 20000 */
1763 # endif /* SASL >= 20000 */
1768 auth_type = newstr(p);
1770 if (result == SASL_OK)
1772 /* ugly, but same code */
1774 /* authenticated by the initial response */
1777 /* len is at least 2 */
1778 len = ENC64LEN(outlen);
1780 result = sasl_encode64(out, outlen, out2, len,
1783 if (result != SASL_OK)
1785 message("454 4.5.4 Temporary authentication failure");
1787 sm_syslog(LOG_WARNING, e->e_id,
1788 "AUTH encode64 error [%d for \"%s\"]",
1792 authenticating = SASL_NOT_AUTH;
1797 message("334 %s", out2);
1798 authenticating = SASL_PROC_AUTH;
1802 # endif /* SASL >= 20000 */
1807 case CMDSTLS: /* starttls */
1808 DELAY_CONN("STARTTLS");
1811 message("501 5.5.2 Syntax error (no parameters allowed)");
1814 if (!bitset(SRV_OFFER_TLS, features))
1816 message("503 5.5.0 TLS not available");
1821 message("454 4.3.3 TLS not available after start");
1824 if (smtp.sm_gotmail)
1826 message("503 5.5.0 TLS not permitted during a mail transaction");
1832 sm_syslog(LOG_INFO, e->e_id,
1833 "SMTP STARTTLS command (%.100s) from %s tempfailed (due to previous checks)",
1835 usrerr("454 4.7.0 Please try again later");
1841 ** XXX do we need a temp key ?
1843 # else /* TLS_NO_RSA */
1844 # endif /* TLS_NO_RSA */
1846 # if TLS_VRFY_PER_CTX
1848 ** Note: this sets the verification globally
1850 ** it's ok since it applies only to one transaction
1853 TLS_VERIFY_CLIENT();
1854 # endif /* TLS_VRFY_PER_CTX */
1856 if (srv_ssl != NULL)
1858 else if ((srv_ssl = SSL_new(srv_ctx)) == NULL)
1860 message("454 4.3.3 TLS not available: error generating SSL handle");
1862 tlslogerr("server");
1866 # if !TLS_VRFY_PER_CTX
1868 ** this could be used if it were possible to set
1869 ** verification per SSL (connection)
1870 ** not just per SSL_CTX (global)
1873 TLS_VERIFY_CLIENT();
1874 # endif /* !TLS_VRFY_PER_CTX */
1876 rfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1877 wfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
1879 if (rfd < 0 || wfd < 0 ||
1880 SSL_set_rfd(srv_ssl, rfd) <= 0 ||
1881 SSL_set_wfd(srv_ssl, wfd) <= 0)
1883 message("454 4.3.3 TLS not available: error set fd");
1889 message("220 2.0.0 Ready to start TLS");
1891 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
1892 # endif /* PIPELINING */
1894 SSL_set_accept_state(srv_ssl);
1896 # define SSL_ACC(s) SSL_accept(s)
1898 tlsstart = curtime();
1900 if ((r = SSL_ACC(srv_ssl)) <= 0)
1904 ssl_err = SSL_get_error(srv_ssl, r);
1905 i = tls_retry(srv_ssl, rfd, wfd, tlsstart,
1906 TimeOuts.to_starttls, ssl_err,
1913 sm_syslog(LOG_WARNING, NOQID,
1914 "STARTTLS=server, error: accept failed=%d, SSL_error=%d, errno=%d, retry=%d, relay=%.100s",
1915 r, ssl_err, errno, i,
1918 tlslogerr("server");
1925 ** according to the next draft of
1926 ** RFC 2487 the connection should be dropped
1929 /* arrange to ignore any current send list */
1930 e->e_sendqueue = NULL;
1934 /* ignore return code for now, it's in {verify} */
1935 (void) tls_get_info(srv_ssl, true,
1937 &BlankEnvelope.e_macro,
1938 bitset(SRV_VRFY_CLT, features));
1941 ** call Stls_client to find out whether
1942 ** to accept the connection from the client
1945 saveQuickAbort = QuickAbort;
1946 saveSuprErrs = SuprErrs;
1949 if (rscheck("tls_client",
1950 macvalue(macid("{verify}"), e),
1952 RSF_RMCOMM|RSF_COUNT,
1953 5, NULL, NOQID, NULL) != EX_OK ||
1956 extern char MsgBuf[];
1958 if (MsgBuf[0] != '\0' && ISSMTPREPLY(MsgBuf))
1959 nullserver = newstr(MsgBuf);
1961 nullserver = "503 5.7.0 Authentication required.";
1963 QuickAbort = saveQuickAbort;
1964 SuprErrs = saveSuprErrs;
1966 tls_ok_srv = false; /* don't offer STARTTLS again */
1975 s = macvalue(macid("{cipher_bits}"), e);
1976 v = macvalue(macid("{verify}"), e);
1977 c = macvalue(macid("{cert_subject}"), e);
1978 verified = (v != NULL && strcmp(v, "OK") == 0);
1979 if (s != NULL && (cipher_bits = atoi(s)) > 0)
1982 ext_ssf = cipher_bits;
1983 auth_id = verified ? c : NULL;
1984 sasl_ok = ((sasl_setprop(conn,
1986 &ext_ssf) == SASL_OK) &&
1989 auth_id) == SASL_OK));
1990 # else /* SASL >= 20000 */
1991 ext_ssf.ssf = cipher_bits;
1992 ext_ssf.auth_id = verified ? c : NULL;
1993 sasl_ok = sasl_setprop(conn,
1995 &ext_ssf) == SASL_OK;
1996 # endif /* SASL >= 20000 */
1999 n_mechs = saslmechs(conn,
2005 /* switch to secure connection */
2006 if (sfdctls(&InChannel, &OutChannel, srv_ssl) == 0)
2010 (void) sm_io_autoflush(InChannel, OutChannel);
2011 # endif /* PIPELINING */
2016 ** XXX this is an internal error
2017 ** how to deal with it?
2018 ** we can't generate an error message
2019 ** since the other side switched to an
2020 ** encrypted layer, but we could not...
2024 nullserver = "454 4.3.3 TLS not available: can't switch to encrypted layer";
2025 syserr("STARTTLS: can't switch to encrypted layer");
2036 #endif /* STARTTLS */
2038 case CMDHELO: /* hello -- introduce yourself */
2039 case CMDEHLO: /* extended hello */
2041 if (c->cmd_code == CMDEHLO)
2044 SmtpPhase = "server EHLO";
2049 SmtpPhase = "server HELO";
2052 /* avoid denial-of-service */
2053 STOP_IF_ATTACK(checksmtpattack(&n_helo, MAXHELOCOMMANDS,
2054 true, "HELO/EHLO", e));
2057 /* RFC2821 4.1.4 allows duplicate HELO/EHLO */
2058 /* check for duplicate HELO/EHLO per RFC 1651 4.2 */
2061 usrerr("503 %s Duplicate HELO/EHLO",
2067 /* check for valid domain name (re 1123 5.2.5) */
2068 if (*p == '\0' && !AllowBogusHELO)
2070 usrerr("501 %s requires domain address",
2075 /* check for long domain name (hides Received: info) */
2076 if (strlen(p) > MAXNAME)
2078 usrerr("501 Invalid domain name");
2080 sm_syslog(LOG_INFO, CurEnv->e_id,
2081 "invalid domain name (too long) from %s",
2087 for (q = p; *q != '\0'; q++)
2097 /* only complain if strict check */
2098 ok = AllowBogusHELO;
2100 /* allow trailing whitespace */
2101 while (!ok && *++q != '\0' &&
2108 if (strchr("[].-_#:", *q) == NULL)
2112 if (*q == '\0' && ok)
2114 q = "pleased to meet you";
2115 sendinghost = sm_strdup_x(p);
2117 else if (!AllowBogusHELO)
2119 usrerr("501 Invalid domain name");
2121 sm_syslog(LOG_INFO, CurEnv->e_id,
2122 "invalid domain name (%s) from %.100s",
2128 q = "accepting invalid domain name";
2131 if (gothello || smtp.sm_gotmail)
2132 CLEAR_STATE(cmdbuf);
2135 if (smtp.sm_milterlist && smtp.sm_milterize &&
2136 !bitset(EF_DISCARD, e->e_flags))
2141 response = milter_helo(p, e, &state);
2145 if (MilterLogLevel > 3)
2146 sm_syslog(LOG_INFO, e->e_id,
2147 "Milter: helo=%s, reject=Command rejected",
2149 nullserver = "Command rejected";
2150 smtp.sm_milterize = false;
2153 case SMFIR_TEMPFAIL:
2154 if (MilterLogLevel > 3)
2155 sm_syslog(LOG_INFO, e->e_id,
2156 "Milter: helo=%s, reject=%s",
2159 smtp.sm_milterize = false;
2162 case SMFIR_REPLYCODE:
2163 if (MilterLogLevel > 3)
2164 sm_syslog(LOG_INFO, e->e_id,
2165 "Milter: helo=%s, reject=%s",
2167 if (strncmp(response, "421 ", 4) != 0
2168 && strncmp(response, "421-", 4) != 0)
2170 nullserver = newstr(response);
2171 smtp.sm_milterize = false;
2176 case SMFIR_SHUTDOWN:
2177 if (MilterLogLevel > 3 &&
2179 sm_syslog(LOG_INFO, e->e_id,
2180 "Milter: helo=%s, reject=421 4.7.0 %s closing connection",
2183 smtp.sm_milterize = false;
2184 if (response != NULL)
2187 message("421 4.7.0 %s closing connection",
2189 /* arrange to ignore send list */
2190 e->e_sendqueue = NULL;
2191 lognullconnection = false;
2194 if (response != NULL)
2198 ** If quarantining by a connect/ehlo action,
2199 ** save between messages
2202 if (smtp.sm_quarmsg == NULL &&
2203 e->e_quarmsg != NULL)
2204 smtp.sm_quarmsg = newstr(e->e_quarmsg);
2209 /* print HELO response message */
2210 if (c->cmd_code != CMDEHLO)
2212 message("250 %s Hello %s, %s",
2213 MyHostName, CurSmtpClient, q);
2217 message("250-%s Hello %s, %s",
2218 MyHostName, CurSmtpClient, q);
2220 /* offer ENHSC even for nullserver */
2221 if (nullserver != NULL)
2223 message("250 ENHANCEDSTATUSCODES");
2228 ** print EHLO features list
2230 ** Note: If you change this list,
2231 ** remember to update 'helpfile'
2234 message("250-ENHANCEDSTATUSCODES");
2236 if (bitset(SRV_OFFER_PIPE, features))
2237 message("250-PIPELINING");
2238 #endif /* PIPELINING */
2239 if (bitset(SRV_OFFER_EXPN, features))
2241 message("250-EXPN");
2242 if (bitset(SRV_OFFER_VERB, features))
2243 message("250-VERB");
2246 message("250-8BITMIME");
2247 #endif /* MIME8TO7 */
2248 if (MaxMessageSize > 0)
2249 message("250-SIZE %ld", MaxMessageSize);
2251 message("250-SIZE");
2253 if (SendMIMEErrors && bitset(SRV_OFFER_DSN, features))
2256 if (bitset(SRV_OFFER_ETRN, features))
2257 message("250-ETRN");
2259 if (sasl_ok && mechlist != NULL && *mechlist != '\0')
2260 message("250-AUTH %s", mechlist);
2264 bitset(SRV_OFFER_TLS, features))
2265 message("250-STARTTLS");
2266 #endif /* STARTTLS */
2267 if (DeliverByMin > 0)
2268 message("250-DELIVERBY %ld",
2269 (long) DeliverByMin);
2270 else if (DeliverByMin == 0)
2271 message("250-DELIVERBY");
2273 /* < 0: no deliver-by */
2275 message("250 HELP");
2278 case CMDMAIL: /* mail -- designate sender */
2279 SmtpPhase = "server MAIL";
2282 /* check for validity of this command */
2283 if (!gothello && bitset(PRIV_NEEDMAILHELO, PrivacyFlags))
2285 usrerr("503 5.0.0 Polite people say HELO first");
2288 if (smtp.sm_gotmail)
2290 usrerr("503 5.5.0 Sender already specified");
2294 if (bitset(SRV_REQ_AUTH, features) &&
2295 authenticating != SASL_IS_AUTH)
2297 usrerr("530 5.7.0 Authentication required");
2302 p = skipword(p, "from");
2308 sm_syslog(LOG_INFO, e->e_id,
2309 "SMTP MAIL command (%.100s) from %s tempfailed (due to previous checks)",
2311 usrerr(MSG_TEMPFAIL);
2315 /* make sure we know who the sending host is */
2316 if (sendinghost == NULL)
2317 sendinghost = peerhostname;
2321 if (sm_debug_active(&DebugLeakSmtp, 1))
2324 sm_dprintf("smtp() heap group #%d\n",
2327 #endif /* SM_HEAP_CHECK */
2333 auth_warning(e, "%s didn't use HELO protocol",
2336 #ifdef PICKY_HELO_CHECK
2337 if (sm_strcasecmp(sendinghost, peerhostname) != 0 &&
2338 (sm_strcasecmp(peerhostname, "localhost") != 0 ||
2339 sm_strcasecmp(sendinghost, MyHostName) != 0))
2341 auth_warning(e, "Host %s claimed to be %s",
2342 CurSmtpClient, sendinghost);
2344 #endif /* PICKY_HELO_CHECK */
2346 if (protocol == NULL)
2348 macdefine(&e->e_macro, A_PERM, 'r', protocol);
2349 macdefine(&e->e_macro, A_PERM, 's', sendinghost);
2355 macdefine(&e->e_macro, A_PERM, macid("{ntries}"), "0");
2356 macdefine(&e->e_macro, A_PERM, macid("{nrcpts}"), "0");
2357 macdefine(&e->e_macro, A_PERM, macid("{nbadrcpts}"),
2359 e->e_flags |= EF_CLRQUEUE;
2360 sm_setproctitle(true, e, "%s %s: %.80s",
2362 CurSmtpClient, inp);
2364 /* do the processing */
2367 extern char *FullName;
2370 SM_FREE_CLR(FullName);
2372 /* must parse sender first */
2374 setsender(p, e, &delimptr, ' ', false);
2375 if (delimptr != NULL && *delimptr != '\0')
2378 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2380 /* Successfully set e_from, allow logging */
2381 e->e_flags |= EF_LOGSENDER;
2383 /* put resulting triple from parseaddr() into macros */
2384 if (e->e_from.q_mailer != NULL)
2385 macdefine(&e->e_macro, A_PERM,
2386 macid("{mail_mailer}"),
2387 e->e_from.q_mailer->m_name);
2389 macdefine(&e->e_macro, A_PERM,
2390 macid("{mail_mailer}"), NULL);
2391 if (e->e_from.q_host != NULL)
2392 macdefine(&e->e_macro, A_PERM,
2393 macid("{mail_host}"),
2396 macdefine(&e->e_macro, A_PERM,
2397 macid("{mail_host}"), "localhost");
2398 if (e->e_from.q_user != NULL)
2399 macdefine(&e->e_macro, A_PERM,
2400 macid("{mail_addr}"),
2403 macdefine(&e->e_macro, A_PERM,
2404 macid("{mail_addr}"), NULL);
2406 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2408 /* check for possible spoofing */
2409 if (RealUid != 0 && OpMode == MD_SMTP &&
2410 !wordinclass(RealUserName, 't') &&
2411 (!bitnset(M_LOCALMAILER,
2412 e->e_from.q_mailer->m_flags) ||
2413 strcmp(e->e_from.q_user, RealUserName) != 0))
2415 auth_warning(e, "%s owned process doing -bs",
2419 /* reset to default value */
2420 SevenBitInput = SevenBitInput_Saved;
2422 /* now parse ESMTP arguments */
2425 parse_esmtp_args(e, NULL, p, delimptr, "MAIL", args,
2428 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2431 # if _FFR_AUTH_PASSING
2432 /* set the default AUTH= if the sender didn't */
2433 if (e->e_auth_param == NULL)
2435 /* XXX only do this for an MSA? */
2436 e->e_auth_param = macvalue(macid("{auth_authen}"),
2438 if (e->e_auth_param == NULL)
2439 e->e_auth_param = "<>";
2442 ** XXX should we invoke Strust_auth now?
2443 ** authorizing as the client that just
2444 ** authenticated, so we'll trust implicitly
2447 # endif /* _FFR_AUTH_PASSING */
2450 /* do config file checking of the sender */
2451 macdefine(&e->e_macro, A_PERM,
2452 macid("{addr_type}"), "e s");
2454 /* make the "real" sender address available */
2455 macdefine(&e->e_macro, A_TEMP, macid("{mail_from}"),
2457 #endif /* _FFR_MAIL_MACRO */
2458 if (rscheck("check_mail", addr,
2459 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2460 NULL, e->e_id, NULL) != EX_OK ||
2462 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2463 macdefine(&e->e_macro, A_PERM,
2464 macid("{addr_type}"), NULL);
2466 if (MaxMessageSize > 0 &&
2467 (e->e_msgsize > MaxMessageSize ||
2470 usrerr("552 5.2.3 Message size exceeds fixed maximum message size (%ld)",
2472 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2476 ** XXX always check whether there is at least one fs
2477 ** with enough space?
2478 ** However, this may not help much: the queue group
2479 ** selection may later on select a FS that hasn't
2483 if ((NumFileSys == 1 || NumQueue == 1) &&
2484 !enoughdiskspace(e->e_msgsize, e)
2485 #if _FFR_ANY_FREE_FS
2486 && !filesys_free(e->e_msgsize)
2487 #endif /* _FFR_ANY_FREE_FS */
2491 ** We perform this test again when the
2492 ** queue directory is selected, in collect.
2495 usrerr("452 4.4.5 Insufficient disk space; try again later");
2496 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2499 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2503 if (smtp.sm_milterlist && smtp.sm_milterize &&
2504 !bitset(EF_DISCARD, e->e_flags))
2509 response = milter_envfrom(args, e, &state);
2510 MILTER_REPLY("from");
2514 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2516 message("250 2.1.0 Sender ok");
2517 smtp.sm_gotmail = true;
2519 SM_EXCEPT(exc, "[!F]*")
2522 ** An error occurred while processing a MAIL command.
2523 ** Jump to the common error handling code.
2533 e->e_flags &= ~EF_PM_NOTIFY;
2537 case CMDRCPT: /* rcpt -- designate recipient */
2539 macdefine(&e->e_macro, A_PERM,
2540 macid("{rcpt_mailer}"), NULL);
2541 macdefine(&e->e_macro, A_PERM,
2542 macid("{rcpt_host}"), NULL);
2543 macdefine(&e->e_macro, A_PERM,
2544 macid("{rcpt_addr}"), NULL);
2546 (void) memset(&addr_st, '\0', sizeof(addr_st));
2548 milter_rcpt_added = false;
2549 smtp.sm_e_nrcpts_orig = e->e_nrcpts;
2551 #if _FFR_BADRCPT_SHUTDOWN
2553 ** hack to deal with hack, see below:
2554 ** n_badrcpts is increased if limit is reached.
2557 n_badrcpts_adj = (BadRcptThrottle > 0 &&
2558 n_badrcpts > BadRcptThrottle &&
2560 ? n_badrcpts - 1 : n_badrcpts;
2561 if (BadRcptShutdown > 0 &&
2562 n_badrcpts_adj >= BadRcptShutdown &&
2563 (BadRcptShutdownGood == 0 ||
2564 smtp.sm_nrcpts == 0 ||
2565 (n_badrcpts_adj * 100 /
2566 (smtp.sm_nrcpts + n_badrcpts) >=
2567 BadRcptShutdownGood)))
2570 sm_syslog(LOG_INFO, e->e_id,
2571 "%s: Possible SMTP RCPT flood, shutting down connection.",
2573 message("421 4.7.0 %s Too many bad recipients; closing connection",
2576 /* arrange to ignore any current send list */
2577 e->e_sendqueue = NULL;
2580 #endif /* _FFR_BADRCPT_SHUTDOWN */
2581 if (BadRcptThrottle > 0 &&
2582 n_badrcpts >= BadRcptThrottle)
2585 n_badrcpts == BadRcptThrottle)
2587 sm_syslog(LOG_INFO, e->e_id,
2588 "%s: Possible SMTP RCPT flood, throttling.",
2591 /* To avoid duplicated message */
2597 ** Don't use exponential backoff for now.
2598 ** Some systems will open more connections
2599 ** and actually overload the receiver even
2603 (void) sleep(BadRcptThrottleDelay);
2605 if (!smtp.sm_gotmail)
2607 usrerr("503 5.0.0 Need MAIL before RCPT");
2610 SmtpPhase = "server RCPT";
2616 /* limit flooding of our machine */
2617 if (MaxRcptPerMsg > 0 &&
2618 smtp.sm_nrcpts >= MaxRcptPerMsg)
2620 /* sleep(1); / * slow down? */
2621 usrerr("452 4.5.3 Too many recipients");
2625 if (e->e_sendmode != SM_DELIVER
2627 && (NotFirstDelivery || SM_DM_ONE != e->e_sendmode)
2628 #endif /* _FFR_DM_ONE */
2630 e->e_flags |= EF_VRFYONLY;
2634 ** Do not expand recipients at RCPT time (in the call
2635 ** to recipient()) if a milter can delete or reject
2636 ** a RCPT. If they are expanded, it is impossible
2637 ** for removefromlist() to figure out the expanded
2638 ** members of the original recipient and mark them
2642 if (!(smtp.sm_milterlist && smtp.sm_milterize &&
2643 !bitset(EF_DISCARD, e->e_flags)) &&
2644 (smtp.sm_milters.mis_flags &
2645 (MIS_FL_DEL_RCPT|MIS_FL_REJ_RCPT)) != 0)
2646 e->e_flags |= EF_VRFYONLY;
2647 milter_cmd_done = false;
2648 milter_cmd_safe = false;
2651 p = skipword(p, "to");
2654 macdefine(&e->e_macro, A_PERM,
2655 macid("{addr_type}"), "e r");
2656 a = parseaddr(p, NULLADDR, RF_COPYALL, ' ', &delimptr,
2658 macdefine(&e->e_macro, A_PERM,
2659 macid("{addr_type}"), NULL);
2664 usrerr("501 5.0.0 Missing recipient");
2668 if (delimptr != NULL && *delimptr != '\0')
2671 /* put resulting triple from parseaddr() into macros */
2672 if (a->q_mailer != NULL)
2673 macdefine(&e->e_macro, A_PERM,
2674 macid("{rcpt_mailer}"),
2675 a->q_mailer->m_name);
2677 macdefine(&e->e_macro, A_PERM,
2678 macid("{rcpt_mailer}"), NULL);
2679 if (a->q_host != NULL)
2680 macdefine(&e->e_macro, A_PERM,
2681 macid("{rcpt_host}"), a->q_host);
2683 macdefine(&e->e_macro, A_PERM,
2684 macid("{rcpt_host}"), "localhost");
2685 if (a->q_user != NULL)
2686 macdefine(&e->e_macro, A_PERM,
2687 macid("{rcpt_addr}"), a->q_user);
2689 macdefine(&e->e_macro, A_PERM,
2690 macid("{rcpt_addr}"), NULL);
2694 /* now parse ESMTP arguments */
2696 parse_esmtp_args(e, a, p, delimptr, "RCPT", args,
2703 ** rscheck() can trigger an "exception"
2704 ** in which case the execution continues at
2705 ** SM_EXCEPT(exc, "[!F]*")
2706 ** This means milter_cmd_safe is not set
2707 ** and hence milter is not invoked.
2708 ** Would it be "safe" to change that, i.e., use
2709 ** milter_cmd_safe = true;
2710 ** here so a milter is informed (if requested)
2711 ** about RCPTs that are rejected by check_rcpt?
2713 # if _FFR_MILTER_CHECK_REJECTIONS_TOO
2714 milter_cmd_safe = true;
2718 /* do config file checking of the recipient */
2719 macdefine(&e->e_macro, A_PERM,
2720 macid("{addr_type}"), "e r");
2721 if (rscheck("check_rcpt", addr,
2722 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2723 NULL, e->e_id, p_addr_st) != EX_OK ||
2726 macdefine(&e->e_macro, A_PERM,
2727 macid("{addr_type}"), NULL);
2729 /* If discarding, don't bother to verify user */
2730 if (bitset(EF_DISCARD, e->e_flags))
2731 a->q_state = QS_VERIFIED;
2733 milter_cmd_safe = true;
2736 /* save in recipient list after ESMTP mods */
2737 a = recipient(a, &e->e_sendqueue, 0, e);
2738 /* may trigger exception... */
2741 milter_rcpt_added = true;
2744 if(!(Errors > 0) && QS_IS_BADADDR(a->q_state))
2746 /* punt -- should keep message in ADDRESS.... */
2747 usrerr("550 5.1.1 Addressee unknown");
2752 if (smtp.sm_milterlist && smtp.sm_milterize &&
2753 !bitset(EF_DISCARD, e->e_flags))
2758 /* how to get the error codes? */
2761 macdefine(&e->e_macro, A_PERM,
2762 macid("{rcpt_mailer}"),
2765 a->q_status != NULL &&
2766 a->q_rstatus != NULL)
2768 macdefine(&e->e_macro, A_PERM,
2769 macid("{rcpt_host}"),
2771 macdefine(&e->e_macro, A_PERM,
2772 macid("{rcpt_addr}"),
2777 if (addr_st.q_host != NULL)
2778 macdefine(&e->e_macro,
2780 macid("{rcpt_host}"),
2782 if (addr_st.q_user != NULL)
2783 macdefine(&e->e_macro,
2785 macid("{rcpt_addr}"),
2790 response = milter_envrcpt(args, e, &state,
2792 milter_cmd_done = true;
2797 /* no errors during parsing, but might be a duplicate */
2798 e->e_to = a->q_paddr;
2799 if (!(Errors > 0) && !QS_IS_BADADDR(a->q_state))
2801 if (smtp.sm_nrcpts == 0)
2803 message("250 2.1.5 Recipient ok%s",
2804 QS_IS_QUEUEUP(a->q_state) ?
2805 " (will queue)" : "");
2809 /* Is this needed? */
2812 #endif /* !MILTER */
2813 macdefine(&e->e_macro, A_PERM,
2814 macid("{rcpt_mailer}"), NULL);
2815 macdefine(&e->e_macro, A_PERM,
2816 macid("{rcpt_host}"), NULL);
2817 macdefine(&e->e_macro, A_PERM,
2818 macid("{rcpt_addr}"), NULL);
2819 macdefine(&e->e_macro, A_PERM,
2820 macid("{dsn_notify}"), NULL);
2828 SM_EXCEPT(exc, "[!F]*")
2830 /* An exception occurred while processing RCPT */
2831 e->e_flags &= ~(EF_FATALERRS|EF_PM_NOTIFY);
2835 if (smtp.sm_milterlist && smtp.sm_milterize &&
2836 !bitset(EF_DISCARD, e->e_flags) &&
2837 !milter_cmd_done && milter_cmd_safe)
2842 macdefine(&e->e_macro, A_PERM,
2843 macid("{rcpt_mailer}"), "error");
2845 /* how to get the error codes? */
2846 if (addr_st.q_host != NULL)
2847 macdefine(&e->e_macro, A_PERM,
2848 macid("{rcpt_host}"),
2850 else if (a != NULL && a->q_status != NULL)
2851 macdefine(&e->e_macro, A_PERM,
2852 macid("{rcpt_host}"),
2855 if (addr_st.q_user != NULL)
2856 macdefine(&e->e_macro, A_PERM,
2857 macid("{rcpt_addr}"),
2859 else if (a != NULL && a->q_rstatus != NULL)
2860 macdefine(&e->e_macro, A_PERM,
2861 macid("{rcpt_addr}"),
2864 response = milter_envrcpt(args, e, &state,
2866 milter_cmd_done = true;
2868 macdefine(&e->e_macro, A_PERM,
2869 macid("{rcpt_mailer}"), NULL);
2870 macdefine(&e->e_macro, A_PERM,
2871 macid("{rcpt_host}"), NULL);
2872 macdefine(&e->e_macro, A_PERM,
2873 macid("{rcpt_addr}"), NULL);
2875 if (smtp.sm_milterlist && smtp.sm_milterize &&
2876 milter_rcpt_added && milter_cmd_done &&
2879 (void) removefromlist(addr, &e->e_sendqueue, e);
2880 milter_cmd_fail = false;
2881 if (smtp.sm_e_nrcpts_orig < e->e_nrcpts)
2882 e->e_nrcpts = smtp.sm_e_nrcpts_orig;
2889 case CMDDATA: /* data -- text of mail */
2891 if (!smtp_data(&smtp, e))
2895 case CMDRSET: /* rset -- reset state */
2897 message("451 4.0.0 Test failure");
2899 message("250 2.0.0 Reset state");
2900 CLEAR_STATE(cmdbuf);
2903 case CMDVRFY: /* vrfy -- verify address */
2904 case CMDEXPN: /* expn -- expand address */
2905 vrfy = c->cmd_code == CMDVRFY;
2906 DELAY_CONN(vrfy ? "VRFY" : "EXPN");
2910 sm_syslog(LOG_INFO, e->e_id,
2911 "SMTP %s command (%.100s) from %s tempfailed (due to previous checks)",
2912 vrfy ? "VRFY" : "EXPN",
2915 /* RFC 821 doesn't allow 4xy reply code */
2916 usrerr("550 5.7.1 Please try again later");
2919 wt = checksmtpattack(&n_verifies, MAXVRFYCOMMANDS,
2920 false, vrfy ? "VRFY" : "EXPN", e);
2922 previous = curtime();
2923 if ((vrfy && bitset(PRIV_NOVRFY, PrivacyFlags)) ||
2924 (!vrfy && !bitset(SRV_OFFER_EXPN, features)))
2927 message("252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)");
2929 message("502 5.7.0 Sorry, we do not allow this operation");
2931 sm_syslog(LOG_INFO, e->e_id,
2932 "%s: %s [rejected]",
2934 shortenstring(inp, MAXSHORTSTR));
2937 else if (!gothello &&
2938 bitset(vrfy ? PRIV_NEEDVRFYHELO : PRIV_NEEDEXPNHELO,
2941 usrerr("503 5.0.0 I demand that you introduce yourself first");
2947 sm_syslog(LOG_INFO, e->e_id, "%s: %s",
2949 shortenstring(inp, MAXSHORTSTR));
2955 e->e_flags |= EF_VRFYONLY;
2956 while (*p != '\0' && isascii(*p) && isspace(*p))
2960 usrerr("501 5.5.2 Argument required");
2964 /* do config file checking of the address */
2965 if (rscheck(vrfy ? "check_vrfy" : "check_expn",
2966 p, NULL, e, RSF_RMCOMM,
2967 3, NULL, NOQID, NULL) != EX_OK ||
2969 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2970 (void) sendtolist(p, NULLADDR, &vrfyqueue, 0, e);
2976 t = wt - (curtime() - previous);
2981 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2982 if (vrfyqueue == NULL)
2984 usrerr("554 5.5.2 Nothing to %s", vrfy ? "VRFY" : "EXPN");
2986 while (vrfyqueue != NULL)
2988 if (!QS_IS_UNDELIVERED(vrfyqueue->q_state))
2990 vrfyqueue = vrfyqueue->q_next;
2994 /* see if there is more in the vrfy list */
2996 while ((a = a->q_next) != NULL &&
2997 (!QS_IS_UNDELIVERED(a->q_state)))
2999 printvrfyaddr(vrfyqueue, a == NULL, vrfy);
3003 SM_EXCEPT(exc, "[!F]*")
3006 ** An exception occurred while processing VRFY/EXPN
3015 case CMDETRN: /* etrn -- force queue flush */
3018 /* Don't leak queue information via debug flags */
3019 if (!bitset(SRV_OFFER_ETRN, features) || UseMSP ||
3020 (RealUid != 0 && RealUid != TrustedUid &&
3023 /* different message for MSA ? */
3024 message("502 5.7.0 Sorry, we do not allow this operation");
3026 sm_syslog(LOG_INFO, e->e_id,
3027 "%s: %s [rejected]",
3029 shortenstring(inp, MAXSHORTSTR));
3035 sm_syslog(LOG_INFO, e->e_id,
3036 "SMTP ETRN command (%.100s) from %s tempfailed (due to previous checks)",
3038 usrerr(MSG_TEMPFAIL);
3044 usrerr("500 5.5.2 Parameter required");
3048 /* crude way to avoid denial-of-service attacks */
3049 STOP_IF_ATTACK(checksmtpattack(&n_etrn, MAXETRNCOMMANDS,
3053 ** Do config file checking of the parameter.
3054 ** Even though we have srv_features now, we still
3055 ** need this ruleset because the former is called
3056 ** when the connection has been established, while
3057 ** this ruleset is called when the command is
3058 ** actually issued and therefore has all information
3059 ** available to make a decision.
3062 if (rscheck("check_etrn", p, NULL, e,
3063 RSF_RMCOMM, 3, NULL, NOQID, NULL)
3069 sm_syslog(LOG_INFO, e->e_id,
3070 "%s: ETRN %s", CurSmtpClient,
3071 shortenstring(p, MAXSHORTSTR));
3079 qgrp = name2qid(id);
3080 if (!ISVALIDQGRP(qgrp))
3082 usrerr("459 4.5.4 Queue %s unknown",
3086 for (i = 0; i < NumQueue && Queue[i] != NULL;
3088 Queue[i]->qg_nextrun = (time_t) -1;
3089 Queue[qgrp]->qg_nextrun = 0;
3090 ok = run_work_group(Queue[qgrp]->qg_wgrp,
3091 RWG_FORK|RWG_FORCE);
3092 if (ok && Errors == 0)
3093 message("250 2.0.0 Queuing for queue group %s started", id);
3102 new = (QUEUE_CHAR *) sm_malloc(sizeof(QUEUE_CHAR));
3105 syserr("500 5.5.0 ETRN out of memory");
3108 new->queue_match = id;
3109 new->queue_negate = false;
3110 new->queue_next = NULL;
3111 QueueLimitRecipient = new;
3112 ok = runqueue(true, false, false, true);
3113 sm_free(QueueLimitRecipient); /* XXX */
3114 QueueLimitRecipient = NULL;
3115 if (ok && Errors == 0)
3116 message("250 2.0.0 Queuing for node %s started", p);
3119 case CMDHELP: /* help -- give user info */
3124 case CMDNOOP: /* noop -- do nothing */
3126 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
3128 message("250 2.0.0 OK");
3131 case CMDQUIT: /* quit -- leave mail */
3132 message("221 2.0.0 %s closing connection", MyHostName);
3134 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3135 #endif /* PIPELINING */
3137 if (smtp.sm_nrcpts > 0)
3138 logundelrcpts(e, "aborted by sender", 9, false);
3140 /* arrange to ignore any current send list */
3141 e->e_sendqueue = NULL;
3144 /* shutdown TLS connection */
3147 (void) endtls(srv_ssl, "server");
3150 #endif /* STARTTLS */
3152 if (authenticating == SASL_IS_AUTH)
3154 sasl_dispose(&conn);
3155 authenticating = SASL_NOT_AUTH;
3156 /* XXX sasl_done(); this is a child */
3161 /* avoid future 050 messages */
3165 /* close out milter filters */
3170 sm_dprintf("QUIT: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",
3172 bitset(EF_LOGSENDER, e->e_flags),
3174 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3176 e->e_flags &= ~EF_LOGSENDER;
3178 if (lognullconnection && LogLevel > 5 &&
3183 d = macvalue(macid("{daemon_name}"), e);
3188 ** even though this id is "bogus", it makes
3189 ** it simpler to "grep" related events, e.g.,
3190 ** timeouts for the same connection.
3193 sm_syslog(LOG_INFO, e->e_id,
3194 "%s did not issue MAIL/EXPN/VRFY/ETRN during connection to %s",
3199 /* return to handle next connection */
3202 finis(true, true, ExitStat);
3205 /* just to avoid bogus warning from some compilers */
3208 case CMDVERB: /* set verbose mode */
3210 if (!bitset(SRV_OFFER_EXPN, features) ||
3211 !bitset(SRV_OFFER_VERB, features))
3213 /* this would give out the same info */
3214 message("502 5.7.0 Verbose unavailable");
3217 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
3220 set_delivery_mode(SM_DELIVER, e);
3221 message("250 2.0.0 Verbose mode");
3225 case CMDDBGQSHOW: /* show queues */
3226 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3228 printaddr(smioout, e->e_sendqueue, true);
3231 case CMDDBGDEBUG: /* set debug mode */
3232 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1");
3234 message("200 2.0.0 Debug set");
3237 #else /* SMTPDEBUG */
3238 case CMDDBGQSHOW: /* show queues */
3239 case CMDDBGDEBUG: /* set debug mode */
3240 #endif /* SMTPDEBUG */
3241 case CMDLOGBOGUS: /* bogus command */
3242 DELAY_CONN("Bogus");
3244 sm_syslog(LOG_CRIT, e->e_id,
3245 "\"%s\" command from %s (%.100s)",
3246 c->cmd_name, CurSmtpClient,
3247 anynet_ntoa(&RealHostAddr));
3250 case CMDERROR: /* unknown command */
3251 #if MAXBADCOMMANDS > 0
3252 if (++n_badcmds > MAXBADCOMMANDS)
3255 message("421 4.7.0 %s Too many bad commands; closing connection",
3258 /* arrange to ignore any current send list */
3259 e->e_sendqueue = NULL;
3262 #endif /* MAXBADCOMMANDS > 0 */
3264 #if MILTER && SMFI_VERSION > 2
3265 if (smtp.sm_milterlist && smtp.sm_milterize &&
3266 !bitset(EF_DISCARD, e->e_flags))
3271 if (MilterLogLevel > 9)
3272 sm_syslog(LOG_INFO, e->e_id,
3273 "Sending \"%s\" to Milter", inp);
3274 response = milter_unknown(inp, e, &state);
3275 MILTER_REPLY("unknown");
3276 if (state == SMFIR_REPLYCODE ||
3277 state == SMFIR_REJECT ||
3278 state == SMFIR_TEMPFAIL ||
3279 state == SMFIR_SHUTDOWN)
3281 /* MILTER_REPLY already gave an error */
3285 #endif /* MILTER && SMFI_VERSION > 2 */
3287 usrerr("500 5.5.1 Command unrecognized: \"%s\"",
3288 shortenstring(inp, MAXSHORTSTR));
3292 DELAY_CONN("Unimpl");
3293 usrerr("502 5.5.1 Command not implemented: \"%s\"",
3294 shortenstring(inp, MAXSHORTSTR));
3298 DELAY_CONN("default");
3300 syserr("500 5.5.0 smtp: unknown code %d", c->cmd_code);
3307 SM_EXCEPT(exc, "[!F]*")
3310 ** The only possible exception is "E:mta.quickabort".
3311 ** There is nothing to do except fall through and loop.
3318 ** SMTP_DATA -- implement the SMTP DATA command.
3321 ** smtp -- status of SMTP connection.
3325 ** true iff SMTP session can continue.
3328 ** possibly sends message.
3346 unsigned int features;
3349 SmtpPhase = "server DATA";
3350 if (!smtp->sm_gotmail)
3352 usrerr("503 5.0.0 Need MAIL command");
3355 else if (smtp->sm_nrcpts <= 0)
3357 usrerr("503 5.0.0 Need RCPT (recipient)");
3360 (void) sm_snprintf(buf, sizeof(buf), "%u", smtp->sm_nrcpts);
3361 if (rscheck("check_data", buf, NULL, e,
3362 RSF_RMCOMM|RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL,
3363 e->e_id, NULL) != EX_OK)
3366 #if MILTER && SMFI_VERSION > 3
3367 if (smtp->sm_milterlist && smtp->sm_milterize &&
3368 !bitset(EF_DISCARD, e->e_flags))
3372 int savelogusrerrs = LogUsrErrs;
3374 response = milter_data_cmd(e, &state);
3377 case SMFIR_REPLYCODE:
3378 if (MilterLogLevel > 3)
3380 sm_syslog(LOG_INFO, e->e_id,
3381 "Milter: cmd=data, reject=%s",
3385 #if _FFR_MILTER_ENHSC
3386 if (ISSMTPCODE(response))
3387 (void) extenhsc(response + 4, ' ', e->e_enhsc);
3388 #endif /* _FFR_MILTER_ENHSC */
3391 if (strncmp(response, "421 ", 4) == 0
3392 || strncmp(response, "421-", 4) == 0)
3394 e->e_sendqueue = NULL;
3400 if (MilterLogLevel > 3)
3402 sm_syslog(LOG_INFO, e->e_id,
3403 "Milter: cmd=data, reject=550 5.7.1 Command rejected");
3406 #if _FFR_MILTER_ENHSC
3407 (void) sm_strlcpy(e->e_enhsc, "5.7.1",
3408 sizeof(e->e_enhsc));
3409 #endif /* _FFR_MILTER_ENHSC */
3410 usrerr("550 5.7.1 Command rejected");
3414 if (MilterLogLevel > 3)
3415 sm_syslog(LOG_INFO, e->e_id,
3416 "Milter: cmd=data, discard");
3417 e->e_flags |= EF_DISCARD;
3420 case SMFIR_TEMPFAIL:
3421 if (MilterLogLevel > 3)
3423 sm_syslog(LOG_INFO, e->e_id,
3424 "Milter: cmd=data, reject=%s",
3428 #if _FFR_MILTER_ENHSC
3429 (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc);
3430 #endif /* _FFR_MILTER_ENHSC */
3431 usrerr(MSG_TEMPFAIL);
3434 case SMFIR_SHUTDOWN:
3435 if (MilterLogLevel > 3)
3437 sm_syslog(LOG_INFO, e->e_id,
3438 "Milter: cmd=data, reject=421 4.7.0 %s closing connection",
3442 usrerr("421 4.7.0 %s closing connection", MyHostName);
3443 e->e_sendqueue = NULL;
3446 LogUsrErrs = savelogusrerrs;
3447 if (response != NULL)
3448 sm_free(response); /* XXX */
3450 #endif /* MILTER && SMFI_VERSION > 3 */
3452 /* put back discard bit */
3453 if (smtp->sm_discard)
3454 e->e_flags |= EF_DISCARD;
3456 /* check to see if we need to re-expand aliases */
3457 /* also reset QS_BADADDR on already-diagnosted addrs */
3458 doublequeue = false;
3459 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3461 if (QS_IS_VERIFIED(a->q_state) &&
3462 !bitset(EF_DISCARD, e->e_flags))
3464 /* need to re-expand aliases */
3467 if (QS_IS_BADADDR(a->q_state))
3469 /* make this "go away" */
3470 a->q_state = QS_DONTSEND;
3474 /* collect the text of the message */
3475 SmtpPhase = "collect";
3478 collect(InChannel, true, NULL, e, true);
3480 /* redefine message size */
3481 (void) sm_snprintf(buf, sizeof(buf), "%ld", e->e_msgsize);
3482 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3484 /* rscheck() will set Errors or EF_DISCARD if it trips */
3485 (void) rscheck("check_eom", buf, NULL, e, RSF_UNSTRUCTURED|RSF_COUNT,
3486 3, NULL, e->e_id, NULL);
3489 milteraccept = true;
3490 if (smtp->sm_milterlist && smtp->sm_milterize &&
3492 !bitset(EF_DISCARD, e->e_flags))
3497 response = milter_data(e, &state);
3500 case SMFIR_REPLYCODE:
3501 if (MilterLogLevel > 3)
3502 sm_syslog(LOG_INFO, e->e_id,
3503 "Milter: data, reject=%s",
3505 milteraccept = false;
3506 #if _FFR_MILTER_ENHSC
3507 if (ISSMTPCODE(response))
3508 (void) extenhsc(response + 4, ' ', e->e_enhsc);
3509 #endif /* _FFR_MILTER_ENHSC */
3511 if (strncmp(response, "421 ", 4) == 0
3512 || strncmp(response, "421-", 4) == 0)
3517 milteraccept = false;
3518 if (MilterLogLevel > 3)
3519 sm_syslog(LOG_INFO, e->e_id,
3520 "Milter: data, reject=554 5.7.1 Command rejected");
3521 usrerr("554 5.7.1 Command rejected");
3525 if (MilterLogLevel > 3)
3526 sm_syslog(LOG_INFO, e->e_id,
3527 "Milter: data, discard");
3528 milteraccept = false;
3529 e->e_flags |= EF_DISCARD;
3532 case SMFIR_TEMPFAIL:
3533 if (MilterLogLevel > 3)
3534 sm_syslog(LOG_INFO, e->e_id,
3535 "Milter: data, reject=%s",
3537 milteraccept = false;
3538 #if _FFR_MILTER_ENHSC
3539 (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc);
3540 #endif /* _FFR_MILTER_ENHSC */
3541 usrerr(MSG_TEMPFAIL);
3544 case SMFIR_SHUTDOWN:
3545 if (MilterLogLevel > 3)
3546 sm_syslog(LOG_INFO, e->e_id,
3547 "Milter: data, reject=421 4.7.0 %s closing connection",
3549 milteraccept = false;
3550 usrerr("421 4.7.0 %s closing connection", MyHostName);
3554 if (response != NULL)
3558 /* Milter may have changed message size */
3559 (void) sm_snprintf(buf, sizeof(buf), "%ld", e->e_msgsize);
3560 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3562 /* abort message filters that didn't get the body & log msg is OK */
3563 if (smtp->sm_milterlist && smtp->sm_milterize)
3566 if (milteraccept && MilterLogLevel > 9)
3567 sm_syslog(LOG_INFO, e->e_id, "Milter accept: message");
3571 ** If SuperSafe is SAFE_REALLY_POSTMILTER, and we don't have milter or
3572 ** milter accepted message, sync it now
3574 ** XXX This is almost a copy of the code in collect(): put it into
3575 ** a function that is called from both places?
3578 if (milteraccept && SuperSafe == SAFE_REALLY_POSTMILTER)
3581 SM_FILE_T *volatile df;
3585 dfname = queuename(e, DATAFL_LETTER);
3586 if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0
3592 if (save_errno == EEXIST)
3597 if (stat(dfname, &st) < 0)
3600 syserr("@collect: bfcommit(%s): already on disk, size=%ld",
3601 dfname, (long) st.st_size);
3602 dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
3604 dumpfd(dfd, true, true);
3607 dferror(df, "bfcommit", e);
3609 finis(save_errno != EEXIST, true, ExitStat);
3611 else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0)
3613 dferror(df, "sm_io_getinfo", e);
3615 finis(true, true, ExitStat);
3618 else if (fsync(afd) < 0)
3620 dferror(df, "fsync", e);
3622 finis(true, true, ExitStat);
3625 else if (sm_io_close(df, SM_TIME_DEFAULT) < 0)
3627 dferror(df, "sm_io_close", e);
3629 finis(true, true, ExitStat);
3633 /* Now reopen the df file */
3634 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
3635 SM_IO_RDONLY, NULL);
3636 if (e->e_dfp == NULL)
3638 /* we haven't acked receipt yet, so just chuck this */
3639 syserr("@Cannot reopen %s", dfname);
3640 finis(true, true, ExitStat);
3646 /* Check if quarantining stats should be updated */
3647 if (e->e_quarmsg != NULL)
3648 markstats(e, NULL, STATS_QUARANTINE);
3651 ** If a header/body check (header checks or milter)
3652 ** set EF_DISCARD, don't queueup the message --
3653 ** that would lose the EF_DISCARD bit and deliver
3657 if (bitset(EF_DISCARD, e->e_flags))
3658 doublequeue = false;
3660 aborting = Errors > 0;
3661 if (!(aborting || bitset(EF_DISCARD, e->e_flags)) &&
3662 (QueueMode == QM_QUARANTINE || e->e_quarmsg == NULL) &&
3663 !split_by_recipient(e))
3664 aborting = bitset(EF_FATALERRS, e->e_flags);
3670 /* Log who the mail would have gone to */
3671 logundelrcpts(e, e->e_message, 8, false);
3674 ** If something above refused the message, we still haven't
3675 ** accepted responsibility for it. Don't send DSNs.
3678 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
3679 q->q_flags &= ~Q_PINGFLAGS;
3686 /* from now on, we have to operate silently */
3691 ** Clear message, it may contain an error from the SMTP dialogue.
3692 ** This error must not show up in the queue.
3693 ** Some error message should show up, e.g., alias database
3694 ** not available, but others shouldn't, e.g., from check_rcpt.
3697 e->e_message = NULL;
3701 ** Arrange to send to everyone.
3702 ** If sending to multiple people, mail back
3703 ** errors rather than reporting directly.
3704 ** In any case, don't mail back errors for
3705 ** anything that has happened up to
3706 ** now (the other end will do this).
3707 ** Truncate our transcript -- the mail has gotten
3708 ** to us successfully, and if we have
3709 ** to mail this back, it will be easier
3711 ** Then send to everyone.
3712 ** Finally give a reply code. If an error has
3713 ** already been given, don't mail a
3715 ** We goose error returns by clearing error bit.
3718 SmtpPhase = "delivery";
3719 (void) sm_io_setinfo(e->e_xfp, SM_BF_TRUNCATE, NULL);
3723 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
3724 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
3725 #endif /* NAMED_BIND */
3727 for (ee = e; ee != NULL; ee = ee->e_sibling)
3729 /* make sure we actually do delivery */
3730 ee->e_flags &= ~EF_CLRQUEUE;
3732 /* from now on, operate silently */
3733 ee->e_errormode = EM_MAIL;
3737 /* make sure it is in the queue */
3738 queueup(ee, false, true);
3744 /* send to all recipients */
3747 if (SM_DM_ONE == e->e_sendmode)
3749 if (NotFirstDelivery)
3752 e->e_sendmode = SM_QUEUE;
3757 NotFirstDelivery = true;
3760 #endif /* _FFR_DM_ONE */
3766 /* put back id for SMTP logging in putoutmsg() */
3767 oldid = CurEnv->e_id;
3770 /* issue success message */
3772 if (MessageAccept != NULL && *MessageAccept != '\0')
3776 expand(MessageAccept, msg, sizeof(msg), e);
3777 message("250 2.0.0 %s", msg);
3780 #endif /* _FFR_MSG_ACCEPT */
3781 message("250 2.0.0 %s Message accepted for delivery", id);
3782 CurEnv->e_id = oldid;
3784 /* if we just queued, poke it */
3787 bool anything_to_send = false;
3790 for (ee = e; ee != NULL; ee = ee->e_sibling)
3792 if (WILL_BE_QUEUED(ee->e_sendmode))
3794 if (shouldqueue(ee->e_msgpriority, ee->e_ctime))
3796 ee->e_sendmode = SM_QUEUE;
3799 else if (QueueMode != QM_QUARANTINE &&
3800 ee->e_quarmsg != NULL)
3802 ee->e_sendmode = SM_QUEUE;
3805 anything_to_send = true;
3807 /* close all the queue files */
3809 if (ee->e_dfp != NULL)
3811 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
3816 if (anything_to_send)
3820 ** XXX if we don't do this, we get 250 twice
3821 ** because it is also flushed in the child.
3824 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3825 #endif /* PIPELINING */
3826 (void) doworklist(e, true, true);
3832 sm_dprintf("abortmessage: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",
3833 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);
3834 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3836 e->e_flags &= ~EF_LOGSENDER;
3838 /* clean up a bit */
3839 smtp->sm_gotmail = false;
3842 ** Call dropenvelope if and only if the envelope is *not*
3843 ** being processed by the child process forked by doworklist().
3846 if (aborting || bitset(EF_DISCARD, e->e_flags))
3847 (void) dropenvelope(e, true, false);
3850 for (ee = e; ee != NULL; ee = ee->e_sibling)
3853 QueueMode != QM_QUARANTINE &&
3854 ee->e_quarmsg != NULL)
3856 (void) dropenvelope(ee, true, false);
3859 if (WILL_BE_QUEUED(ee->e_sendmode))
3860 (void) dropenvelope(ee, true, false);
3865 features = e->e_features;
3866 sm_rpool_free(e->e_rpool);
3867 newenvelope(e, e, sm_rpool_new_x(NULL));
3868 e->e_flags = BlankEnvelope.e_flags;
3869 e->e_features = features;
3871 /* restore connection quarantining */
3872 if (smtp->sm_quarmsg == NULL)
3874 e->e_quarmsg = NULL;
3875 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
3879 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, smtp->sm_quarmsg);
3880 macdefine(&e->e_macro, A_PERM,
3881 macid("{quarantine}"), e->e_quarmsg);
3886 ** LOGUNDELRCPTS -- log undelivered (or all) recipients.
3890 ** msg -- message for Stat=
3891 ** level -- log level.
3892 ** all -- log all recipients.
3898 ** logs undelivered (or all) recipients
3902 logundelrcpts(e, msg, level, all)
3910 if (LogLevel <= level || msg == NULL || *msg == '\0')
3913 /* Clear $h so relay= doesn't get mislogged by logdelivery() */
3914 macdefine(&e->e_macro, A_PERM, 'h', NULL);
3916 /* Log who the mail would have gone to */
3917 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3919 if (!QS_IS_UNDELIVERED(a->q_state) && !all)
3921 e->e_to = a->q_paddr;
3922 logdelivery(NULL, NULL,
3923 #if _FFR_MILTER_ENHSC
3924 (a->q_status == NULL && e->e_enhsc[0] != '\0')
3926 #endif /* _FFR_MILTER_ENHSC */
3928 msg, NULL, (time_t) 0, e);
3933 ** CHECKSMTPATTACK -- check for denial-of-service attack by repetition
3936 ** pcounter -- pointer to a counter for this command.
3937 ** maxcount -- maximum value for this counter before we
3939 ** waitnow -- sleep now (in this routine)?
3940 ** cname -- command name for logging.
3941 ** e -- the current envelope.
3945 ** STOP_ATTACK if twice as many commands as allowed and
3949 ** Slows down if we seem to be under attack.
3953 checksmtpattack(pcounter, maxcount, waitnow, cname, e)
3954 volatile unsigned int *pcounter;
3955 unsigned int maxcount;
3960 if (maxcount <= 0) /* no limit */
3963 if (++(*pcounter) >= maxcount)
3968 if (*pcounter == maxcount && LogLevel > 5)
3970 sm_syslog(LOG_INFO, e->e_id,
3971 "%s: possible SMTP attack: command=%.40s, count=%u",
3972 CurSmtpClient, cname, *pcounter);
3974 shift = *pcounter - maxcount;
3976 if (shift > MAXSHIFT || s >= MAXTIMEOUT || s <= 0)
3979 #define IS_ATTACK(s) ((MaxChildren > 0 && *pcounter >= maxcount * 2) \
3980 ? STOP_ATTACK : (time_t) s)
3982 /* sleep at least 1 second before returning */
3983 (void) sleep(*pcounter / maxcount);
3984 s -= *pcounter / maxcount;
3985 if (s >= MAXTIMEOUT || s < 0)
3987 if (waitnow && s > 0)
3990 return IS_ATTACK(0);
3992 return IS_ATTACK(s);
3997 ** SETUP_SMTPD_IO -- setup I/O fd correctly for the SMTP server
4006 ** may change I/O fd.
4012 int inchfd, outchfd, outfd;
4014 inchfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
4015 outchfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
4016 outfd = sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL);
4017 if (outchfd != outfd)
4019 /* arrange for debugging output to go to remote host */
4020 (void) dup2(outchfd, outfd);
4024 ** if InChannel and OutChannel are stdin/stdout
4025 ** and connected to ttys
4026 ** and fcntl(STDIN, F_SETFL, O_NONBLOCKING) also changes STDOUT,
4027 ** then "chain" them together.
4030 if (inchfd == STDIN_FILENO && outchfd == STDOUT_FILENO &&
4031 isatty(inchfd) && isatty(outchfd))
4033 int inmode, outmode;
4035 inmode = fcntl(inchfd, F_GETFL, 0);
4039 sm_syslog(LOG_INFO, NOQID,
4040 "fcntl(inchfd, F_GETFL) failed: %s",
4041 sm_errstring(errno));
4044 outmode = fcntl(outchfd, F_GETFL, 0);
4048 sm_syslog(LOG_INFO, NOQID,
4049 "fcntl(outchfd, F_GETFL) failed: %s",
4050 sm_errstring(errno));
4053 if (bitset(O_NONBLOCK, inmode) ||
4054 bitset(O_NONBLOCK, outmode) ||
4055 fcntl(inchfd, F_SETFL, inmode | O_NONBLOCK) == -1)
4057 outmode = fcntl(outchfd, F_GETFL, 0);
4058 if (outmode != -1 && bitset(O_NONBLOCK, outmode))
4060 /* changing InChannel also changes OutChannel */
4061 sm_io_automode(OutChannel, InChannel);
4062 if (tTd(97, 4) && LogLevel > 9)
4063 sm_syslog(LOG_INFO, NOQID,
4064 "set automode for I (%d)/O (%d) in SMTP server",
4068 /* undo change of inchfd */
4069 (void) fcntl(inchfd, F_SETFL, inmode);
4073 ** SKIPWORD -- skip a fixed word.
4076 ** p -- place to start looking.
4077 ** w -- word to skip.
4084 ** clobbers the p data area.
4089 register char *volatile p;
4095 /* find beginning of word */
4099 /* find end of word */
4100 while (*p != '\0' && *p != ':' && !(isascii(*p) && isspace(*p)))
4102 while (isascii(*p) && isspace(*p))
4107 usrerr("501 5.5.2 Syntax error in parameters scanning \"%s\"",
4108 shortenstring(firstp, MAXSHORTSTR));
4117 /* see if the input word matches desired word */
4118 if (sm_strcasecmp(q, w))
4125 ** RESET_MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
4128 ** e -- the envelope.
4135 reset_mail_esmtp_args(e)
4138 /* "size": no reset */
4141 SevenBitInput = SevenBitInput_Saved;
4142 e->e_bodytype = NULL;
4146 macdefine(&e->e_macro, A_PERM, macid("{dsn_envid}"), NULL);
4149 e->e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
4150 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), NULL);
4154 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"), NULL);
4155 e->e_auth_param = "";
4156 # if _FFR_AUTH_PASSING
4157 macdefine(&BlankEnvelope.e_macro, A_PERM,
4158 macid("{auth_author}"), NULL);
4159 # endif /* _FFR_AUTH_PASSING */
4163 e->e_deliver_by = 0;
4168 ** MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
4171 ** a -- address (unused, for compatibility with rcpt_esmtp_args)
4172 ** kp -- the parameter key.
4173 ** vp -- the value of that parameter.
4174 ** e -- the envelope.
4181 mail_esmtp_args(a, kp, vp, e)
4187 if (sm_strcasecmp(kp, "size") == 0)
4191 usrerr("501 5.5.2 SIZE requires a value");
4194 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), vp);
4196 e->e_msgsize = strtol(vp, (char **) NULL, 10);
4197 if (e->e_msgsize == LONG_MAX && errno == ERANGE)
4199 usrerr("552 5.2.3 Message size exceeds maximum value");
4202 if (e->e_msgsize < 0)
4204 usrerr("552 5.2.3 Message size invalid");
4208 else if (sm_strcasecmp(kp, "body") == 0)
4212 usrerr("501 5.5.2 BODY requires a value");
4215 else if (sm_strcasecmp(vp, "8bitmime") == 0)
4217 SevenBitInput = false;
4219 else if (sm_strcasecmp(vp, "7bit") == 0)
4221 SevenBitInput = true;
4225 usrerr("501 5.5.4 Unknown BODY type %s", vp);
4228 e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, vp);
4230 else if (sm_strcasecmp(kp, "envid") == 0)
4232 if (!bitset(SRV_OFFER_DSN, e->e_features))
4234 usrerr("504 5.7.0 Sorry, ENVID not supported, we do not allow DSN");
4239 usrerr("501 5.5.2 ENVID requires a value");
4244 usrerr("501 5.5.4 Syntax error in ENVID parameter value");
4247 if (e->e_envid != NULL)
4249 usrerr("501 5.5.0 Duplicate ENVID parameter");
4252 e->e_envid = sm_rpool_strdup_x(e->e_rpool, vp);
4253 macdefine(&e->e_macro, A_PERM,
4254 macid("{dsn_envid}"), e->e_envid);
4256 else if (sm_strcasecmp(kp, "ret") == 0)
4258 if (!bitset(SRV_OFFER_DSN, e->e_features))
4260 usrerr("504 5.7.0 Sorry, RET not supported, we do not allow DSN");
4265 usrerr("501 5.5.2 RET requires a value");
4268 if (bitset(EF_RET_PARAM, e->e_flags))
4270 usrerr("501 5.5.0 Duplicate RET parameter");
4273 e->e_flags |= EF_RET_PARAM;
4274 if (sm_strcasecmp(vp, "hdrs") == 0)
4275 e->e_flags |= EF_NO_BODY_RETN;
4276 else if (sm_strcasecmp(vp, "full") != 0)
4278 usrerr("501 5.5.2 Bad argument \"%s\" to RET", vp);
4281 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), vp);
4284 else if (sm_strcasecmp(kp, "auth") == 0)
4288 char *auth_param; /* the value of the AUTH=x */
4289 bool saveQuickAbort = QuickAbort;
4290 bool saveSuprErrs = SuprErrs;
4291 bool saveExitStat = ExitStat;
4295 usrerr("501 5.5.2 AUTH= requires a value");
4298 if (e->e_auth_param != NULL)
4300 usrerr("501 5.5.0 Duplicate AUTH parameter");
4303 if ((q = strchr(vp, ' ')) != NULL)
4306 len = strlen(vp) + 1;
4307 auth_param = xalloc(len);
4308 (void) sm_strlcpy(auth_param, vp, len);
4309 if (!xtextok(auth_param))
4311 usrerr("501 5.5.4 Syntax error in AUTH parameter value");
4312 /* just a warning? */
4316 /* XXX define this always or only if trusted? */
4317 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"),
4321 ** call Strust_auth to find out whether
4322 ** auth_param is acceptable (trusted)
4323 ** we shouldn't trust it if not authenticated
4324 ** (required by RFC, leave it to ruleset?)
4329 if (strcmp(auth_param, "<>") != 0 &&
4330 (rscheck("trust_auth", auth_param, NULL, e, RSF_RMCOMM,
4331 9, NULL, NOQID, NULL) != EX_OK || Errors > 0))
4335 q = e->e_auth_param;
4336 sm_dprintf("auth=\"%.100s\" not trusted user=\"%.100s\"\n",
4337 auth_param, (q == NULL) ? "" : q);
4341 e->e_auth_param = "<>";
4342 # if _FFR_AUTH_PASSING
4343 macdefine(&BlankEnvelope.e_macro, A_PERM,
4344 macid("{auth_author}"), NULL);
4345 # endif /* _FFR_AUTH_PASSING */
4350 sm_dprintf("auth=\"%.100s\" trusted\n", auth_param);
4351 e->e_auth_param = sm_rpool_strdup_x(e->e_rpool,
4354 sm_free(auth_param); /* XXX */
4358 QuickAbort = saveQuickAbort;
4359 SuprErrs = saveSuprErrs;
4360 ExitStat = saveExitStat;
4363 #define PRTCHAR(c) ((isascii(c) && isprint(c)) ? (c) : '?')
4366 ** "by" is only accepted if DeliverByMin >= 0.
4367 ** We maybe could add this to the list of server_features.
4370 else if (sm_strcasecmp(kp, "by") == 0 && DeliverByMin >= 0)
4376 usrerr("501 5.5.2 BY= requires a value");
4380 e->e_deliver_by = strtol(vp, &s, 10);
4381 if (e->e_deliver_by == LONG_MIN ||
4382 e->e_deliver_by == LONG_MAX ||
4383 e->e_deliver_by > 999999999l ||
4384 e->e_deliver_by < -999999999l)
4386 usrerr("501 5.5.2 BY=%s out of range", vp);
4389 if (s == NULL || *s != ';')
4391 usrerr("501 5.5.2 BY= missing ';'");
4395 ++s; /* XXX: spaces allowed? */
4397 switch (tolower(*s))
4400 e->e_dlvr_flag = DLVR_NOTIFY;
4403 e->e_dlvr_flag = DLVR_RETURN;
4404 if (e->e_deliver_by <= 0)
4406 usrerr("501 5.5.4 mode R requires BY time > 0");
4409 if (DeliverByMin > 0 && e->e_deliver_by > 0 &&
4410 e->e_deliver_by < DeliverByMin)
4412 usrerr("555 5.5.2 time %ld less than %ld",
4413 e->e_deliver_by, (long) DeliverByMin);
4418 usrerr("501 5.5.2 illegal by-mode '%c'", PRTCHAR(*s));
4421 ++s; /* XXX: spaces allowed? */
4423 switch (tolower(*s))
4426 e->e_dlvr_flag |= DLVR_TRACE;
4431 usrerr("501 5.5.2 illegal by-trace '%c'", PRTCHAR(*s));
4435 /* XXX: check whether more characters follow? */
4439 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4445 ** RCPT_ESMTP_ARGS -- process ESMTP arguments from RCPT line
4448 ** a -- the address corresponding to the To: parameter.
4449 ** kp -- the parameter key.
4450 ** vp -- the value of that parameter.
4451 ** e -- the envelope.
4458 rcpt_esmtp_args(a, kp, vp, e)
4464 if (sm_strcasecmp(kp, "notify") == 0)
4468 if (!bitset(SRV_OFFER_DSN, e->e_features))
4470 usrerr("504 5.7.0 Sorry, NOTIFY not supported, we do not allow DSN");
4475 usrerr("501 5.5.2 NOTIFY requires a value");
4478 a->q_flags &= ~(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY);
4479 a->q_flags |= QHASNOTIFY;
4480 macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), vp);
4482 if (sm_strcasecmp(vp, "never") == 0)
4484 for (p = vp; p != NULL; vp = p)
4488 s = p = strchr(p, ',');
4491 if (sm_strcasecmp(vp, "success") == 0)
4492 a->q_flags |= QPINGONSUCCESS;
4493 else if (sm_strcasecmp(vp, "failure") == 0)
4494 a->q_flags |= QPINGONFAILURE;
4495 else if (sm_strcasecmp(vp, "delay") == 0)
4496 a->q_flags |= QPINGONDELAY;
4499 usrerr("501 5.5.4 Bad argument \"%s\" to NOTIFY",
4507 else if (sm_strcasecmp(kp, "orcpt") == 0)
4509 if (!bitset(SRV_OFFER_DSN, e->e_features))
4511 usrerr("504 5.7.0 Sorry, ORCPT not supported, we do not allow DSN");
4516 usrerr("501 5.5.2 ORCPT requires a value");
4519 if (strchr(vp, ';') == NULL || !xtextok(vp))
4521 usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4524 if (a->q_orcpt != NULL)
4526 usrerr("501 5.5.0 Duplicate ORCPT parameter");
4529 a->q_orcpt = sm_rpool_strdup_x(e->e_rpool, vp);
4533 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4538 ** PRINTVRFYADDR -- print an entry in the verify queue
4541 ** a -- the address to print.
4542 ** last -- set if this is the last one.
4543 ** vrfy -- set if this is a VRFY command.
4549 ** Prints the appropriate 250 codes.
4551 #define OFFF (3 + 1 + 5 + 1) /* offset in fmt: SMTP reply + enh. code */
4554 printvrfyaddr(a, last, vrfy)
4555 register ADDRESS *a;
4561 if (vrfy && a->q_mailer != NULL &&
4562 !bitnset(M_VRFY250, a->q_mailer->m_flags))
4563 (void) sm_strlcpy(fmtbuf, "252", sizeof(fmtbuf));
4565 (void) sm_strlcpy(fmtbuf, "250", sizeof(fmtbuf));
4566 fmtbuf[3] = last ? ' ' : '-';
4567 (void) sm_strlcpy(&fmtbuf[4], "2.1.5 ", sizeof(fmtbuf) - 4);
4568 if (a->q_fullname == NULL)
4570 if ((a->q_mailer == NULL ||
4571 a->q_mailer->m_addrtype == NULL ||
4572 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4573 strchr(a->q_user, '@') == NULL)
4574 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s@%s>",
4575 sizeof(fmtbuf) - OFFF);
4577 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s>",
4578 sizeof(fmtbuf) - OFFF);
4579 message(fmtbuf, a->q_user, MyHostName);
4583 if ((a->q_mailer == NULL ||
4584 a->q_mailer->m_addrtype == NULL ||
4585 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4586 strchr(a->q_user, '@') == NULL)
4587 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s@%s>",
4588 sizeof(fmtbuf) - OFFF);
4590 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s>",
4591 sizeof(fmtbuf) - OFFF);
4592 message(fmtbuf, a->q_fullname, a->q_user, MyHostName);
4598 ** SASLMECHS -- get list of possible AUTH mechanisms
4601 ** conn -- SASL connection info.
4602 ** mechlist -- output parameter for list of mechanisms.
4609 saslmechs(conn, mechlist)
4613 int len, num, result;
4615 /* "user" is currently unused */
4617 result = sasl_listmech(conn, NULL,
4618 "", " ", "", (const char **) mechlist,
4619 (unsigned int *)&len, &num);
4620 # else /* SASL >= 20000 */
4621 result = sasl_listmech(conn, "user", /* XXX */
4622 "", " ", "", mechlist,
4623 (unsigned int *)&len, (unsigned int *)&num);
4624 # endif /* SASL >= 20000 */
4625 if (result != SASL_OK)
4628 sm_syslog(LOG_WARNING, NOQID,
4629 "AUTH error: listmech=%d, num=%d",
4636 sm_syslog(LOG_INFO, NOQID,
4637 "AUTH: available mech=%s, allowed mech=%s",
4638 *mechlist, AuthMechanisms);
4639 *mechlist = intersect(AuthMechanisms, *mechlist, NULL);
4643 *mechlist = NULL; /* be paranoid... */
4644 if (result == SASL_OK && LogLevel > 9)
4645 sm_syslog(LOG_WARNING, NOQID,
4646 "AUTH warning: no mechanisms");
4653 ** PROXY_POLICY -- define proxy policy for AUTH
4657 ** context -- unused.
4658 ** requested_user -- authorization identity.
4659 ** rlen -- authorization identity length.
4660 ** auth_identity -- authentication identity.
4661 ** alen -- authentication identity length.
4662 ** def_realm -- default user realm.
4663 ** urlen -- user realm length.
4664 ** propctx -- unused.
4670 ** sets {auth_authen} macro.
4674 proxy_policy(conn, context, requested_user, rlen, auth_identity, alen,
4675 def_realm, urlen, propctx)
4678 const char *requested_user;
4680 const char *auth_identity;
4682 const char *def_realm;
4684 struct propctx *propctx;
4686 if (auth_identity == NULL)
4689 macdefine(&BlankEnvelope.e_macro, A_TEMP,
4690 macid("{auth_authen}"), (char *) auth_identity);
4694 # else /* SASL >= 20000 */
4697 ** PROXY_POLICY -- define proxy policy for AUTH
4700 ** context -- unused.
4701 ** auth_identity -- authentication identity.
4702 ** requested_user -- authorization identity.
4703 ** user -- allowed user (output).
4704 ** errstr -- possible error string (output).
4711 proxy_policy(context, auth_identity, requested_user, user, errstr)
4713 const char *auth_identity;
4714 const char *requested_user;
4716 const char **errstr;
4718 if (user == NULL || auth_identity == NULL)
4720 *user = newstr(auth_identity);
4723 # endif /* SASL >= 20000 */
4728 ** INITSRVTLS -- initialize server side TLS
4731 ** tls_ok -- should tls initialization be done?
4737 ** sets tls_ok_srv which is a static variable in this module.
4738 ** Do NOT remove assignments to it!
4748 /* do NOT remove assignment */
4749 tls_ok_srv = inittls(&srv_ctx, TLS_Srv_Opts, Srv_SSL_Options, true,
4750 SrvCertFile, SrvKeyFile,
4751 CACertPath, CACertFile, DHParams);
4754 #endif /* STARTTLS */
4756 ** SRVFEATURES -- get features for SMTP server
4759 ** e -- envelope (should be session context).
4760 ** clientname -- name of client.
4761 ** features -- default features for this invocation.
4767 /* table with options: it uses just one character, how about strings? */
4771 unsigned int srvf_flag;
4772 } srv_feat_table[] =
4774 { 'A', SRV_OFFER_AUTH },
4775 { 'B', SRV_OFFER_VERB },
4776 { 'C', SRV_REQ_SEC },
4777 { 'D', SRV_OFFER_DSN },
4778 { 'E', SRV_OFFER_ETRN },
4779 { 'L', SRV_REQ_AUTH },
4782 { 'N', SRV_NO_PIPE },
4783 # endif /* _FFR_NO_PIPE */
4784 { 'P', SRV_OFFER_PIPE },
4785 #endif /* PIPELINING */
4786 { 'R', SRV_VRFY_CLT }, /* same as V; not documented */
4787 { 'S', SRV_OFFER_TLS },
4788 /* { 'T', SRV_TMP_FAIL }, */
4789 { 'V', SRV_VRFY_CLT },
4790 { 'X', SRV_OFFER_EXPN },
4791 /* { 'Y', SRV_OFFER_VRFY }, */
4796 srvfeatures(e, clientname, features)
4799 unsigned int features;
4803 char pvpbuf[PSBUFSIZE];
4806 r = rscap("srv_features", clientname, "", e, &pvp, pvpbuf,
4810 if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
4812 if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0)
4813 return SRV_TMP_FAIL;
4816 ** General rule (see sendmail.h, d_flags):
4817 ** lower case: required/offered, upper case: Not required/available
4819 ** Since we can change some features per daemon, we have both
4820 ** cases here: turn on/off a feature.
4823 for (i = 1; pvp[i] != NULL; i++)
4829 if ((opt = srv_feat_table[j].srvf_opt) == '\0')
4832 sm_syslog(LOG_WARNING, e->e_id,
4833 "srvfeatures: unknown feature %s",
4839 features &= ~(srv_feat_table[j].srvf_flag);
4842 if (c == tolower(opt))
4844 features |= srv_feat_table[j].srvf_flag;
4854 ** HELP -- implement the HELP command.
4857 ** topic -- the topic we want help for.
4864 ** outputs the help file to message output.
4866 #define HELPVSTR "#vers "
4867 #define HELPVERSION 2
4874 register SM_FILE_T *hf;
4879 long sff = SFF_OPENASROOT|SFF_REGONLY;
4882 static int foundvers = -1;
4883 extern char Version[];
4885 if (DontLockReadFiles)
4887 if (!bitnset(DBS_HELPFILEINUNSAFEDIRPATH, DontBlameSendmail))
4888 sff |= SFF_SAFEDIRPATH;
4890 if (HelpFile == NULL ||
4891 (hf = safefopen(HelpFile, O_RDONLY, 0444, sff)) == NULL)
4895 message("502 5.3.0 Sendmail %s -- HELP not implemented",
4900 if (topic == NULL || *topic == '\0')
4911 len = strlen(topic);
4913 while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof(buf)) != NULL)
4917 if (foundvers < 0 &&
4918 strncmp(buf, HELPVSTR, strlen(HELPVSTR)) == 0)
4922 if (sm_io_sscanf(buf + strlen(HELPVSTR), "%d",
4928 if (strncmp(buf, topic, len) == 0)
4934 /* print version if no/old vers# in file */
4935 if (foundvers < 2 && !noinfo)
4936 message("214-2.0.0 This is Sendmail version %s", Version);
4938 p = strpbrk(buf, " \t");
4940 p = buf + strlen(buf) - 1;
4947 int lbs = sizeof(buf) - (p - buf);
4949 lbp = translate_dollars(p, p, &lbs);
4950 expand(lbp, inp, sizeof(inp), e);
4955 message("214-2.0.0 %s", p);
4961 message("504 5.3.0 HELP topic \"%.10s\" unknown", topic);
4963 message("214 2.0.0 End of HELP info");
4965 if (foundvers != 0 && foundvers < HELPVERSION)
4968 sm_syslog(LOG_WARNING, e->e_id,
4969 "%s too old (require version %d)",
4970 HelpFile, HELPVERSION);
4972 /* avoid log next time */
4976 (void) sm_io_close(hf, SM_TIME_DEFAULT);
4981 ** RESET_SASLCONN -- reset SASL connection data
4984 ** conn -- SASL connection context
4985 ** hostname -- host name
4986 ** various connection data
4993 reset_saslconn(sasl_conn_t **conn, char *hostname,
4995 char *remoteip, char *localip,
4996 char *auth_id, sasl_ssf_t * ext_ssf)
4997 # else /* SASL >= 20000 */
4998 struct sockaddr_in *saddr_r, struct sockaddr_in *saddr_l,
4999 sasl_external_properties_t * ext_ssf)
5000 # endif /* SASL >= 20000 */
5006 result = sasl_server_new("smtp", hostname, NULL, NULL, NULL,
5009 /* use empty realm: only works in SASL > 1.5.5 */
5010 result = sasl_server_new("smtp", hostname, "", NULL, 0, conn);
5011 # else /* SASL >= 20000 */
5012 /* use no realm -> realm is set to hostname by SASL lib */
5013 result = sasl_server_new("smtp", hostname, NULL, NULL, 0,
5015 # endif /* SASL >= 20000 */
5016 if (result != SASL_OK)
5020 # if NETINET || NETINET6
5021 if (remoteip != NULL && *remoteip != '\0')
5022 result = sasl_setprop(*conn, SASL_IPREMOTEPORT, remoteip);
5023 if (result != SASL_OK)
5026 if (localip != NULL && *localip != '\0')
5027 result = sasl_setprop(*conn, SASL_IPLOCALPORT, localip);
5028 if (result != SASL_OK)
5030 # endif /* NETINET || NETINET6 */
5032 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
5033 if (result != SASL_OK)
5036 result = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, auth_id);
5037 if (result != SASL_OK)
5039 # else /* SASL >= 20000 */
5041 if (saddr_r != NULL)
5042 result = sasl_setprop(*conn, SASL_IP_REMOTE, saddr_r);
5043 if (result != SASL_OK)
5046 if (saddr_l != NULL)
5047 result = sasl_setprop(*conn, SASL_IP_LOCAL, saddr_l);
5048 if (result != SASL_OK)
5050 # endif /* NETINET */
5052 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
5053 if (result != SASL_OK)
5055 # endif /* SASL >= 20000 */