2 * Copyright (c) 1998-2010, 2012-2014 Proofpoint, Inc. and its suppliers.
4 * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved.
5 * Copyright (c) 1988, 1993
6 * The Regents of the University of California. All rights reserved.
8 * By using this file, you agree to the terms and conditions set
9 * forth in the LICENSE file which can be found at the top level of
10 * the sendmail distribution.
16 # include <libmilter/mfapi.h>
17 # include <libmilter/mfdef.h>
20 SM_RCSID("@(#)$Id: srvrsmtp.c,v 8.1016 2013-11-22 20:51:56 ca Exp $")
27 #endif /* SASL || STARTTLS */
29 # define ENC64LEN(l) (((l) + 2) * 4 / 3 + 1)
30 static int saslmechs __P((sasl_conn_t *, char **));
33 # include <openssl/err.h>
34 # include <sysexits.h>
36 static SSL_CTX *srv_ctx = NULL; /* TLS server context */
37 static SSL *srv_ssl = NULL; /* per connection context */
39 static bool tls_ok_srv = false;
41 # define TLS_VERIFY_CLIENT() tls_set_verify(srv_ctx, srv_ssl, \
42 bitset(SRV_VRFY_CLT, features))
46 static bool NotFirstDelivery = false;
47 #endif /* _FFR_DM_ONE */
50 #define SRV_NONE 0x0000 /* none... */
51 #define SRV_OFFER_TLS 0x0001 /* offer STARTTLS */
52 #define SRV_VRFY_CLT 0x0002 /* request a cert */
53 #define SRV_OFFER_AUTH 0x0004 /* offer AUTH */
54 #define SRV_OFFER_ETRN 0x0008 /* offer ETRN */
55 #define SRV_OFFER_VRFY 0x0010 /* offer VRFY (not yet used) */
56 #define SRV_OFFER_EXPN 0x0020 /* offer EXPN */
57 #define SRV_OFFER_VERB 0x0040 /* offer VERB */
58 #define SRV_OFFER_DSN 0x0080 /* offer DSN */
60 # define SRV_OFFER_PIPE 0x0100 /* offer PIPELINING */
62 # define SRV_NO_PIPE 0x0200 /* disable PIPELINING, sleep if used */
63 # endif /* _FFR_NO_PIPE */
64 #endif /* PIPELINING */
65 #define SRV_REQ_AUTH 0x0400 /* require AUTH */
66 #define SRV_REQ_SEC 0x0800 /* require security - equiv to AuthOptions=p */
67 #define SRV_TMP_FAIL 0x1000 /* ruleset caused a temporary failure */
69 static unsigned int srvfeatures __P((ENVELOPE *, char *, unsigned int));
71 #define STOP_ATTACK ((time_t) -1)
72 static time_t checksmtpattack __P((volatile unsigned int *, unsigned int,
73 bool, char *, ENVELOPE *));
74 static void printvrfyaddr __P((ADDRESS *, bool, bool));
75 static char *skipword __P((char *volatile, char *));
76 static void setup_smtpd_io __P((void));
80 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
81 char *_remoteip, char *_localip,
82 char *_auth_id, sasl_ssf_t *_ext_ssf));
84 # define RESET_SASLCONN \
87 result = reset_saslconn(&conn, AuthRealm, remoteip, \
88 localip, auth_id, &ext_ssf); \
89 if (result != SASL_OK) \
93 # else /* SASL >= 20000 */
94 static int reset_saslconn __P((sasl_conn_t **_conn, char *_hostname,
95 struct sockaddr_in *_saddr_r,
96 struct sockaddr_in *_saddr_l,
97 sasl_external_properties_t *_ext_ssf));
98 # define RESET_SASLCONN \
101 result = reset_saslconn(&conn, AuthRealm, &saddr_r, \
102 &saddr_l, &ext_ssf); \
103 if (result != SASL_OK) \
107 # endif /* SASL >= 20000 */
110 extern ENVELOPE BlankEnvelope;
116 (void) sm_snprintf(buf, sizeof(buf), "%d", \
117 BadRcptThrottle > 0 && n_badrcpts > BadRcptThrottle \
118 ? n_badrcpts - 1 : n_badrcpts); \
119 macdefine(&e->e_macro, A_TEMP, macid("{nbadrcpts}"), buf); \
122 #define SKIP_SPACE(s) while (isascii(*s) && isspace(*s)) \
126 ** PARSE_ESMTP_ARGS -- parse EMSTP arguments (for MAIL, RCPT)
130 ** addr_st -- address (RCPT only)
132 ** delimptr -- current position in read buffer
133 ** which -- MAIL/RCPT
134 ** args -- arguments (output)
135 ** esmtp_args -- function to process a single ESMTP argument
142 parse_esmtp_args(e, addr_st, p, delimptr, which, args, esmtp_args)
149 esmtp_args_F esmtp_args;
157 while (p != NULL && *p != '\0')
163 /* locate the beginning of the keyword */
169 /* skip to the value portion */
170 while ((isascii(*p) && isalnum(*p)) || *p == '-')
178 /* skip to the end of the value */
179 while (*p != '\0' && *p != ' ' &&
180 !(isascii(*p) && iscntrl(*p)) &&
189 sm_dprintf("%s: got arg %s=\"%s\"\n", which, kp,
190 vp == NULL ? "<null>" : vp);
192 esmtp_args(addr_st, kp, vp, e);
198 if (argno >= MAXSMTPARGS - 1)
199 usrerr("501 5.5.4 Too many parameters");
210 ** ADDRCPT -- Add a rcpt to sendq list
214 ** sendq -- a pointer to the head of a queue to put
215 ** these people into.
216 ** e -- the envelope in which to add these recipients.
219 ** The number of addresses added to the list.
223 addrcpt(rcpt, sendq, e)
232 SM_REQUIRE(rcpt != NULL);
233 SM_REQUIRE(sendq != NULL);
234 SM_REQUIRE(e != NULL);
237 sm_dprintf("addrcpt: rcpt=%s\n", rcpt);
242 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e b");
243 a = parseaddr(rcpt, NULLADDR, RF_COPYALL, ' ', NULL, e, true);
247 a->q_flags &= ~Q_PINGFLAGS;
248 a->q_flags |= QINTBCC;
251 /* disable alias expansion? */
252 a = recipient(a, sendq, 0, e);
257 macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
261 sm_dprintf("addrcpt: rcpt=%s, flags=%#lx\n", rcpt,
262 a != NULL ? a->q_flags : 0);
268 ** ADDBCC -- Maybe create a copy of an e-mail
272 ** e -- the envelope.
278 ** rscheck() can trigger an "exception"
287 char *newrcpt, empty[1];
296 nobcc = rscheck("bcc", a->q_paddr, NULL, e, RSF_ADDR, 12, NULL, NOQID,
299 sm_dprintf("addbcc: nobcc=%d, Errors=%d, newrcpt=<%s>\n", nobcc, Errors, newrcpt);
300 if (nobcc != EX_OK || Errors > 0 || *newrcpt == '\0')
303 (void) addrcpt(newrcpt, &e->e_sendqueue, e);
306 #else /* _FFR_ADD_BCC */
307 # define addbcc(a, e)
308 #endif /* _FFR_ADD_BCC */
312 ** RCPTMODS -- Perform rcpt modifications if requested
315 ** rcpt -- current RCPT
316 ** e -- the envelope.
329 SM_REQUIRE(rcpt != NULL);
330 SM_REQUIRE(e != NULL);
332 fl = macvalue(macid("{rcpt_flags}"), e);
333 if (fl == NULL || *fl == '\0')
336 sm_dprintf("rcptmods: rcpt=%s, flags=%s\n", rcpt->q_paddr, fl);
339 for ( ; *fl != '\0'; ++fl)
344 rcpt->q_flags &= ~Q_PINGFLAGS;
345 rcpt->q_flags |= QINTBCC;
346 rcpt->q_owner = "<>";
350 rcpt->q_flags &= ~Q_PINGFLAGS;
351 rcpt->q_owner = "<>";
355 rcpt->q_flags |= QDYNMAILER;
356 newmodmailer(rcpt, *fl);
360 sm_syslog(LOG_INFO, e->e_id,
361 "rcpt=%s, rcpt_flags=%s, status=unknown",
367 /* reset macro to avoid confusion later on */
368 macdefine(&e->e_macro, A_PERM, macid("{rcpt_flags}"), NULL);
371 #else /* _FFR_RCPTFLAGS */
372 # define rcptmods(a, e)
373 #endif /* _FFR_RCPTFLAGS */
376 ** SMTP -- run the SMTP protocol.
379 ** nullserver -- if non-NULL, rejection message for
380 ** (almost) all SMTP commands.
381 ** d_flags -- daemon flags
382 ** e -- the envelope.
388 ** Reads commands from the input channel and processes them.
392 ** Notice: The smtp server doesn't have a session context like the client
393 ** side has (mci). Therefore some data (session oriented) is allocated
394 ** or assigned to the "wrong" structure (esp. STARTTLS, AUTH).
395 ** This should be fixed in a successor version.
400 char *cmd_name; /* command name */
401 int cmd_code; /* internal code, see below */
404 /* values for cmd_code */
405 #define CMDERROR 0 /* bad command */
406 #define CMDMAIL 1 /* mail -- designate sender */
407 #define CMDRCPT 2 /* rcpt -- designate recipient */
408 #define CMDDATA 3 /* data -- send message text */
409 #define CMDRSET 4 /* rset -- reset state */
410 #define CMDVRFY 5 /* vrfy -- verify address */
411 #define CMDEXPN 6 /* expn -- expand address */
412 #define CMDNOOP 7 /* noop -- do nothing */
413 #define CMDQUIT 8 /* quit -- close connection and die */
414 #define CMDHELO 9 /* helo -- be polite */
415 #define CMDHELP 10 /* help -- give usage info */
416 #define CMDEHLO 11 /* ehlo -- extended helo (RFC 1425) */
417 #define CMDETRN 12 /* etrn -- flush queue */
419 # define CMDAUTH 13 /* auth -- SASL authenticate */
422 # define CMDSTLS 14 /* STARTTLS -- start TLS session */
423 #endif /* STARTTLS */
424 /* non-standard commands */
425 #define CMDVERB 17 /* verb -- go into verbose mode */
426 /* unimplemented commands from RFC 821 */
427 #define CMDUNIMPL 19 /* unimplemented rfc821 commands */
428 /* use this to catch and log "door handle" attempts on your system */
429 #define CMDLOGBOGUS 23 /* bogus command that should be logged */
430 /* debugging-only commands, only enabled if SMTPDEBUG is defined */
431 #define CMDDBGQSHOW 24 /* showq -- show send queue */
432 #define CMDDBGDEBUG 25 /* debug -- set debug mode */
435 ** Note: If you change this list, remember to update 'helpfile'
438 static struct cmd CmdTab[] =
453 { "send", CMDUNIMPL },
454 { "saml", CMDUNIMPL },
455 { "soml", CMDUNIMPL },
456 { "turn", CMDUNIMPL },
458 { "auth", CMDAUTH, },
461 { "starttls", CMDSTLS, },
462 #endif /* STARTTLS */
463 /* remaining commands are here only to trap and log attempts to use them */
464 { "showq", CMDDBGQSHOW },
465 { "debug", CMDDBGDEBUG },
466 { "wiz", CMDLOGBOGUS },
471 static char *CurSmtpClient; /* who's at the other end of channel */
473 #ifndef MAXBADCOMMANDS
474 # define MAXBADCOMMANDS 25 /* maximum number of bad commands */
475 #endif /* ! MAXBADCOMMANDS */
476 #ifndef MAXHELOCOMMANDS
477 # define MAXHELOCOMMANDS 3 /* max HELO/EHLO commands before slowdown */
478 #endif /* ! MAXHELOCOMMANDS */
479 #ifndef MAXVRFYCOMMANDS
480 # define MAXVRFYCOMMANDS 6 /* max VRFY/EXPN commands before slowdown */
481 #endif /* ! MAXVRFYCOMMANDS */
482 #ifndef MAXETRNCOMMANDS
483 # define MAXETRNCOMMANDS 8 /* max ETRN commands before slowdown */
484 #endif /* ! MAXETRNCOMMANDS */
486 # define MAXTIMEOUT (4 * 60) /* max timeout for bad commands */
487 #endif /* ! MAXTIMEOUT */
490 ** Maximum shift value to compute timeout for bad commands.
491 ** This introduces an upper limit of 2^MAXSHIFT for the timeout.
496 #endif /* ! MAXSHIFT */
498 ERROR _MAXSHIFT > 31 is invalid
499 #endif /* MAXSHIFT */
502 #if MAXBADCOMMANDS > 0
503 # define STOP_IF_ATTACK(r) do \
505 if ((r) == STOP_ATTACK) \
509 #else /* MAXBADCOMMANDS > 0 */
510 # define STOP_IF_ATTACK(r) r
511 #endif /* MAXBADCOMMANDS > 0 */
515 static SM_DEBUG_T DebugLeakSmtp = SM_DEBUG_INITIALIZER("leak_smtp",
516 "@(#)$Debug: leak_smtp - trace memory leaks during SMTP processing $");
517 #endif /* SM_HEAP_CHECK */
521 bool sm_gotmail; /* mail command received */
522 unsigned int sm_nrcpts; /* number of successful RCPT commands */
526 bool sm_milterlist; /* any filters in the list? */
527 milters_T sm_milters;
529 /* e_nrcpts from envelope before recipient() call */
530 unsigned int sm_e_nrcpts_orig;
532 char *sm_quarmsg; /* carry quarantining across messages */
535 static bool smtp_data __P((SMTP_T *, ENVELOPE *));
537 #define MSG_TEMPFAIL "451 4.3.2 Please try again later"
540 # define MILTER_ABORT(e) milter_abort((e))
542 # define MILTER_REPLY(str) \
544 int savelogusrerrs = LogUsrErrs; \
546 milter_cmd_fail = true; \
549 case SMFIR_SHUTDOWN: \
550 if (MilterLogLevel > 3) \
552 sm_syslog(LOG_INFO, e->e_id, \
553 "Milter: %s=%s, reject=421, errormode=4", \
555 LogUsrErrs = false; \
558 bool tsave = QuickAbort; \
560 QuickAbort = false; \
561 usrerr("421 4.3.0 closing connection"); \
562 QuickAbort = tsave; \
563 e->e_sendqueue = NULL; \
567 case SMFIR_REPLYCODE: \
568 if (MilterLogLevel > 3) \
570 sm_syslog(LOG_INFO, e->e_id, \
571 "Milter: %s=%s, reject=%s", \
572 str, addr, response); \
573 LogUsrErrs = false; \
575 if (strncmp(response, "421 ", 4) == 0 \
576 || strncmp(response, "421-", 4) == 0) \
578 bool tsave = QuickAbort; \
580 QuickAbort = false; \
582 QuickAbort = tsave; \
583 e->e_sendqueue = NULL; \
591 if (MilterLogLevel > 3) \
593 sm_syslog(LOG_INFO, e->e_id, \
594 "Milter: %s=%s, reject=550 5.7.1 Command rejected", \
596 LogUsrErrs = false; \
598 usrerr("550 5.7.1 Command rejected"); \
601 case SMFIR_DISCARD: \
602 if (MilterLogLevel > 3) \
603 sm_syslog(LOG_INFO, e->e_id, \
604 "Milter: %s=%s, discard", \
606 e->e_flags |= EF_DISCARD; \
607 milter_cmd_fail = false; \
610 case SMFIR_TEMPFAIL: \
611 if (MilterLogLevel > 3) \
613 sm_syslog(LOG_INFO, e->e_id, \
614 "Milter: %s=%s, reject=%s", \
615 str, addr, MSG_TEMPFAIL); \
616 LogUsrErrs = false; \
618 usrerr(MSG_TEMPFAIL); \
621 milter_cmd_fail = false; \
624 LogUsrErrs = savelogusrerrs; \
625 if (response != NULL) \
626 sm_free(response); /* XXX */ \
630 # define MILTER_ABORT(e)
633 /* clear all SMTP state (for HELO/EHLO/RSET) */
634 #define CLEAR_STATE(cmd) \
637 /* abort milter filters */ \
640 if (smtp.sm_nrcpts > 0) \
642 logundelrcpts(e, cmd, 10, false); \
643 smtp.sm_nrcpts = 0; \
644 macdefine(&e->e_macro, A_PERM, \
645 macid("{nrcpts}"), "0"); \
648 e->e_sendqueue = NULL; \
649 e->e_flags |= EF_CLRQUEUE; \
652 sm_dprintf("CLEAR_STATE: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",\
653 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);\
654 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags)) \
655 logsender(e, NULL); \
656 e->e_flags &= ~EF_LOGSENDER; \
658 /* clean up a bit */ \
659 smtp.sm_gotmail = false; \
661 (void) dropenvelope(e, true, false); \
662 sm_rpool_free(e->e_rpool); \
663 e = newenvelope(e, CurEnv, sm_rpool_new_x(NULL)); \
665 e->e_features = features; \
667 /* put back discard bit */ \
668 if (smtp.sm_discard) \
669 e->e_flags |= EF_DISCARD; \
671 /* restore connection quarantining */ \
672 if (smtp.sm_quarmsg == NULL) \
674 e->e_quarmsg = NULL; \
675 macdefine(&e->e_macro, A_PERM, \
676 macid("{quarantine}"), ""); \
680 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, \
682 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), \
687 /* sleep to flatten out connection load */
688 #define MIN_DELAY_LOG 15 /* wait before logging this again */
690 /* is it worth setting the process title for 1s? */
691 #define DELAY_CONN(cmd) \
692 if (DelayLA > 0 && (CurrentLA = getla()) >= DelayLA) \
696 sm_setproctitle(true, e, \
697 "%s: %s: delaying %s: load average: %d", \
698 qid_printname(e), CurSmtpClient, \
700 if (LogLevel > 8 && (dnow = curtime()) > log_delay) \
702 sm_syslog(LOG_INFO, e->e_id, \
703 "delaying=%s, load average=%d >= %d", \
704 cmd, CurrentLA, DelayLA); \
705 log_delay = dnow + MIN_DELAY_LOG; \
708 sm_setproctitle(true, e, "%s %s: %.80s", \
709 qid_printname(e), CurSmtpClient, inp); \
713 ** Determine the correct protocol keyword to use in the
714 ** Received: header, following RFC 3848.
718 # define tls_active false
721 # define auth_active (authenticating == SASL_IS_AUTH)
723 # define auth_active false
725 #define GET_PROTOCOL() \
727 ? (tls_active ? "ESMTPSA" : "ESMTPA") \
728 : (tls_active ? "ESMTPS" : "ESMTP"))
730 static bool SevenBitInput_Saved; /* saved version of SevenBitInput */
733 smtp(nullserver, d_flags, e)
734 char *volatile nullserver;
736 register ENVELOPE *volatile e;
738 register char *volatile p;
739 register struct cmd *volatile c = NULL;
741 auto ADDRESS *vrfyqueue;
743 volatile bool gothello; /* helo command received */
744 bool vrfy; /* set if this is a vrfy command */
745 char *volatile protocol; /* sending protocol */
746 char *volatile sendinghost; /* sending hostname */
747 char *volatile peerhostname; /* name of SMTP peer or "localhost" */
750 volatile unsigned int n_badcmds = 0; /* count of bad commands */
751 volatile unsigned int n_badrcpts = 0; /* number of rejected RCPT */
752 volatile unsigned int n_verifies = 0; /* count of VRFY/EXPN */
753 volatile unsigned int n_etrn = 0; /* count of ETRN */
754 volatile unsigned int n_noop = 0; /* count of NOOP/VERB/etc */
755 volatile unsigned int n_helo = 0; /* count of HELO/EHLO */
758 volatile bool tempfail = false;
759 volatile time_t wt; /* timeout after too many commands */
760 volatile time_t previous; /* time after checksmtpattack() */
761 volatile bool lognullconnection = true;
765 char *greetcode = "220";
766 const char *greetmsg = "not accepting messages";
767 char *hostname; /* my hostname ($j) */
769 char *args[MAXSMTPARGS];
770 char inp[MAXINPLINE];
771 #if MAXINPLINE < MAXLINE
772 ERROR _MAXINPLINE must NOT be less than _MAXLINE: MAXINPLINE < MAXLINE
773 #endif /* MAXINPLINE < MAXLINE */
774 char cmdbuf[MAXLINE];
777 volatile bool sasl_ok;
778 volatile unsigned int n_auth = 0; /* count of AUTH commands */
781 volatile int authenticating;
785 char *auth_id = NULL;
788 char localip[60], remoteip[60];
789 # else /* SASL >= 20000 */
792 sasl_external_properties_t ext_ssf;
793 struct sockaddr_in saddr_l;
794 struct sockaddr_in saddr_r;
795 # endif /* SASL >= 20000 */
796 sasl_security_properties_t ssp;
798 unsigned int inlen, out2len;
800 char *volatile auth_type;
802 volatile unsigned int n_mechs;
809 volatile bool tls_active = false;
810 volatile bool smtps = bitnset(D_SMTPS, d_flags);
814 #endif /* STARTTLS */
815 volatile unsigned int features;
819 # endif /* _FFR_NO_PIPE */
820 #endif /* PIPELINING */
821 volatile time_t log_delay = (time_t) 0;
823 volatile bool milter_cmd_done, milter_cmd_safe;
824 volatile bool milter_rcpt_added, milter_cmd_fail;
826 # define p_addr_st &addr_st
828 # define p_addr_st NULL
831 #if _FFR_BADRCPT_SHUTDOWN
833 #endif /* _FFR_BADRCPT_SHUTDOWN */
835 SevenBitInput_Saved = SevenBitInput;
838 smtp.sm_milterize = (nullserver == NULL);
839 smtp.sm_milterlist = false;
843 /* setup I/O fd correctly for the SMTP server */
847 if (sm_debug_active(&DebugLeakSmtp, 1))
850 sm_dprintf("smtp() heap group #%d\n", sm_heap_group());
852 #endif /* SM_HEAP_CHECK */
854 /* XXX the rpool should be set when e is initialized in main() */
855 e->e_rpool = sm_rpool_new_x(NULL);
856 e->e_macro.mac_rpool = e->e_rpool;
860 peerhostname = RealHostName;
861 if (peerhostname == NULL)
862 peerhostname = "localhost";
863 CurHostName = peerhostname;
864 CurSmtpClient = macvalue('_', e);
865 if (CurSmtpClient == NULL)
866 CurSmtpClient = CurHostName;
868 /* check_relay may have set discard bit, save for later */
869 smtp.sm_discard = bitset(EF_DISCARD, e->e_flags);
872 /* auto-flush output when reading input */
873 (void) sm_io_autoflush(InChannel, OutChannel);
874 #endif /* PIPELINING */
876 sm_setproctitle(true, e, "server %s startup", CurSmtpClient);
878 /* Set default features for server. */
879 features = ((bitset(PRIV_NOETRN, PrivacyFlags) ||
880 bitnset(D_NOETRN, d_flags)) ? SRV_NONE : SRV_OFFER_ETRN)
881 | (bitnset(D_AUTHREQ, d_flags) ? SRV_REQ_AUTH : SRV_NONE)
882 | (bitset(PRIV_NOEXPN, PrivacyFlags) ? SRV_NONE
884 | (bitset(PRIV_NOVERB, PrivacyFlags)
885 ? SRV_NONE : SRV_OFFER_VERB)))
886 | ((bitset(PRIV_NORECEIPTS, PrivacyFlags) || !SendMIMEErrors)
887 ? SRV_NONE : SRV_OFFER_DSN)
889 | (bitnset(D_NOAUTH, d_flags) ? SRV_NONE : SRV_OFFER_AUTH)
890 | (bitset(SASL_SEC_NOPLAINTEXT, SASLOpts) ? SRV_REQ_SEC
895 #endif /* PIPELINING */
897 | (bitnset(D_NOTLS, d_flags) ? SRV_NONE : SRV_OFFER_TLS)
898 | (bitset(TLS_I_NO_VRFY, TLS_Srv_Opts) ? SRV_NONE
900 #endif /* STARTTLS */
902 if (nullserver == NULL)
904 features = srvfeatures(e, CurSmtpClient, features);
905 if (bitset(SRV_TMP_FAIL, features))
908 sm_syslog(LOG_ERR, NOQID,
909 "ERROR: srv_features=tempfail, relay=%.100s, access temporarily disabled",
911 nullserver = "450 4.3.0 Please try again later.";
917 if (bitset(SRV_NO_PIPE, features))
919 /* for consistency */
920 features &= ~SRV_OFFER_PIPE;
922 # endif /* _FFR_NO_PIPE */
923 #endif /* PIPELINING */
925 if (bitset(SRV_REQ_SEC, features))
926 SASLOpts |= SASL_SEC_NOPLAINTEXT;
928 SASLOpts &= ~SASL_SEC_NOPLAINTEXT;
932 else if (strncmp(nullserver, "421 ", 4) == 0)
938 e->e_features = features;
939 hostname = macvalue('j', e);
941 if (AuthRealm == NULL)
942 AuthRealm = hostname;
943 sasl_ok = bitset(SRV_OFFER_AUTH, features);
945 authenticating = SASL_NOT_AUTH;
947 /* SASL server new connection */
951 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, NULL,
954 /* use empty realm: only works in SASL > 1.5.5 */
955 result = sasl_server_new("smtp", AuthRealm, "", NULL, 0, &conn);
956 # else /* SASL >= 20000 */
957 /* use no realm -> realm is set to hostname by SASL lib */
958 result = sasl_server_new("smtp", AuthRealm, NULL, NULL, 0,
960 # endif /* SASL >= 20000 */
961 sasl_ok = result == SASL_OK;
965 sm_syslog(LOG_WARNING, NOQID,
966 "AUTH error: sasl_server_new failed=%d",
973 ** SASL set properties for sasl
974 ** set local/remote IP
975 ** XXX Cyrus SASL v1 only supports IPv4
977 ** XXX where exactly are these used/required?
982 localip[0] = remoteip[0] = '\0';
983 # if NETINET || NETINET6
984 in = macvalue(macid("{daemon_family}"), e);
987 strcmp(in, "inet6") == 0 ||
988 # endif /* NETINET6 */
989 strcmp(in, "inet") == 0))
991 SOCKADDR_LEN_T addrsize;
995 addrsize = sizeof(saddr_r);
996 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
998 (struct sockaddr *) &saddr_r,
1001 if (iptostring(&saddr_r, addrsize,
1002 remoteip, sizeof(remoteip)))
1004 sasl_setprop(conn, SASL_IPREMOTEPORT,
1007 addrsize = sizeof(saddr_l);
1008 if (getsockname(sm_io_getinfo(InChannel,
1011 (struct sockaddr *) &saddr_l,
1014 if (iptostring(&saddr_l, addrsize,
1025 # endif /* NETINET || NETINET6 */
1026 # else /* SASL >= 20000 */
1028 in = macvalue(macid("{daemon_family}"), e);
1029 if (in != NULL && strcmp(in, "inet") == 0)
1031 SOCKADDR_LEN_T addrsize;
1033 addrsize = sizeof(struct sockaddr_in);
1034 if (getpeername(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
1036 (struct sockaddr *)&saddr_r,
1039 sasl_setprop(conn, SASL_IP_REMOTE, &saddr_r);
1040 addrsize = sizeof(struct sockaddr_in);
1041 if (getsockname(sm_io_getinfo(InChannel,
1044 (struct sockaddr *)&saddr_l,
1046 sasl_setprop(conn, SASL_IP_LOCAL,
1050 # endif /* NETINET */
1051 # endif /* SASL >= 20000 */
1057 macdefine(&BlankEnvelope.e_macro, A_PERM,
1058 macid("{auth_author}"), NULL);
1061 /* set properties */
1062 (void) memset(&ssp, '\0', sizeof(ssp));
1064 /* XXX should these be options settable via .cf ? */
1065 /* ssp.min_ssf = 0; is default due to memset() */
1066 ssp.max_ssf = MaxSLBits;
1067 ssp.maxbufsize = MAXOUTLEN;
1068 ssp.security_flags = SASLOpts & SASL_SEC_MASK;
1069 sasl_ok = sasl_setprop(conn, SASL_SEC_PROPS, &ssp) == SASL_OK;
1074 ** external security strength factor;
1075 ** currently we have none so zero
1081 sasl_ok = ((sasl_setprop(conn, SASL_SSF_EXTERNAL,
1082 &ext_ssf) == SASL_OK) &&
1083 (sasl_setprop(conn, SASL_AUTH_EXTERNAL,
1084 auth_id) == SASL_OK));
1085 # else /* SASL >= 20000 */
1087 ext_ssf.auth_id = NULL;
1088 sasl_ok = sasl_setprop(conn, SASL_SSF_EXTERNAL,
1089 &ext_ssf) == SASL_OK;
1090 # endif /* SASL >= 20000 */
1093 n_mechs = saslmechs(conn, &mechlist);
1097 (void) set_tls_rd_tmo(TimeOuts.to_nextcommand);
1100 if (smtp.sm_milterize)
1104 /* initialize mail filter connection */
1105 smtp.sm_milterlist = milter_init(e, &state, &smtp.sm_milters);
1109 if (MilterLogLevel > 3)
1110 sm_syslog(LOG_INFO, e->e_id,
1111 "Milter: initialization failed, rejecting commands");
1113 nullserver = "Command rejected";
1114 smtp.sm_milterize = false;
1117 case SMFIR_TEMPFAIL:
1118 if (MilterLogLevel > 3)
1119 sm_syslog(LOG_INFO, e->e_id,
1120 "Milter: initialization failed, temp failing commands");
1122 smtp.sm_milterize = false;
1125 case SMFIR_SHUTDOWN:
1126 if (MilterLogLevel > 3)
1127 sm_syslog(LOG_INFO, e->e_id,
1128 "Milter: initialization failed, closing connection");
1130 smtp.sm_milterize = false;
1131 message("421 4.7.0 %s closing connection",
1134 /* arrange to ignore send list */
1135 e->e_sendqueue = NULL;
1136 lognullconnection = false;
1141 if (smtp.sm_milterlist && smtp.sm_milterize &&
1142 !bitset(EF_DISCARD, e->e_flags))
1147 q = macvalue(macid("{client_name}"), e);
1148 SM_ASSERT(q != NULL || OpMode == MD_SMTP);
1151 response = milter_connect(q, RealHostAddr, e, &state);
1154 #if _FFR_MILTER_CONNECT_REPLYCODE
1155 case SMFIR_REPLYCODE:
1156 if (*response == '5')
1158 if (MilterLogLevel > 3)
1159 sm_syslog(LOG_INFO, e->e_id,
1160 "Milter: connect: host=%s, addr=%s, reject=%s",
1162 anynet_ntoa(&RealHostAddr),
1164 greetcode = "554"; /* Required by 2821 3.1 */
1165 nullserver = newstr(response);
1166 if (strlen(nullserver) > 4)
1170 greetmsg = nullserver + 4;
1172 /* skip over enhanced status code */
1173 skip = isenhsc(greetmsg, ' ');
1175 greetmsg += skip + 1;
1177 smtp.sm_milterize = false;
1180 else if (strncmp(response, "421 ", 4) == 0)
1183 const char *msg = response + 4;
1185 if (MilterLogLevel > 3)
1186 sm_syslog(LOG_INFO, e->e_id,
1187 "Milter: connect: host=%s, addr=%s, shutdown=%s",
1189 anynet_ntoa(&RealHostAddr),
1192 smtp.sm_milterize = false;
1194 /* skip over enhanced status code */
1195 skip = isenhsc(msg, ' ');
1198 message("421 %s %s", MyHostName, msg);
1200 /* arrange to ignore send list */
1201 e->e_sendqueue = NULL;
1206 if (MilterLogLevel > 3)
1207 sm_syslog(LOG_INFO, e->e_id,
1208 "Milter: connect: host=%s, addr=%s, temp failing commands=%s",
1210 anynet_ntoa(&RealHostAddr),
1212 /*tempfail = true;*/
1213 smtp.sm_milterize = false;
1214 nullserver = newstr(response);
1218 #else /* _FFR_MILTER_CONNECT_REPLYCODE */
1219 case SMFIR_REPLYCODE: /* REPLYCODE shouldn't happen */
1220 #endif /* _FFR_MILTER_CONNECT_REPLYCODE */
1222 if (MilterLogLevel > 3)
1223 sm_syslog(LOG_INFO, e->e_id,
1224 "Milter: connect: host=%s, addr=%s, rejecting commands",
1226 anynet_ntoa(&RealHostAddr));
1228 nullserver = "Command rejected";
1229 smtp.sm_milterize = false;
1232 case SMFIR_TEMPFAIL:
1233 if (MilterLogLevel > 3)
1234 sm_syslog(LOG_INFO, e->e_id,
1235 "Milter: connect: host=%s, addr=%s, temp failing commands",
1237 anynet_ntoa(&RealHostAddr));
1239 smtp.sm_milterize = false;
1242 case SMFIR_SHUTDOWN:
1243 if (MilterLogLevel > 3)
1244 sm_syslog(LOG_INFO, e->e_id,
1245 "Milter: connect: host=%s, addr=%s, shutdown",
1247 anynet_ntoa(&RealHostAddr));
1249 smtp.sm_milterize = false;
1250 message("421 4.7.0 %s closing connection",
1253 /* arrange to ignore send list */
1254 e->e_sendqueue = NULL;
1257 if (response != NULL)
1263 ** Broken proxies and SMTP slammers
1264 ** push data without waiting, catch them
1270 #endif /* STARTTLS */
1271 *greetcode == '2' && nullserver == NULL)
1275 char pvpbuf[PSBUFSIZE];
1277 /* Ask the rulesets how long to pause */
1279 r = rscap("greet_pause", peerhostname,
1280 anynet_ntoa(&RealHostAddr), e,
1281 &pvp, pvpbuf, sizeof(pvpbuf));
1282 if (r == EX_OK && pvp != NULL && pvp[0] != NULL &&
1283 (pvp[0][0] & 0377) == CANONNET && pvp[1] != NULL)
1285 msecs = strtol(pvp[1], NULL, 10);
1292 struct timeval timeout;
1293 struct timeval bp, ep, tp; /* {begin,end,total}pause */
1296 /* pause for a moment */
1297 timeout.tv_sec = msecs / 1000;
1298 timeout.tv_usec = (msecs % 1000) * 1000;
1300 /* Obey RFC 2821: 4.3.5.2: 220 timeout of 5 minutes */
1301 if (timeout.tv_sec >= 300)
1303 timeout.tv_sec = 300;
1304 timeout.tv_usec = 0;
1307 /* check if data is on the socket during the pause */
1308 fd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
1310 SM_FD_SET(fd, &readfds);
1311 gettimeofday(&bp, NULL);
1312 if (select(fd + 1, FDSET_CAST &readfds,
1313 NULL, NULL, &timeout) > 0 &&
1314 FD_ISSET(fd, &readfds) &&
1315 (eoftest = sm_io_getc(InChannel, SM_TIME_DEFAULT))
1318 sm_io_ungetc(InChannel, SM_TIME_DEFAULT,
1320 gettimeofday(&ep, NULL);
1321 timersub(&ep, &bp, &tp);
1323 nullserver = "Command rejected";
1324 sm_syslog(LOG_INFO, e->e_id,
1325 "rejecting commands from %s [%s] due to pre-greeting traffic after %d seconds",
1327 anynet_ntoa(&RealHostAddr),
1329 (tp.tv_usec >= 500000 ? 1 : 0)
1336 /* If this an smtps connection, start TLS now */
1345 #endif /* STARTTLS */
1347 /* output the first line, inserting "ESMTP" as second word */
1348 if (*greetcode == '5')
1349 (void) sm_snprintf(inp, sizeof(inp), "%s %s", hostname,
1352 expand(SmtpGreeting, inp, sizeof(inp), e);
1354 p = strchr(inp, '\n');
1357 id = strchr(inp, ' ');
1359 id = &inp[strlen(inp)];
1361 (void) sm_snprintf(cmdbuf, sizeof(cmdbuf),
1362 "%s %%.*s ESMTP%%s", greetcode);
1364 (void) sm_snprintf(cmdbuf, sizeof(cmdbuf),
1365 "%s-%%.*s ESMTP%%s", greetcode);
1366 message(cmdbuf, (int) (id - inp), inp, id);
1368 /* output remaining lines */
1369 while ((id = p) != NULL && (p = strchr(id, '\n')) != NULL)
1372 if (isascii(*id) && isspace(*id))
1374 (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, "-%s");
1375 message(cmdbuf, id);
1379 if (isascii(*id) && isspace(*id))
1381 (void) sm_strlcpyn(cmdbuf, sizeof(cmdbuf), 2, greetcode, " %s");
1382 message(cmdbuf, id);
1386 sendinghost = macvalue('s', e);
1388 /* If quarantining by a connect/ehlo action, save between messages */
1389 if (e->e_quarmsg == NULL)
1390 smtp.sm_quarmsg = NULL;
1392 smtp.sm_quarmsg = newstr(e->e_quarmsg);
1394 /* sendinghost's storage must outlive the current envelope */
1395 if (sendinghost != NULL)
1396 sendinghost = sm_strdup_x(sendinghost);
1399 smtp.sm_gotmail = false;
1408 OnlyOneError = true;
1409 e->e_flags &= ~(EF_VRFYONLY|EF_GLOBALERRS);
1411 milter_cmd_fail = false;
1414 /* setup for the read */
1418 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
1420 /* read the input line */
1421 SmtpPhase = "server cmd read";
1422 sm_setproctitle(true, e, "server %s cmd read", CurSmtpClient);
1425 if (sm_io_error(OutChannel) ||
1426 (p = sfgets(inp, sizeof(inp), InChannel,
1427 TimeOuts.to_nextcommand, SmtpPhase)) == NULL)
1431 d = macvalue(macid("{daemon_name}"), e);
1434 /* end of file, just die */
1438 /* close out milter filters */
1442 message("421 4.4.1 %s Lost input channel from %s",
1443 MyHostName, CurSmtpClient);
1444 if (LogLevel > (smtp.sm_gotmail ? 1 : 19))
1445 sm_syslog(LOG_NOTICE, e->e_id,
1446 "lost input channel from %s to %s after %s",
1448 (c == NULL || c->cmd_name == NULL) ? "startup" : c->cmd_name);
1450 ** If have not accepted mail (DATA), do not bounce
1451 ** bad addresses back to sender.
1454 if (bitset(EF_CLRQUEUE, e->e_flags))
1455 e->e_sendqueue = NULL;
1459 /* also used by "proxy" check below */
1460 inplen = strlen(inp);
1463 ** SMTP AUTH requires accepting any length,
1464 ** at least for challenge/response. However, not imposing
1465 ** a limit is a bad idea (denial of service).
1468 if (authenticating != SASL_PROC_AUTH
1469 && sm_strncasecmp(inp, "AUTH ", 5) != 0
1470 && inplen > MAXLINE)
1472 message("421 4.7.0 %s Command too long, possible attack %s",
1473 MyHostName, CurSmtpClient);
1474 sm_syslog(LOG_INFO, e->e_id,
1475 "%s: SMTP violation, input too long: %lu",
1476 CurSmtpClient, (unsigned long) inplen);
1486 static char *http_cmds[] = { "GET", "POST",
1487 "CONNECT", "USER", NULL };
1489 for (idx = 0; (http_cmd = http_cmds[idx]) != NULL;
1492 cmdlen = strlen(http_cmd);
1493 if (cmdlen < inplen &&
1494 sm_strncasecmp(inp, http_cmd, cmdlen) == 0 &&
1495 isascii(inp[cmdlen]) && isspace(inp[cmdlen]))
1497 /* Open proxy, drop it */
1498 message("421 4.7.0 %s Rejecting open proxy %s",
1499 MyHostName, CurSmtpClient);
1500 sm_syslog(LOG_INFO, e->e_id,
1501 "%s: probable open proxy: command=%.40s",
1502 CurSmtpClient, inp);
1509 /* clean up end of line */
1515 ** if there is more input and pipelining is disabled:
1516 ** delay ... (and maybe discard the input?)
1517 ** XXX this doesn't really work, at least in tests using
1518 ** telnet SM_IO_IS_READABLE only returns 1 if there were
1519 ** more than 2 input lines available.
1522 if (bitset(SRV_NO_PIPE, features) &&
1523 sm_io_getinfo(InChannel, SM_IO_IS_READABLE, NULL) > 0)
1526 sm_syslog(LOG_INFO, NOQID,
1527 "unauthorized PIPELINING, sleeping, relay=%.100s",
1532 # endif /* _FFR_NO_PIPE */
1533 #endif /* PIPELINING */
1536 if (authenticating == SASL_PROC_AUTH)
1541 authenticating = SASL_NOT_AUTH;
1542 message("501 5.5.2 missing input");
1547 if (*inp == '*' && *(inp + 1) == '\0')
1549 authenticating = SASL_NOT_AUTH;
1552 message("501 5.0.0 AUTH aborted");
1557 /* could this be shorter? XXX */
1559 in = xalloc(strlen(inp) + 1);
1560 result = sasl_decode64(inp, strlen(inp), in,
1561 strlen(inp), &inlen);
1562 # else /* SASL >= 20000 */
1563 out = xalloc(strlen(inp));
1564 result = sasl_decode64(inp, strlen(inp), out, &outlen);
1565 # endif /* SASL >= 20000 */
1566 if (result != SASL_OK)
1568 authenticating = SASL_NOT_AUTH;
1571 message("501 5.5.4 cannot decode AUTH parameter %s",
1575 # endif /* SASL >= 20000 */
1581 result = sasl_server_step(conn, in, inlen,
1584 # else /* SASL >= 20000 */
1585 result = sasl_server_step(conn, out, outlen,
1586 &out, &outlen, &errstr);
1587 # endif /* SASL >= 20000 */
1589 /* get an OK if we're done */
1590 if (result == SASL_OK)
1593 message("235 2.0.0 OK Authenticated");
1594 authenticating = SASL_IS_AUTH;
1595 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1596 macid("{auth_type}"), auth_type);
1599 user = macvalue(macid("{auth_authen}"), e);
1601 /* get security strength (features) */
1602 result = sasl_getprop(conn, SASL_SSF,
1603 (const void **) &ssf);
1604 # else /* SASL >= 20000 */
1605 result = sasl_getprop(conn, SASL_USERNAME,
1607 if (result != SASL_OK)
1610 macdefine(&BlankEnvelope.e_macro,
1612 macid("{auth_authen}"), NULL);
1616 macdefine(&BlankEnvelope.e_macro,
1618 macid("{auth_authen}"),
1619 xtextify(user, "<>\")"));
1624 sasl_getprop(conn, SASL_REALM, (void **) &data);
1627 /* get security strength (features) */
1628 result = sasl_getprop(conn, SASL_SSF,
1630 # endif /* SASL >= 20000 */
1631 if (result != SASL_OK)
1633 macdefine(&BlankEnvelope.e_macro,
1635 macid("{auth_ssf}"), "0");
1642 (void) sm_snprintf(pbuf, sizeof(pbuf),
1644 macdefine(&BlankEnvelope.e_macro,
1646 macid("{auth_ssf}"), pbuf);
1648 sm_dprintf("AUTH auth_ssf: %u\n",
1652 protocol = GET_PROTOCOL();
1655 ** Only switch to encrypted connection
1656 ** if a security layer has been negotiated
1659 if (ssf != NULL && *ssf > 0)
1664 ** Convert I/O layer to use SASL.
1665 ** If the call fails, the connection
1669 tmo = TimeOuts.to_datablock * 1000;
1670 if (sfdcsasl(&InChannel, &OutChannel,
1673 /* restart dialogue */
1676 (void) sm_io_autoflush(InChannel,
1678 # endif /* PIPELINING */
1681 syserr("503 5.3.3 SASL TLS failed");
1684 /* NULL pointer ok since it's our function */
1686 sm_syslog(LOG_INFO, NOQID,
1687 "AUTH=server, relay=%s, authid=%.128s, mech=%.16s, bits=%d",
1689 shortenstring(user, 128),
1692 else if (result == SASL_CONTINUE)
1694 len = ENC64LEN(outlen);
1696 result = sasl_encode64(out, outlen, out2, len,
1698 if (result != SASL_OK)
1700 /* correct code? XXX */
1701 /* 454 Temp. authentication failure */
1702 message("454 4.5.4 Internal error: unable to encode64");
1704 sm_syslog(LOG_WARNING, e->e_id,
1705 "AUTH encode64 error [%d for \"%s\"], relay=%.100s",
1709 authenticating = SASL_NOT_AUTH;
1713 message("334 %s", out2);
1715 sm_dprintf("AUTH continue: msg='%s' len=%u\n",
1720 # endif /* SASL >= 20000 */
1724 /* not SASL_OK or SASL_CONT */
1725 message("535 5.7.0 authentication failed");
1727 sm_syslog(LOG_WARNING, e->e_id,
1728 "AUTH failure (%s): %s (%d) %s, relay=%.100s",
1730 sasl_errstring(result, NULL,
1734 sasl_errdetail(conn),
1735 # else /* SASL >= 20000 */
1736 errstr == NULL ? "" : errstr,
1737 # endif /* SASL >= 20000 */
1740 authenticating = SASL_NOT_AUTH;
1745 /* don't want to do any of this if authenticating */
1748 /* echo command to transcript */
1749 if (e->e_xfp != NULL)
1750 (void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
1754 sm_syslog(LOG_INFO, e->e_id, "<-- %s", inp);
1756 /* break off command */
1757 for (p = inp; isascii(*p) && isspace(*p); p++)
1760 while (*p != '\0' &&
1761 !(isascii(*p) && isspace(*p)) &&
1762 cmd < &cmdbuf[sizeof(cmdbuf) - 2])
1766 /* throw away leading whitespace */
1769 /* decode command */
1770 for (c = CmdTab; c->cmd_name != NULL; c++)
1772 if (sm_strcasecmp(c->cmd_name, cmdbuf) == 0)
1779 /* check whether a "non-null" command has been used */
1780 switch (c->cmd_code)
1784 /* avoid information leak; take first two words? */
1793 lognullconnection = false;
1800 if (e->e_id == NULL)
1801 sm_setproctitle(true, e, "%s: %.80s",
1804 sm_setproctitle(true, e, "%s %s: %.80s",
1811 ** If we are running as a null server, return 550
1812 ** to almost everything.
1815 if (nullserver != NULL || bitnset(D_ETRNONLY, d_flags))
1817 switch (c->cmd_code)
1825 /* process normally */
1829 if (bitnset(D_ETRNONLY, d_flags) &&
1836 #if MAXBADCOMMANDS > 0
1837 /* theoretically this could overflow */
1838 if (nullserver != NULL &&
1839 ++n_badcmds > MAXBADCOMMANDS)
1841 message("421 4.7.0 %s Too many bad commands; closing connection",
1844 /* arrange to ignore send list */
1845 e->e_sendqueue = NULL;
1848 #endif /* MAXBADCOMMANDS > 0 */
1849 if (nullserver != NULL)
1851 if (ISSMTPREPLY(nullserver))
1854 usrerr("550 5.0.0 %s",
1858 usrerr("452 4.4.5 Insufficient disk space; try again later");
1863 switch (c->cmd_code)
1866 case CMDAUTH: /* sasl */
1868 if (!sasl_ok || n_mechs <= 0)
1870 message("503 5.3.3 AUTH not available");
1873 if (authenticating == SASL_IS_AUTH)
1875 message("503 5.5.0 Already Authenticated");
1878 if (smtp.sm_gotmail)
1880 message("503 5.5.0 AUTH not permitted during a mail transaction");
1886 sm_syslog(LOG_INFO, e->e_id,
1887 "SMTP AUTH command (%.100s) from %s tempfailed (due to previous checks)",
1889 usrerr("454 4.3.0 Please try again later");
1895 /* crude way to avoid crack attempts */
1896 STOP_IF_ATTACK(checksmtpattack(&n_auth, n_mechs + 1,
1899 /* make sure mechanism (p) is a valid string */
1900 for (q = p; *q != '\0' && isascii(*q); q++)
1905 while (*++q != '\0' &&
1906 isascii(*q) && isspace(*q))
1909 ismore = (*q != '\0');
1916 message("501 5.5.2 AUTH mechanism must be specified");
1920 /* check whether mechanism is available */
1921 if (iteminlist(p, mechlist, " ") == NULL)
1923 message("504 5.3.3 AUTH mechanism %.32s not available",
1930 ** Unlike a zero-length client answer to a
1931 ** 334 reply, a zero- length initial response
1932 ** is sent as a single equals sign ("=").
1935 if (ismore && *q == '=' && *(q + 1) == '\0')
1937 /* will be free()d, don't use in=""; */
1944 /* could this be shorter? XXX */
1946 in = xalloc(strlen(q) + 1);
1947 result = sasl_decode64(q, strlen(q), in,
1949 # else /* SASL >= 20000 */
1950 in = sm_rpool_malloc(e->e_rpool, strlen(q));
1951 result = sasl_decode64(q, strlen(q), in,
1953 # endif /* SASL >= 20000 */
1954 if (result != SASL_OK)
1956 message("501 5.5.4 cannot BASE64 decode '%s'",
1959 sm_syslog(LOG_WARNING, e->e_id,
1960 "AUTH decode64 error [%d for \"%s\"], relay=%.100s",
1964 authenticating = SASL_NOT_AUTH;
1967 # endif /* SASL >= 20000 */
1979 /* see if that auth type exists */
1981 result = sasl_server_start(conn, p, in, inlen,
1985 # else /* SASL >= 20000 */
1986 result = sasl_server_start(conn, p, in, inlen,
1987 &out, &outlen, &errstr);
1988 # endif /* SASL >= 20000 */
1990 if (result != SASL_OK && result != SASL_CONTINUE)
1992 message("535 5.7.0 authentication failed");
1994 sm_syslog(LOG_ERR, e->e_id,
1995 "AUTH failure (%s): %s (%d) %s, relay=%.100s",
1997 sasl_errstring(result, NULL,
2001 sasl_errdetail(conn),
2002 # else /* SASL >= 20000 */
2004 # endif /* SASL >= 20000 */
2009 auth_type = newstr(p);
2011 if (result == SASL_OK)
2013 /* ugly, but same code */
2015 /* authenticated by the initial response */
2018 /* len is at least 2 */
2019 len = ENC64LEN(outlen);
2021 result = sasl_encode64(out, outlen, out2, len,
2024 if (result != SASL_OK)
2026 message("454 4.5.4 Temporary authentication failure");
2028 sm_syslog(LOG_WARNING, e->e_id,
2029 "AUTH encode64 error [%d for \"%s\"]",
2033 authenticating = SASL_NOT_AUTH;
2038 message("334 %s", out2);
2039 authenticating = SASL_PROC_AUTH;
2043 # endif /* SASL >= 20000 */
2048 case CMDSTLS: /* starttls */
2049 DELAY_CONN("STARTTLS");
2052 message("501 5.5.2 Syntax error (no parameters allowed)");
2055 if (!bitset(SRV_OFFER_TLS, features))
2057 message("503 5.5.0 TLS not available");
2062 message("454 4.3.3 TLS not available after start");
2065 if (smtp.sm_gotmail)
2067 message("503 5.5.0 TLS not permitted during a mail transaction");
2073 sm_syslog(LOG_INFO, e->e_id,
2074 "SMTP STARTTLS command (%.100s) from %s tempfailed (due to previous checks)",
2076 usrerr("454 4.7.0 Please try again later");
2080 # if USE_OPENSSL_ENGINE
2081 if (!SSLEngineInitialized)
2083 if (!SSL_set_engine(NULL))
2085 sm_syslog(LOG_ERR, NOQID,
2086 "STARTTLS=server, SSL_set_engine=failed");
2088 message("454 4.3.3 TLS not available right now");
2092 SSLEngineInitialized = true;
2094 # endif /* USE_OPENSSL_ENGINE */
2097 ** XXX do we need a temp key ?
2099 # else /* TLS_NO_RSA */
2100 # endif /* TLS_NO_RSA */
2102 # if TLS_VRFY_PER_CTX
2104 ** Note: this sets the verification globally
2106 ** it's ok since it applies only to one transaction
2109 TLS_VERIFY_CLIENT();
2110 # endif /* TLS_VRFY_PER_CTX */
2112 if (srv_ssl != NULL)
2114 else if ((srv_ssl = SSL_new(srv_ctx)) == NULL)
2116 message("454 4.3.3 TLS not available: error generating SSL handle");
2118 tlslogerr(LOG_WARNING, "server");
2122 if (get_tls_se_options(e, srv_ssl, true) != 0)
2124 message("454 4.3.3 TLS not available: error setting options");
2130 # if !TLS_VRFY_PER_CTX
2132 ** this could be used if it were possible to set
2133 ** verification per SSL (connection)
2134 ** not just per SSL_CTX (global)
2137 TLS_VERIFY_CLIENT();
2138 # endif /* !TLS_VRFY_PER_CTX */
2140 rfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
2141 wfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
2143 if (rfd < 0 || wfd < 0 ||
2144 SSL_set_rfd(srv_ssl, rfd) <= 0 ||
2145 SSL_set_wfd(srv_ssl, wfd) <= 0)
2147 message("454 4.3.3 TLS not available: error set fd");
2153 message("220 2.0.0 Ready to start TLS");
2155 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
2156 # endif /* PIPELINING */
2158 SSL_set_accept_state(srv_ssl);
2160 tlsstart = curtime();
2162 if ((r = SSL_accept(srv_ssl)) <= 0)
2165 int save_errno = errno;
2167 ssl_err = SSL_get_error(srv_ssl, r);
2168 i = tls_retry(srv_ssl, rfd, wfd, tlsstart,
2169 TimeOuts.to_starttls, ssl_err,
2179 l = ERR_peek_error();
2180 sr = ERR_reason_error_string(l);
2181 sm_syslog(LOG_WARNING, NOQID,
2182 "STARTTLS=server, error: accept failed=%d, reason=%s, SSL_error=%d, errno=%d, retry=%d, relay=%.100s",
2183 r, sr == NULL ? "unknown"
2185 ssl_err, save_errno, i,
2188 tlslogerr(LOG_WARNING, "server");
2195 ** according to the next draft of
2196 ** RFC 2487 the connection should be dropped
2199 /* arrange to ignore any current send list */
2200 e->e_sendqueue = NULL;
2204 /* ignore return code for now, it's in {verify} */
2205 (void) tls_get_info(srv_ssl, true,
2207 &BlankEnvelope.e_macro,
2208 bitset(SRV_VRFY_CLT, features));
2211 ** call Stls_client to find out whether
2212 ** to accept the connection from the client
2215 saveQuickAbort = QuickAbort;
2216 saveSuprErrs = SuprErrs;
2219 if (rscheck("tls_client",
2220 macvalue(macid("{verify}"), e),
2222 RSF_RMCOMM|RSF_COUNT,
2223 5, NULL, NOQID, NULL, NULL) != EX_OK ||
2226 extern char MsgBuf[];
2228 if (MsgBuf[0] != '\0' && ISSMTPREPLY(MsgBuf))
2229 nullserver = newstr(MsgBuf);
2231 nullserver = "503 5.7.0 Authentication required.";
2233 QuickAbort = saveQuickAbort;
2234 SuprErrs = saveSuprErrs;
2236 tls_ok_srv = false; /* don't offer STARTTLS again */
2245 s = macvalue(macid("{cipher_bits}"), e);
2246 v = macvalue(macid("{verify}"), e);
2247 c = macvalue(macid("{cert_subject}"), e);
2248 verified = (v != NULL && strcmp(v, "OK") == 0);
2249 if (s != NULL && (cipher_bits = atoi(s)) > 0)
2252 ext_ssf = cipher_bits;
2253 auth_id = verified ? c : NULL;
2254 sasl_ok = ((sasl_setprop(conn,
2256 &ext_ssf) == SASL_OK) &&
2259 auth_id) == SASL_OK));
2260 # else /* SASL >= 20000 */
2261 ext_ssf.ssf = cipher_bits;
2262 ext_ssf.auth_id = verified ? c : NULL;
2263 sasl_ok = sasl_setprop(conn,
2265 &ext_ssf) == SASL_OK;
2266 # endif /* SASL >= 20000 */
2269 n_mechs = saslmechs(conn,
2275 /* switch to secure connection */
2276 if (sfdctls(&InChannel, &OutChannel, srv_ssl) == 0)
2280 (void) sm_io_autoflush(InChannel, OutChannel);
2281 # endif /* PIPELINING */
2286 ** XXX this is an internal error
2287 ** how to deal with it?
2288 ** we can't generate an error message
2289 ** since the other side switched to an
2290 ** encrypted layer, but we could not...
2294 nullserver = "454 4.3.3 TLS not available: can't switch to encrypted layer";
2295 syserr("STARTTLS: can't switch to encrypted layer");
2306 #endif /* STARTTLS */
2308 case CMDHELO: /* hello -- introduce yourself */
2309 case CMDEHLO: /* extended hello */
2311 if (c->cmd_code == CMDEHLO)
2313 protocol = GET_PROTOCOL();
2314 SmtpPhase = "server EHLO";
2319 SmtpPhase = "server HELO";
2322 /* avoid denial-of-service */
2323 STOP_IF_ATTACK(checksmtpattack(&n_helo, MAXHELOCOMMANDS,
2324 true, "HELO/EHLO", e));
2327 /* RFC2821 4.1.4 allows duplicate HELO/EHLO */
2328 /* check for duplicate HELO/EHLO per RFC 1651 4.2 */
2331 usrerr("503 %s Duplicate HELO/EHLO",
2337 /* check for valid domain name (re 1123 5.2.5) */
2338 if (*p == '\0' && !AllowBogusHELO)
2340 usrerr("501 %s requires domain address",
2345 /* check for long domain name (hides Received: info) */
2346 if (strlen(p) > MAXNAME)
2348 usrerr("501 Invalid domain name");
2350 sm_syslog(LOG_INFO, CurEnv->e_id,
2351 "invalid domain name (too long) from %s",
2357 for (q = p; *q != '\0'; q++)
2367 /* only complain if strict check */
2368 ok = AllowBogusHELO;
2370 /* allow trailing whitespace */
2371 while (!ok && *++q != '\0' &&
2378 if (strchr("[].-_#:", *q) == NULL)
2382 if (*q == '\0' && ok)
2384 q = "pleased to meet you";
2385 sendinghost = sm_strdup_x(p);
2387 else if (!AllowBogusHELO)
2389 usrerr("501 Invalid domain name");
2391 sm_syslog(LOG_INFO, CurEnv->e_id,
2392 "invalid domain name (%s) from %.100s",
2398 q = "accepting invalid domain name";
2401 if (gothello || smtp.sm_gotmail)
2402 CLEAR_STATE(cmdbuf);
2405 if (smtp.sm_milterlist && smtp.sm_milterize &&
2406 !bitset(EF_DISCARD, e->e_flags))
2411 response = milter_helo(p, e, &state);
2415 if (MilterLogLevel > 3)
2416 sm_syslog(LOG_INFO, e->e_id,
2417 "Milter: helo=%s, reject=Command rejected",
2419 nullserver = "Command rejected";
2420 smtp.sm_milterize = false;
2423 case SMFIR_TEMPFAIL:
2424 if (MilterLogLevel > 3)
2425 sm_syslog(LOG_INFO, e->e_id,
2426 "Milter: helo=%s, reject=%s",
2429 smtp.sm_milterize = false;
2432 case SMFIR_REPLYCODE:
2433 if (MilterLogLevel > 3)
2434 sm_syslog(LOG_INFO, e->e_id,
2435 "Milter: helo=%s, reject=%s",
2437 if (strncmp(response, "421 ", 4) != 0
2438 && strncmp(response, "421-", 4) != 0)
2440 nullserver = newstr(response);
2441 smtp.sm_milterize = false;
2446 case SMFIR_SHUTDOWN:
2447 if (MilterLogLevel > 3 &&
2449 sm_syslog(LOG_INFO, e->e_id,
2450 "Milter: helo=%s, reject=421 4.7.0 %s closing connection",
2453 smtp.sm_milterize = false;
2454 if (response != NULL)
2457 message("421 4.7.0 %s closing connection",
2459 /* arrange to ignore send list */
2460 e->e_sendqueue = NULL;
2461 lognullconnection = false;
2464 if (response != NULL)
2468 ** If quarantining by a connect/ehlo action,
2469 ** save between messages
2472 if (smtp.sm_quarmsg == NULL &&
2473 e->e_quarmsg != NULL)
2474 smtp.sm_quarmsg = newstr(e->e_quarmsg);
2479 /* print HELO response message */
2480 if (c->cmd_code != CMDEHLO)
2482 message("250 %s Hello %s, %s",
2483 MyHostName, CurSmtpClient, q);
2487 message("250-%s Hello %s, %s",
2488 MyHostName, CurSmtpClient, q);
2490 /* offer ENHSC even for nullserver */
2491 if (nullserver != NULL)
2493 message("250 ENHANCEDSTATUSCODES");
2498 ** print EHLO features list
2500 ** Note: If you change this list,
2501 ** remember to update 'helpfile'
2504 message("250-ENHANCEDSTATUSCODES");
2506 if (bitset(SRV_OFFER_PIPE, features))
2507 message("250-PIPELINING");
2508 #endif /* PIPELINING */
2509 if (bitset(SRV_OFFER_EXPN, features))
2511 message("250-EXPN");
2512 if (bitset(SRV_OFFER_VERB, features))
2513 message("250-VERB");
2516 message("250-8BITMIME");
2517 #endif /* MIME8TO7 */
2518 if (MaxMessageSize > 0)
2519 message("250-SIZE %ld", MaxMessageSize);
2521 message("250-SIZE");
2523 if (SendMIMEErrors && bitset(SRV_OFFER_DSN, features))
2526 if (bitset(SRV_OFFER_ETRN, features))
2527 message("250-ETRN");
2529 if (sasl_ok && mechlist != NULL && *mechlist != '\0')
2530 message("250-AUTH %s", mechlist);
2533 if (tls_ok_srv && bitset(SRV_OFFER_TLS, features))
2534 message("250-STARTTLS");
2535 #endif /* STARTTLS */
2536 if (DeliverByMin > 0)
2537 message("250-DELIVERBY %ld",
2538 (long) DeliverByMin);
2539 else if (DeliverByMin == 0)
2540 message("250-DELIVERBY");
2542 /* < 0: no deliver-by */
2544 message("250 HELP");
2547 case CMDMAIL: /* mail -- designate sender */
2548 SmtpPhase = "server MAIL";
2551 /* check for validity of this command */
2552 if (!gothello && bitset(PRIV_NEEDMAILHELO, PrivacyFlags))
2554 usrerr("503 5.0.0 Polite people say HELO first");
2557 if (smtp.sm_gotmail)
2559 usrerr("503 5.5.0 Sender already specified");
2563 if (bitset(SRV_REQ_AUTH, features) &&
2564 authenticating != SASL_IS_AUTH)
2566 usrerr("530 5.7.0 Authentication required");
2571 p = skipword(p, "from");
2577 sm_syslog(LOG_INFO, e->e_id,
2578 "SMTP MAIL command (%.100s) from %s tempfailed (due to previous checks)",
2580 usrerr(MSG_TEMPFAIL);
2584 /* make sure we know who the sending host is */
2585 if (sendinghost == NULL)
2586 sendinghost = peerhostname;
2590 if (sm_debug_active(&DebugLeakSmtp, 1))
2593 sm_dprintf("smtp() heap group #%d\n",
2596 #endif /* SM_HEAP_CHECK */
2602 auth_warning(e, "%s didn't use HELO protocol",
2605 #ifdef PICKY_HELO_CHECK
2606 if (sm_strcasecmp(sendinghost, peerhostname) != 0 &&
2607 (sm_strcasecmp(peerhostname, "localhost") != 0 ||
2608 sm_strcasecmp(sendinghost, MyHostName) != 0))
2610 auth_warning(e, "Host %s claimed to be %s",
2611 CurSmtpClient, sendinghost);
2613 #endif /* PICKY_HELO_CHECK */
2615 if (protocol == NULL)
2617 macdefine(&e->e_macro, A_PERM, 'r', protocol);
2618 macdefine(&e->e_macro, A_PERM, 's', sendinghost);
2624 macdefine(&e->e_macro, A_PERM, macid("{ntries}"), "0");
2625 macdefine(&e->e_macro, A_PERM, macid("{nrcpts}"), "0");
2626 macdefine(&e->e_macro, A_PERM, macid("{nbadrcpts}"),
2628 e->e_flags |= EF_CLRQUEUE;
2629 sm_setproctitle(true, e, "%s %s: %.80s",
2631 CurSmtpClient, inp);
2633 /* do the processing */
2636 extern char *FullName;
2639 SM_FREE_CLR(FullName);
2641 /* must parse sender first */
2643 setsender(p, e, &delimptr, ' ', false);
2644 if (delimptr != NULL && *delimptr != '\0')
2647 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2649 /* Successfully set e_from, allow logging */
2650 e->e_flags |= EF_LOGSENDER;
2652 /* put resulting triple from parseaddr() into macros */
2653 if (e->e_from.q_mailer != NULL)
2654 macdefine(&e->e_macro, A_PERM,
2655 macid("{mail_mailer}"),
2656 e->e_from.q_mailer->m_name);
2658 macdefine(&e->e_macro, A_PERM,
2659 macid("{mail_mailer}"), NULL);
2660 if (e->e_from.q_host != NULL)
2661 macdefine(&e->e_macro, A_PERM,
2662 macid("{mail_host}"),
2665 macdefine(&e->e_macro, A_PERM,
2666 macid("{mail_host}"), "localhost");
2667 if (e->e_from.q_user != NULL)
2668 macdefine(&e->e_macro, A_PERM,
2669 macid("{mail_addr}"),
2672 macdefine(&e->e_macro, A_PERM,
2673 macid("{mail_addr}"), NULL);
2675 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2677 /* check for possible spoofing */
2678 if (RealUid != 0 && OpMode == MD_SMTP &&
2679 !wordinclass(RealUserName, 't') &&
2680 (!bitnset(M_LOCALMAILER,
2681 e->e_from.q_mailer->m_flags) ||
2682 strcmp(e->e_from.q_user, RealUserName) != 0))
2684 auth_warning(e, "%s owned process doing -bs",
2688 /* reset to default value */
2689 SevenBitInput = SevenBitInput_Saved;
2691 /* now parse ESMTP arguments */
2694 parse_esmtp_args(e, NULL, p, delimptr, "MAIL", args,
2697 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2700 # if _FFR_AUTH_PASSING
2701 /* set the default AUTH= if the sender didn't */
2702 if (e->e_auth_param == NULL)
2704 /* XXX only do this for an MSA? */
2705 e->e_auth_param = macvalue(macid("{auth_authen}"),
2707 if (e->e_auth_param == NULL)
2708 e->e_auth_param = "<>";
2711 ** XXX should we invoke Strust_auth now?
2712 ** authorizing as the client that just
2713 ** authenticated, so we'll trust implicitly
2716 # endif /* _FFR_AUTH_PASSING */
2719 /* do config file checking of the sender */
2720 macdefine(&e->e_macro, A_PERM,
2721 macid("{addr_type}"), "e s");
2723 /* make the "real" sender address available */
2724 macdefine(&e->e_macro, A_TEMP, macid("{mail_from}"),
2726 #endif /* _FFR_MAIL_MACRO */
2727 if (rscheck("check_mail", addr,
2728 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2729 NULL, e->e_id, NULL, NULL) != EX_OK ||
2731 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2732 macdefine(&e->e_macro, A_PERM,
2733 macid("{addr_type}"), NULL);
2735 if (MaxMessageSize > 0 &&
2736 (e->e_msgsize > MaxMessageSize ||
2739 usrerr("552 5.2.3 Message size exceeds fixed maximum message size (%ld)",
2741 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2745 ** XXX always check whether there is at least one fs
2746 ** with enough space?
2747 ** However, this may not help much: the queue group
2748 ** selection may later on select a FS that hasn't
2752 if ((NumFileSys == 1 || NumQueue == 1) &&
2753 !enoughdiskspace(e->e_msgsize, e)
2754 #if _FFR_ANY_FREE_FS
2755 && !filesys_free(e->e_msgsize)
2756 #endif /* _FFR_ANY_FREE_FS */
2760 ** We perform this test again when the
2761 ** queue directory is selected, in collect.
2764 usrerr("452 4.4.5 Insufficient disk space; try again later");
2765 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2768 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2772 if (smtp.sm_milterlist && smtp.sm_milterize &&
2773 !bitset(EF_DISCARD, e->e_flags))
2778 response = milter_envfrom(args, e, &state);
2779 MILTER_REPLY("from");
2783 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
2785 message("250 2.1.0 Sender ok");
2786 smtp.sm_gotmail = true;
2788 SM_EXCEPT(exc, "[!F]*")
2791 ** An error occurred while processing a MAIL command.
2792 ** Jump to the common error handling code.
2802 e->e_flags &= ~EF_PM_NOTIFY;
2806 case CMDRCPT: /* rcpt -- designate recipient */
2808 macdefine(&e->e_macro, A_PERM,
2809 macid("{rcpt_mailer}"), NULL);
2810 macdefine(&e->e_macro, A_PERM,
2811 macid("{rcpt_host}"), NULL);
2812 macdefine(&e->e_macro, A_PERM,
2813 macid("{rcpt_addr}"), NULL);
2815 (void) memset(&addr_st, '\0', sizeof(addr_st));
2817 milter_rcpt_added = false;
2818 smtp.sm_e_nrcpts_orig = e->e_nrcpts;
2820 #if _FFR_BADRCPT_SHUTDOWN
2822 ** hack to deal with hack, see below:
2823 ** n_badrcpts is increased if limit is reached.
2826 n_badrcpts_adj = (BadRcptThrottle > 0 &&
2827 n_badrcpts > BadRcptThrottle &&
2829 ? n_badrcpts - 1 : n_badrcpts;
2830 if (BadRcptShutdown > 0 &&
2831 n_badrcpts_adj >= BadRcptShutdown &&
2832 (BadRcptShutdownGood == 0 ||
2833 smtp.sm_nrcpts == 0 ||
2834 (n_badrcpts_adj * 100 /
2835 (smtp.sm_nrcpts + n_badrcpts) >=
2836 BadRcptShutdownGood)))
2839 sm_syslog(LOG_INFO, e->e_id,
2840 "%s: Possible SMTP RCPT flood, shutting down connection.",
2842 message("421 4.7.0 %s Too many bad recipients; closing connection",
2845 /* arrange to ignore any current send list */
2846 e->e_sendqueue = NULL;
2849 #endif /* _FFR_BADRCPT_SHUTDOWN */
2850 if (BadRcptThrottle > 0 &&
2851 n_badrcpts >= BadRcptThrottle)
2854 n_badrcpts == BadRcptThrottle)
2856 sm_syslog(LOG_INFO, e->e_id,
2857 "%s: Possible SMTP RCPT flood, throttling.",
2860 /* To avoid duplicated message */
2866 ** Don't use exponential backoff for now.
2867 ** Some systems will open more connections
2868 ** and actually overload the receiver even
2872 (void) sleep(BadRcptThrottleDelay);
2874 if (!smtp.sm_gotmail)
2876 usrerr("503 5.0.0 Need MAIL before RCPT");
2879 SmtpPhase = "server RCPT";
2885 /* limit flooding of our machine */
2886 if (MaxRcptPerMsg > 0 &&
2887 smtp.sm_nrcpts >= MaxRcptPerMsg)
2889 /* sleep(1); / * slow down? */
2890 usrerr("452 4.5.3 Too many recipients");
2894 if (!SM_IS_INTERACTIVE(e->e_sendmode)
2896 && (NotFirstDelivery || SM_DM_ONE != e->e_sendmode)
2897 #endif /* _FFR_DM_ONE */
2899 e->e_flags |= EF_VRFYONLY;
2903 ** Do not expand recipients at RCPT time (in the call
2904 ** to recipient()) if a milter can delete or reject
2905 ** a RCPT. If they are expanded, it is impossible
2906 ** for removefromlist() to figure out the expanded
2907 ** members of the original recipient and mark them
2911 if (!(smtp.sm_milterlist && smtp.sm_milterize &&
2912 !bitset(EF_DISCARD, e->e_flags)) &&
2913 (smtp.sm_milters.mis_flags &
2914 (MIS_FL_DEL_RCPT|MIS_FL_REJ_RCPT)) != 0)
2915 e->e_flags |= EF_VRFYONLY;
2916 milter_cmd_done = false;
2917 milter_cmd_safe = false;
2920 p = skipword(p, "to");
2923 macdefine(&e->e_macro, A_PERM,
2924 macid("{addr_type}"), "e r");
2925 a = parseaddr(p, NULLADDR, RF_COPYALL, ' ', &delimptr,
2927 macdefine(&e->e_macro, A_PERM,
2928 macid("{addr_type}"), NULL);
2933 usrerr("501 5.0.0 Missing recipient");
2937 if (delimptr != NULL && *delimptr != '\0')
2940 /* put resulting triple from parseaddr() into macros */
2941 if (a->q_mailer != NULL)
2942 macdefine(&e->e_macro, A_PERM,
2943 macid("{rcpt_mailer}"),
2944 a->q_mailer->m_name);
2946 macdefine(&e->e_macro, A_PERM,
2947 macid("{rcpt_mailer}"), NULL);
2948 if (a->q_host != NULL)
2949 macdefine(&e->e_macro, A_PERM,
2950 macid("{rcpt_host}"), a->q_host);
2952 macdefine(&e->e_macro, A_PERM,
2953 macid("{rcpt_host}"), "localhost");
2954 if (a->q_user != NULL)
2955 macdefine(&e->e_macro, A_PERM,
2956 macid("{rcpt_addr}"), a->q_user);
2958 macdefine(&e->e_macro, A_PERM,
2959 macid("{rcpt_addr}"), NULL);
2963 /* now parse ESMTP arguments */
2965 parse_esmtp_args(e, a, p, delimptr, "RCPT", args,
2972 ** rscheck() can trigger an "exception"
2973 ** in which case the execution continues at
2974 ** SM_EXCEPT(exc, "[!F]*")
2975 ** This means milter_cmd_safe is not set
2976 ** and hence milter is not invoked.
2977 ** Would it be "safe" to change that, i.e., use
2978 ** milter_cmd_safe = true;
2979 ** here so a milter is informed (if requested)
2980 ** about RCPTs that are rejected by check_rcpt?
2982 # if _FFR_MILTER_CHECK_REJECTIONS_TOO
2983 milter_cmd_safe = true;
2987 /* do config file checking of the recipient */
2988 macdefine(&e->e_macro, A_PERM,
2989 macid("{addr_type}"), "e r");
2990 if (rscheck("check_rcpt", addr,
2991 NULL, e, RSF_RMCOMM|RSF_COUNT, 3,
2992 NULL, e->e_id, p_addr_st, NULL) != EX_OK ||
2995 macdefine(&e->e_macro, A_PERM,
2996 macid("{addr_type}"), NULL);
2998 /* If discarding, don't bother to verify user */
2999 if (bitset(EF_DISCARD, e->e_flags))
3000 a->q_state = QS_VERIFIED;
3002 milter_cmd_safe = true;
3008 /* save in recipient list after ESMTP mods */
3009 a = recipient(a, &e->e_sendqueue, 0, e);
3010 /* may trigger exception... */
3013 milter_rcpt_added = true;
3016 if(!(Errors > 0) && QS_IS_BADADDR(a->q_state))
3018 /* punt -- should keep message in ADDRESS.... */
3019 usrerr("550 5.1.1 Addressee unknown");
3024 if (smtp.sm_milterlist && smtp.sm_milterize &&
3025 !bitset(EF_DISCARD, e->e_flags))
3030 /* how to get the error codes? */
3033 macdefine(&e->e_macro, A_PERM,
3034 macid("{rcpt_mailer}"),
3037 a->q_status != NULL &&
3038 a->q_rstatus != NULL)
3040 macdefine(&e->e_macro, A_PERM,
3041 macid("{rcpt_host}"),
3043 macdefine(&e->e_macro, A_PERM,
3044 macid("{rcpt_addr}"),
3049 if (addr_st.q_host != NULL)
3050 macdefine(&e->e_macro,
3052 macid("{rcpt_host}"),
3054 if (addr_st.q_user != NULL)
3055 macdefine(&e->e_macro,
3057 macid("{rcpt_addr}"),
3062 response = milter_envrcpt(args, e, &state,
3064 milter_cmd_done = true;
3069 /* no errors during parsing, but might be a duplicate */
3070 e->e_to = a->q_paddr;
3071 if (!(Errors > 0) && !QS_IS_BADADDR(a->q_state))
3073 if (smtp.sm_nrcpts == 0)
3075 message("250 2.1.5 Recipient ok%s",
3076 QS_IS_QUEUEUP(a->q_state) ?
3077 " (will queue)" : "");
3081 /* Is this needed? */
3084 #endif /* !MILTER */
3086 macdefine(&e->e_macro, A_PERM,
3087 macid("{rcpt_mailer}"), NULL);
3088 macdefine(&e->e_macro, A_PERM,
3089 macid("{rcpt_host}"), NULL);
3090 macdefine(&e->e_macro, A_PERM,
3091 macid("{rcpt_addr}"), NULL);
3092 macdefine(&e->e_macro, A_PERM,
3093 macid("{dsn_notify}"), NULL);
3101 SM_EXCEPT(exc, "[!F]*")
3103 /* An exception occurred while processing RCPT */
3104 e->e_flags &= ~(EF_FATALERRS|EF_PM_NOTIFY);
3108 if (smtp.sm_milterlist && smtp.sm_milterize &&
3109 !bitset(EF_DISCARD, e->e_flags) &&
3110 !milter_cmd_done && milter_cmd_safe)
3115 macdefine(&e->e_macro, A_PERM,
3116 macid("{rcpt_mailer}"), "error");
3118 /* how to get the error codes? */
3119 if (addr_st.q_host != NULL)
3120 macdefine(&e->e_macro, A_PERM,
3121 macid("{rcpt_host}"),
3123 else if (a != NULL && a->q_status != NULL)
3124 macdefine(&e->e_macro, A_PERM,
3125 macid("{rcpt_host}"),
3128 if (addr_st.q_user != NULL)
3129 macdefine(&e->e_macro, A_PERM,
3130 macid("{rcpt_addr}"),
3132 else if (a != NULL && a->q_rstatus != NULL)
3133 macdefine(&e->e_macro, A_PERM,
3134 macid("{rcpt_addr}"),
3137 response = milter_envrcpt(args, e, &state,
3139 milter_cmd_done = true;
3141 macdefine(&e->e_macro, A_PERM,
3142 macid("{rcpt_mailer}"), NULL);
3143 macdefine(&e->e_macro, A_PERM,
3144 macid("{rcpt_host}"), NULL);
3145 macdefine(&e->e_macro, A_PERM,
3146 macid("{rcpt_addr}"), NULL);
3148 if (smtp.sm_milterlist && smtp.sm_milterize &&
3149 milter_rcpt_added && milter_cmd_done &&
3152 (void) removefromlist(addr, &e->e_sendqueue, e);
3153 milter_cmd_fail = false;
3154 if (smtp.sm_e_nrcpts_orig < e->e_nrcpts)
3155 e->e_nrcpts = smtp.sm_e_nrcpts_orig;
3162 case CMDDATA: /* data -- text of mail */
3164 if (!smtp_data(&smtp, e))
3168 case CMDRSET: /* rset -- reset state */
3170 message("451 4.0.0 Test failure");
3172 message("250 2.0.0 Reset state");
3173 CLEAR_STATE(cmdbuf);
3176 case CMDVRFY: /* vrfy -- verify address */
3177 case CMDEXPN: /* expn -- expand address */
3178 vrfy = c->cmd_code == CMDVRFY;
3179 DELAY_CONN(vrfy ? "VRFY" : "EXPN");
3183 sm_syslog(LOG_INFO, e->e_id,
3184 "SMTP %s command (%.100s) from %s tempfailed (due to previous checks)",
3185 vrfy ? "VRFY" : "EXPN",
3188 /* RFC 821 doesn't allow 4xy reply code */
3189 usrerr("550 5.7.1 Please try again later");
3192 wt = checksmtpattack(&n_verifies, MAXVRFYCOMMANDS,
3193 false, vrfy ? "VRFY" : "EXPN", e);
3195 previous = curtime();
3196 if ((vrfy && bitset(PRIV_NOVRFY, PrivacyFlags)) ||
3197 (!vrfy && !bitset(SRV_OFFER_EXPN, features)))
3200 message("252 2.5.2 Cannot VRFY user; try RCPT to attempt delivery (or try finger)");
3202 message("502 5.7.0 Sorry, we do not allow this operation");
3204 sm_syslog(LOG_INFO, e->e_id,
3205 "%s: %s [rejected]",
3207 shortenstring(inp, MAXSHORTSTR));
3210 else if (!gothello &&
3211 bitset(vrfy ? PRIV_NEEDVRFYHELO : PRIV_NEEDEXPNHELO,
3214 usrerr("503 5.0.0 I demand that you introduce yourself first");
3220 sm_syslog(LOG_INFO, e->e_id, "%s: %s",
3222 shortenstring(inp, MAXSHORTSTR));
3228 e->e_flags |= EF_VRFYONLY;
3229 while (*p != '\0' && isascii(*p) && isspace(*p))
3233 usrerr("501 5.5.2 Argument required");
3237 /* do config file checking of the address */
3238 if (rscheck(vrfy ? "check_vrfy" : "check_expn",
3239 p, NULL, e, RSF_RMCOMM, 3, NULL,
3240 NOQID, NULL, NULL) != EX_OK ||
3242 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
3243 (void) sendtolist(p, NULLADDR, &vrfyqueue, 0, e);
3249 t = wt - (curtime() - previous);
3254 sm_exc_raisenew_x(&EtypeQuickAbort, 1);
3255 if (vrfyqueue == NULL)
3257 usrerr("554 5.5.2 Nothing to %s", vrfy ? "VRFY" : "EXPN");
3259 while (vrfyqueue != NULL)
3261 if (!QS_IS_UNDELIVERED(vrfyqueue->q_state))
3263 vrfyqueue = vrfyqueue->q_next;
3267 /* see if there is more in the vrfy list */
3269 while ((a = a->q_next) != NULL &&
3270 (!QS_IS_UNDELIVERED(a->q_state)))
3272 printvrfyaddr(vrfyqueue, a == NULL, vrfy);
3276 SM_EXCEPT(exc, "[!F]*")
3279 ** An exception occurred while processing VRFY/EXPN
3288 case CMDETRN: /* etrn -- force queue flush */
3291 /* Don't leak queue information via debug flags */
3292 if (!bitset(SRV_OFFER_ETRN, features) || UseMSP ||
3293 (RealUid != 0 && RealUid != TrustedUid &&
3296 /* different message for MSA ? */
3297 message("502 5.7.0 Sorry, we do not allow this operation");
3299 sm_syslog(LOG_INFO, e->e_id,
3300 "%s: %s [rejected]",
3302 shortenstring(inp, MAXSHORTSTR));
3308 sm_syslog(LOG_INFO, e->e_id,
3309 "SMTP ETRN command (%.100s) from %s tempfailed (due to previous checks)",
3311 usrerr(MSG_TEMPFAIL);
3317 usrerr("500 5.5.2 Parameter required");
3321 /* crude way to avoid denial-of-service attacks */
3322 STOP_IF_ATTACK(checksmtpattack(&n_etrn, MAXETRNCOMMANDS,
3326 ** Do config file checking of the parameter.
3327 ** Even though we have srv_features now, we still
3328 ** need this ruleset because the former is called
3329 ** when the connection has been established, while
3330 ** this ruleset is called when the command is
3331 ** actually issued and therefore has all information
3332 ** available to make a decision.
3335 if (rscheck("check_etrn", p, NULL, e, RSF_RMCOMM, 3,
3336 NULL, NOQID, NULL, NULL) != EX_OK ||
3341 sm_syslog(LOG_INFO, e->e_id,
3342 "%s: ETRN %s", CurSmtpClient,
3343 shortenstring(p, MAXSHORTSTR));
3351 qgrp = name2qid(id);
3352 if (!ISVALIDQGRP(qgrp))
3354 usrerr("459 4.5.4 Queue %s unknown",
3358 for (i = 0; i < NumQueue && Queue[i] != NULL;
3360 Queue[i]->qg_nextrun = (time_t) -1;
3361 Queue[qgrp]->qg_nextrun = 0;
3362 ok = run_work_group(Queue[qgrp]->qg_wgrp,
3363 RWG_FORK|RWG_FORCE);
3364 if (ok && Errors == 0)
3365 message("250 2.0.0 Queuing for queue group %s started", id);
3374 new = (QUEUE_CHAR *) sm_malloc(sizeof(QUEUE_CHAR));
3377 syserr("500 5.5.0 ETRN out of memory");
3380 new->queue_match = id;
3381 new->queue_negate = false;
3382 new->queue_next = NULL;
3383 QueueLimitRecipient = new;
3384 ok = runqueue(true, false, false, true);
3385 sm_free(QueueLimitRecipient); /* XXX */
3386 QueueLimitRecipient = NULL;
3387 if (ok && Errors == 0)
3388 message("250 2.0.0 Queuing for node %s started", p);
3391 case CMDHELP: /* help -- give user info */
3396 case CMDNOOP: /* noop -- do nothing */
3398 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
3400 message("250 2.0.0 OK");
3403 case CMDQUIT: /* quit -- leave mail */
3404 message("221 2.0.0 %s closing connection", MyHostName);
3406 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
3407 #endif /* PIPELINING */
3409 if (smtp.sm_nrcpts > 0)
3410 logundelrcpts(e, "aborted by sender", 9, false);
3412 /* arrange to ignore any current send list */
3413 e->e_sendqueue = NULL;
3416 /* shutdown TLS connection */
3419 (void) endtls(srv_ssl, "server");
3422 #endif /* STARTTLS */
3424 if (authenticating == SASL_IS_AUTH)
3426 sasl_dispose(&conn);
3427 authenticating = SASL_NOT_AUTH;
3428 /* XXX sasl_done(); this is a child */
3433 /* avoid future 050 messages */
3437 /* close out milter filters */
3442 sm_dprintf("QUIT: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",
3444 bitset(EF_LOGSENDER, e->e_flags),
3446 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
3448 e->e_flags &= ~EF_LOGSENDER;
3450 if (lognullconnection && LogLevel > 5 &&
3455 d = macvalue(macid("{daemon_name}"), e);
3460 ** even though this id is "bogus", it makes
3461 ** it simpler to "grep" related events, e.g.,
3462 ** timeouts for the same connection.
3465 sm_syslog(LOG_INFO, e->e_id,
3466 "%s did not issue MAIL/EXPN/VRFY/ETRN during connection to %s",
3471 /* return to handle next connection */
3474 finis(true, true, ExitStat);
3477 /* just to avoid bogus warning from some compilers */
3480 case CMDVERB: /* set verbose mode */
3482 if (!bitset(SRV_OFFER_EXPN, features) ||
3483 !bitset(SRV_OFFER_VERB, features))
3485 /* this would give out the same info */
3486 message("502 5.7.0 Verbose unavailable");
3489 STOP_IF_ATTACK(checksmtpattack(&n_noop, MaxNOOPCommands,
3492 set_delivery_mode(SM_DELIVER, e);
3493 message("250 2.0.0 Verbose mode");
3497 case CMDDBGQSHOW: /* show queues */
3498 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3500 printaddr(smioout, e->e_sendqueue, true);
3503 case CMDDBGDEBUG: /* set debug mode */
3504 tTsetup(tTdvect, sizeof(tTdvect), "0-99.1");
3506 message("200 2.0.0 Debug set");
3509 #else /* SMTPDEBUG */
3510 case CMDDBGQSHOW: /* show queues */
3511 case CMDDBGDEBUG: /* set debug mode */
3512 #endif /* SMTPDEBUG */
3513 case CMDLOGBOGUS: /* bogus command */
3514 DELAY_CONN("Bogus");
3516 sm_syslog(LOG_CRIT, e->e_id,
3517 "\"%s\" command from %s (%.100s)",
3518 c->cmd_name, CurSmtpClient,
3519 anynet_ntoa(&RealHostAddr));
3522 case CMDERROR: /* unknown command */
3523 #if MAXBADCOMMANDS > 0
3524 if (++n_badcmds > MAXBADCOMMANDS)
3527 message("421 4.7.0 %s Too many bad commands; closing connection",
3530 /* arrange to ignore any current send list */
3531 e->e_sendqueue = NULL;
3534 #endif /* MAXBADCOMMANDS > 0 */
3536 #if MILTER && SMFI_VERSION > 2
3537 if (smtp.sm_milterlist && smtp.sm_milterize &&
3538 !bitset(EF_DISCARD, e->e_flags))
3543 if (MilterLogLevel > 9)
3544 sm_syslog(LOG_INFO, e->e_id,
3545 "Sending \"%s\" to Milter", inp);
3546 response = milter_unknown(inp, e, &state);
3547 MILTER_REPLY("unknown");
3548 if (state == SMFIR_REPLYCODE ||
3549 state == SMFIR_REJECT ||
3550 state == SMFIR_TEMPFAIL ||
3551 state == SMFIR_SHUTDOWN)
3553 /* MILTER_REPLY already gave an error */
3557 #endif /* MILTER && SMFI_VERSION > 2 */
3559 usrerr("500 5.5.1 Command unrecognized: \"%s\"",
3560 shortenstring(inp, MAXSHORTSTR));
3564 DELAY_CONN("Unimpl");
3565 usrerr("502 5.5.1 Command not implemented: \"%s\"",
3566 shortenstring(inp, MAXSHORTSTR));
3570 DELAY_CONN("default");
3572 syserr("500 5.5.0 smtp: unknown code %d", c->cmd_code);
3579 SM_EXCEPT(exc, "[!F]*")
3582 ** The only possible exception is "E:mta.quickabort".
3583 ** There is nothing to do except fall through and loop.
3590 ** SMTP_DATA -- implement the SMTP DATA command.
3593 ** smtp -- status of SMTP connection.
3597 ** true iff SMTP session can continue.
3600 ** possibly sends message.
3618 unsigned int features;
3621 SmtpPhase = "server DATA";
3622 if (!smtp->sm_gotmail)
3624 usrerr("503 5.0.0 Need MAIL command");
3627 else if (smtp->sm_nrcpts <= 0)
3629 usrerr("503 5.0.0 Need RCPT (recipient)");
3632 (void) sm_snprintf(buf, sizeof(buf), "%u", smtp->sm_nrcpts);
3633 if (rscheck("check_data", buf, NULL, e,
3634 RSF_RMCOMM|RSF_UNSTRUCTURED|RSF_COUNT, 3, NULL,
3635 e->e_id, NULL, NULL) != EX_OK)
3638 #if MILTER && SMFI_VERSION > 3
3639 if (smtp->sm_milterlist && smtp->sm_milterize &&
3640 !bitset(EF_DISCARD, e->e_flags))
3644 int savelogusrerrs = LogUsrErrs;
3646 response = milter_data_cmd(e, &state);
3649 case SMFIR_REPLYCODE:
3650 if (MilterLogLevel > 3)
3652 sm_syslog(LOG_INFO, e->e_id,
3653 "Milter: cmd=data, reject=%s",
3657 #if _FFR_MILTER_ENHSC
3658 if (ISSMTPCODE(response))
3659 (void) extenhsc(response + 4, ' ', e->e_enhsc);
3660 #endif /* _FFR_MILTER_ENHSC */
3663 if (strncmp(response, "421 ", 4) == 0
3664 || strncmp(response, "421-", 4) == 0)
3666 e->e_sendqueue = NULL;
3672 if (MilterLogLevel > 3)
3674 sm_syslog(LOG_INFO, e->e_id,
3675 "Milter: cmd=data, reject=550 5.7.1 Command rejected");
3678 #if _FFR_MILTER_ENHSC
3679 (void) sm_strlcpy(e->e_enhsc, "5.7.1",
3680 sizeof(e->e_enhsc));
3681 #endif /* _FFR_MILTER_ENHSC */
3682 usrerr("550 5.7.1 Command rejected");
3686 if (MilterLogLevel > 3)
3687 sm_syslog(LOG_INFO, e->e_id,
3688 "Milter: cmd=data, discard");
3689 e->e_flags |= EF_DISCARD;
3692 case SMFIR_TEMPFAIL:
3693 if (MilterLogLevel > 3)
3695 sm_syslog(LOG_INFO, e->e_id,
3696 "Milter: cmd=data, reject=%s",
3700 #if _FFR_MILTER_ENHSC
3701 (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc);
3702 #endif /* _FFR_MILTER_ENHSC */
3703 usrerr(MSG_TEMPFAIL);
3706 case SMFIR_SHUTDOWN:
3707 if (MilterLogLevel > 3)
3709 sm_syslog(LOG_INFO, e->e_id,
3710 "Milter: cmd=data, reject=421 4.7.0 %s closing connection",
3714 usrerr("421 4.7.0 %s closing connection", MyHostName);
3715 e->e_sendqueue = NULL;
3718 LogUsrErrs = savelogusrerrs;
3719 if (response != NULL)
3720 sm_free(response); /* XXX */
3722 #endif /* MILTER && SMFI_VERSION > 3 */
3724 /* put back discard bit */
3725 if (smtp->sm_discard)
3726 e->e_flags |= EF_DISCARD;
3728 /* check to see if we need to re-expand aliases */
3729 /* also reset QS_BADADDR on already-diagnosted addrs */
3730 doublequeue = false;
3731 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
3733 if (QS_IS_VERIFIED(a->q_state) &&
3734 !bitset(EF_DISCARD, e->e_flags))
3736 /* need to re-expand aliases */
3739 if (QS_IS_BADADDR(a->q_state))
3741 /* make this "go away" */
3742 a->q_state = QS_DONTSEND;
3746 /* collect the text of the message */
3747 SmtpPhase = "collect";
3750 collect(InChannel, true, NULL, e, true);
3752 /* redefine message size */
3753 (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize));
3754 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3756 /* rscheck() will set Errors or EF_DISCARD if it trips */
3757 (void) rscheck("check_eom", buf, NULL, e, RSF_UNSTRUCTURED|RSF_COUNT,
3758 3, NULL, e->e_id, NULL, NULL);
3761 milteraccept = true;
3762 if (smtp->sm_milterlist && smtp->sm_milterize &&
3764 !bitset(EF_DISCARD, e->e_flags))
3769 response = milter_data(e, &state);
3772 case SMFIR_REPLYCODE:
3773 if (MilterLogLevel > 3)
3774 sm_syslog(LOG_INFO, e->e_id,
3775 "Milter: data, reject=%s",
3777 milteraccept = false;
3778 #if _FFR_MILTER_ENHSC
3779 if (ISSMTPCODE(response))
3780 (void) extenhsc(response + 4, ' ', e->e_enhsc);
3781 #endif /* _FFR_MILTER_ENHSC */
3783 if (strncmp(response, "421 ", 4) == 0
3784 || strncmp(response, "421-", 4) == 0)
3789 milteraccept = false;
3790 if (MilterLogLevel > 3)
3791 sm_syslog(LOG_INFO, e->e_id,
3792 "Milter: data, reject=554 5.7.1 Command rejected");
3793 usrerr("554 5.7.1 Command rejected");
3797 if (MilterLogLevel > 3)
3798 sm_syslog(LOG_INFO, e->e_id,
3799 "Milter: data, discard");
3800 milteraccept = false;
3801 e->e_flags |= EF_DISCARD;
3804 case SMFIR_TEMPFAIL:
3805 if (MilterLogLevel > 3)
3806 sm_syslog(LOG_INFO, e->e_id,
3807 "Milter: data, reject=%s",
3809 milteraccept = false;
3810 #if _FFR_MILTER_ENHSC
3811 (void) extenhsc(MSG_TEMPFAIL + 4, ' ', e->e_enhsc);
3812 #endif /* _FFR_MILTER_ENHSC */
3813 usrerr(MSG_TEMPFAIL);
3816 case SMFIR_SHUTDOWN:
3817 if (MilterLogLevel > 3)
3818 sm_syslog(LOG_INFO, e->e_id,
3819 "Milter: data, reject=421 4.7.0 %s closing connection",
3821 milteraccept = false;
3822 usrerr("421 4.7.0 %s closing connection", MyHostName);
3826 if (response != NULL)
3830 /* Milter may have changed message size */
3831 (void) sm_snprintf(buf, sizeof(buf), "%ld", PRT_NONNEGL(e->e_msgsize));
3832 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), buf);
3834 /* abort message filters that didn't get the body & log msg is OK */
3835 if (smtp->sm_milterlist && smtp->sm_milterize)
3838 if (milteraccept && MilterLogLevel > 9)
3839 sm_syslog(LOG_INFO, e->e_id, "Milter accept: message");
3843 ** If SuperSafe is SAFE_REALLY_POSTMILTER, and we don't have milter or
3844 ** milter accepted message, sync it now
3846 ** XXX This is almost a copy of the code in collect(): put it into
3847 ** a function that is called from both places?
3850 if (milteraccept && SuperSafe == SAFE_REALLY_POSTMILTER)
3853 SM_FILE_T *volatile df;
3857 dfname = queuename(e, DATAFL_LETTER);
3858 if (sm_io_setinfo(df, SM_BF_COMMIT, NULL) < 0
3864 if (save_errno == EEXIST)
3869 if (stat(dfname, &st) < 0)
3872 syserr("@collect: bfcommit(%s): already on disk, size=%ld",
3873 dfname, (long) st.st_size);
3874 dfd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL);
3876 dumpfd(dfd, true, true);
3879 dferror(df, "bfcommit", e);
3881 finis(save_errno != EEXIST, true, ExitStat);
3883 else if ((afd = sm_io_getinfo(df, SM_IO_WHAT_FD, NULL)) < 0)
3885 dferror(df, "sm_io_getinfo", e);
3887 finis(true, true, ExitStat);
3890 else if (fsync(afd) < 0)
3892 dferror(df, "fsync", e);
3894 finis(true, true, ExitStat);
3897 else if (sm_io_close(df, SM_TIME_DEFAULT) < 0)
3899 dferror(df, "sm_io_close", e);
3901 finis(true, true, ExitStat);
3905 /* Now reopen the df file */
3906 e->e_dfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT, dfname,
3907 SM_IO_RDONLY, NULL);
3908 if (e->e_dfp == NULL)
3910 /* we haven't acked receipt yet, so just chuck this */
3911 syserr("@Cannot reopen %s", dfname);
3912 finis(true, true, ExitStat);
3918 /* Check if quarantining stats should be updated */
3919 if (e->e_quarmsg != NULL)
3920 markstats(e, NULL, STATS_QUARANTINE);
3923 ** If a header/body check (header checks or milter)
3924 ** set EF_DISCARD, don't queueup the message --
3925 ** that would lose the EF_DISCARD bit and deliver
3929 if (bitset(EF_DISCARD, e->e_flags))
3930 doublequeue = false;
3932 aborting = Errors > 0;
3933 if (!(aborting || bitset(EF_DISCARD, e->e_flags)) &&
3934 (QueueMode == QM_QUARANTINE || e->e_quarmsg == NULL) &&
3935 !split_by_recipient(e))
3936 aborting = bitset(EF_FATALERRS, e->e_flags);
3942 /* Log who the mail would have gone to */
3943 logundelrcpts(e, e->e_message, 8, false);
3946 ** If something above refused the message, we still haven't
3947 ** accepted responsibility for it. Don't send DSNs.
3950 for (q = e->e_sendqueue; q != NULL; q = q->q_next)
3951 q->q_flags &= ~Q_PINGFLAGS;
3958 /* from now on, we have to operate silently */
3963 ** Clear message, it may contain an error from the SMTP dialogue.
3964 ** This error must not show up in the queue.
3965 ** Some error message should show up, e.g., alias database
3966 ** not available, but others shouldn't, e.g., from check_rcpt.
3969 e->e_message = NULL;
3973 ** Arrange to send to everyone.
3974 ** If sending to multiple people, mail back
3975 ** errors rather than reporting directly.
3976 ** In any case, don't mail back errors for
3977 ** anything that has happened up to
3978 ** now (the other end will do this).
3979 ** Truncate our transcript -- the mail has gotten
3980 ** to us successfully, and if we have
3981 ** to mail this back, it will be easier
3983 ** Then send to everyone.
3984 ** Finally give a reply code. If an error has
3985 ** already been given, don't mail a
3987 ** We goose error returns by clearing error bit.
3990 SmtpPhase = "delivery";
3991 (void) sm_io_setinfo(e->e_xfp, SM_BF_TRUNCATE, NULL);
3995 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
3996 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
3997 #endif /* NAMED_BIND */
4000 if (SM_PROXY_REQ == e->e_sendmode)
4002 /* is proxy mode possible? */
4003 if (e->e_sibling == NULL && e->e_nrcpts == 1
4004 && smtp->sm_nrcpts == 1
4005 && (a = e->e_sendqueue) != NULL && a->q_next == NULL)
4007 a->q_flags &= ~(QPINGONFAILURE|QPINGONSUCCESS|
4009 e->e_errormode = EM_QUIET;
4010 e->e_sendmode = SM_PROXY;
4017 sm_dprintf("srv: mode=%c, e=%p, sibling=%p, nrcpts=%d, sm_nrcpts=%d, sendqueue=%p, next=%p\n",
4018 e->e_sendmode, e, e->e_sibling, e->e_nrcpts,
4020 (a == NULL) ? (void *)0 : a->q_next);
4023 /* switch to interactive mode */
4024 e->e_sendmode = SM_DELIVER;
4026 sm_syslog(LOG_DEBUG, e->e_id,
4027 "proxy mode requested but not possible");
4030 #endif /* _FFR_PROXY */
4032 for (ee = e; ee != NULL; ee = ee->e_sibling)
4034 /* make sure we actually do delivery */
4035 ee->e_flags &= ~EF_CLRQUEUE;
4037 /* from now on, operate silently */
4038 ee->e_errormode = EM_MAIL;
4042 /* make sure it is in the queue */
4043 queueup(ee, false, true);
4049 /* send to all recipients */
4052 if (SM_DM_ONE == e->e_sendmode)
4054 if (NotFirstDelivery)
4057 e->e_sendmode = SM_QUEUE;
4062 NotFirstDelivery = true;
4065 #endif /* _FFR_DM_ONE */
4071 /* put back id for SMTP logging in putoutmsg() */
4072 oldid = CurEnv->e_id;
4079 sm_dprintf("srv: mode=%c, e=%p, sibling=%p, nrcpts=%d, msg=%s, sendqueue=%p, next=%p, state=%d, SmtpError=%s, rcode=%d, renhsc=%s, text=%s\n",
4080 e->e_sendmode, e, e->e_sibling, e->e_nrcpts, e->e_message, a,
4081 (a == NULL) ? (void *)0 : a->q_next,
4082 (a == NULL) ? -1 : a->q_state, SmtpError, e->e_rcode,
4083 e->e_renhsc, e->e_text);
4086 if (SM_PROXY == e->e_sendmode && a->q_state != QS_SENT &&
4087 a->q_state != QS_VERIFIED) /* discarded! */
4094 #define NN_MSG(e) (((e)->e_message != NULL) ? (e)->e_message : "")
4096 #define SM_MSG_DEFERRED "Deferred: "
4097 if (m != NULL && strncmp(SM_MSG_DEFERRED, m,
4098 sizeof(SM_MSG_DEFERRED) - 1) == 0)
4099 m += sizeof(SM_MSG_DEFERRED) - 1;
4100 offset = extsc(m, ' ', replycode, enhsc);
4104 sm_dprintf("srv: SmtpError=%s, rcode=%d, renhsc=%s, replycode=%s, enhsc=%s, offset=%d\n",
4105 SmtpError, e->e_rcode, e->e_renhsc,
4106 replycode, enhsc, offset);
4109 #define DIG2CHAR(d) ((d) + '0')
4110 if (e->e_rcode != 0 && (replycode[0] == '\0' ||
4111 replycode[0] == DIG2CHAR(REPLYTYPE(e->e_rcode))))
4113 replycode[0] = DIG2CHAR(REPLYTYPE(e->e_rcode));
4114 replycode[1] = DIG2CHAR(REPLYCLASS(e->e_rcode));
4115 replycode[2] = DIG2CHAR(REPLYMINOR(e->e_rcode));
4116 replycode[3] = '\0';
4117 if (e->e_renhsc[0] == replycode[0])
4118 sm_strlcpy(enhsc, e->e_renhsc, sizeof(enhsc));
4122 if (e->e_text != NULL)
4124 (void) strreplnonprt(e->e_text, '_');
4125 errtext = e->e_text;
4128 errtext = m + offset;
4130 if (replycode[0] != '\0' && enhsc[0] != '\0')
4131 emessage(replycode, enhsc, "%s", errtext);
4132 else if (replycode[0] != '\0')
4133 emessage(replycode, smtptodsn(atoi(replycode)),
4135 else if (QS_IS_TEMPFAIL(a->q_state))
4138 message("450 4.5.1 %s", m);
4140 message("450 4.5.1 Temporary error");
4145 message("550 5.5.1 %s", m);
4147 message("550 5.0.0 Permanent error");
4152 #endif /* _FFR_PROXY */
4153 /* issue success message */
4155 if (MessageAccept != NULL && *MessageAccept != '\0')
4159 expand(MessageAccept, msg, sizeof(msg), e);
4160 message("250 2.0.0 %s", msg);
4163 #endif /* _FFR_MSG_ACCEPT */
4164 message("250 2.0.0 %s Message accepted for delivery", id);
4167 #endif /* _FFR_PROXY */
4168 CurEnv->e_id = oldid;
4170 /* if we just queued, poke it */
4173 bool anything_to_send = false;
4176 for (ee = e; ee != NULL; ee = ee->e_sibling)
4178 if (WILL_BE_QUEUED(ee->e_sendmode))
4180 if (shouldqueue(ee->e_msgpriority, ee->e_ctime))
4182 ee->e_sendmode = SM_QUEUE;
4185 else if (QueueMode != QM_QUARANTINE &&
4186 ee->e_quarmsg != NULL)
4188 ee->e_sendmode = SM_QUEUE;
4191 anything_to_send = true;
4193 /* close all the queue files */
4195 if (ee->e_dfp != NULL)
4197 (void) sm_io_close(ee->e_dfp, SM_TIME_DEFAULT);
4202 if (anything_to_send)
4206 ** XXX if we don't do this, we get 250 twice
4207 ** because it is also flushed in the child.
4210 (void) sm_io_flush(OutChannel, SM_TIME_DEFAULT);
4211 #endif /* PIPELINING */
4212 (void) doworklist(e, true, true);
4218 sm_dprintf("abortmessage: e_id=%s, EF_LOGSENDER=%d, LogLevel=%d\n",
4219 e->e_id, bitset(EF_LOGSENDER, e->e_flags), LogLevel);
4220 if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
4222 e->e_flags &= ~EF_LOGSENDER;
4224 /* clean up a bit */
4225 smtp->sm_gotmail = false;
4228 ** Call dropenvelope if and only if the envelope is *not*
4229 ** being processed by the child process forked by doworklist().
4232 if (aborting || bitset(EF_DISCARD, e->e_flags))
4233 (void) dropenvelope(e, true, false);
4236 for (ee = e; ee != NULL; ee = ee->e_sibling)
4239 QueueMode != QM_QUARANTINE &&
4240 ee->e_quarmsg != NULL)
4242 (void) dropenvelope(ee, true, false);
4245 if (WILL_BE_QUEUED(ee->e_sendmode))
4246 (void) dropenvelope(ee, true, false);
4251 features = e->e_features;
4252 sm_rpool_free(e->e_rpool);
4253 newenvelope(e, e, sm_rpool_new_x(NULL));
4254 e->e_flags = BlankEnvelope.e_flags;
4255 e->e_features = features;
4257 /* restore connection quarantining */
4258 if (smtp->sm_quarmsg == NULL)
4260 e->e_quarmsg = NULL;
4261 macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
4265 e->e_quarmsg = sm_rpool_strdup_x(e->e_rpool, smtp->sm_quarmsg);
4266 macdefine(&e->e_macro, A_PERM,
4267 macid("{quarantine}"), e->e_quarmsg);
4272 ** LOGUNDELRCPTS -- log undelivered (or all) recipients.
4276 ** msg -- message for Stat=
4277 ** level -- log level.
4278 ** all -- log all recipients.
4284 ** logs undelivered (or all) recipients
4288 logundelrcpts(e, msg, level, all)
4296 if (LogLevel <= level || msg == NULL || *msg == '\0')
4299 /* Clear $h so relay= doesn't get mislogged by logdelivery() */
4300 macdefine(&e->e_macro, A_PERM, 'h', NULL);
4302 /* Log who the mail would have gone to */
4303 for (a = e->e_sendqueue; a != NULL; a = a->q_next)
4305 if (!QS_IS_UNDELIVERED(a->q_state) && !all)
4307 e->e_to = a->q_paddr;
4308 logdelivery(NULL, NULL,
4309 #if _FFR_MILTER_ENHSC
4310 (a->q_status == NULL && e->e_enhsc[0] != '\0')
4312 #endif /* _FFR_MILTER_ENHSC */
4314 msg, NULL, (time_t) 0, e, a, EX_OK /* ??? */);
4319 ** CHECKSMTPATTACK -- check for denial-of-service attack by repetition
4322 ** pcounter -- pointer to a counter for this command.
4323 ** maxcount -- maximum value for this counter before we
4325 ** waitnow -- sleep now (in this routine)?
4326 ** cname -- command name for logging.
4327 ** e -- the current envelope.
4331 ** STOP_ATTACK if twice as many commands as allowed and
4335 ** Slows down if we seem to be under attack.
4339 checksmtpattack(pcounter, maxcount, waitnow, cname, e)
4340 volatile unsigned int *pcounter;
4341 unsigned int maxcount;
4346 if (maxcount <= 0) /* no limit */
4349 if (++(*pcounter) >= maxcount)
4354 if (*pcounter == maxcount && LogLevel > 5)
4356 sm_syslog(LOG_INFO, e->e_id,
4357 "%s: possible SMTP attack: command=%.40s, count=%u",
4358 CurSmtpClient, cname, *pcounter);
4360 shift = *pcounter - maxcount;
4362 if (shift > MAXSHIFT || s >= MAXTIMEOUT || s <= 0)
4365 #define IS_ATTACK(s) ((MaxChildren > 0 && *pcounter >= maxcount * 2) \
4366 ? STOP_ATTACK : (time_t) s)
4368 /* sleep at least 1 second before returning */
4369 (void) sleep(*pcounter / maxcount);
4370 s -= *pcounter / maxcount;
4371 if (s >= MAXTIMEOUT || s < 0)
4373 if (waitnow && s > 0)
4376 return IS_ATTACK(0);
4378 return IS_ATTACK(s);
4383 ** SETUP_SMTPD_IO -- setup I/O fd correctly for the SMTP server
4392 ** may change I/O fd.
4398 int inchfd, outchfd, outfd;
4400 inchfd = sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL);
4401 outchfd = sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL);
4402 outfd = sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL);
4403 if (outchfd != outfd)
4405 /* arrange for debugging output to go to remote host */
4406 (void) dup2(outchfd, outfd);
4410 ** if InChannel and OutChannel are stdin/stdout
4411 ** and connected to ttys
4412 ** and fcntl(STDIN, F_SETFL, O_NONBLOCKING) also changes STDOUT,
4413 ** then "chain" them together.
4416 if (inchfd == STDIN_FILENO && outchfd == STDOUT_FILENO &&
4417 isatty(inchfd) && isatty(outchfd))
4419 int inmode, outmode;
4421 inmode = fcntl(inchfd, F_GETFL, 0);
4425 sm_syslog(LOG_INFO, NOQID,
4426 "fcntl(inchfd, F_GETFL) failed: %s",
4427 sm_errstring(errno));
4430 outmode = fcntl(outchfd, F_GETFL, 0);
4434 sm_syslog(LOG_INFO, NOQID,
4435 "fcntl(outchfd, F_GETFL) failed: %s",
4436 sm_errstring(errno));
4439 if (bitset(O_NONBLOCK, inmode) ||
4440 bitset(O_NONBLOCK, outmode) ||
4441 fcntl(inchfd, F_SETFL, inmode | O_NONBLOCK) == -1)
4443 outmode = fcntl(outchfd, F_GETFL, 0);
4444 if (outmode != -1 && bitset(O_NONBLOCK, outmode))
4446 /* changing InChannel also changes OutChannel */
4447 sm_io_automode(OutChannel, InChannel);
4448 if (tTd(97, 4) && LogLevel > 9)
4449 sm_syslog(LOG_INFO, NOQID,
4450 "set automode for I (%d)/O (%d) in SMTP server",
4454 /* undo change of inchfd */
4455 (void) fcntl(inchfd, F_SETFL, inmode);
4459 ** SKIPWORD -- skip a fixed word.
4462 ** p -- place to start looking.
4463 ** w -- word to skip.
4470 ** clobbers the p data area.
4475 register char *volatile p;
4481 /* find beginning of word */
4485 /* find end of word */
4486 while (*p != '\0' && *p != ':' && !(isascii(*p) && isspace(*p)))
4488 while (isascii(*p) && isspace(*p))
4493 usrerr("501 5.5.2 Syntax error in parameters scanning \"%s\"",
4494 shortenstring(firstp, MAXSHORTSTR));
4503 /* see if the input word matches desired word */
4504 if (sm_strcasecmp(q, w))
4511 ** RESET_MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
4514 ** e -- the envelope.
4521 reset_mail_esmtp_args(e)
4524 /* "size": no reset */
4527 SevenBitInput = SevenBitInput_Saved;
4528 e->e_bodytype = NULL;
4532 macdefine(&e->e_macro, A_PERM, macid("{dsn_envid}"), NULL);
4535 e->e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
4536 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), NULL);
4540 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"), NULL);
4541 e->e_auth_param = "";
4542 # if _FFR_AUTH_PASSING
4543 macdefine(&BlankEnvelope.e_macro, A_PERM,
4544 macid("{auth_author}"), NULL);
4545 # endif /* _FFR_AUTH_PASSING */
4549 e->e_deliver_by = 0;
4554 ** MAIL_ESMTP_ARGS -- process ESMTP arguments from MAIL line
4557 ** a -- address (unused, for compatibility with rcpt_esmtp_args)
4558 ** kp -- the parameter key.
4559 ** vp -- the value of that parameter.
4560 ** e -- the envelope.
4567 mail_esmtp_args(a, kp, vp, e)
4573 if (sm_strcasecmp(kp, "size") == 0)
4577 usrerr("501 5.5.2 SIZE requires a value");
4580 macdefine(&e->e_macro, A_TEMP, macid("{msg_size}"), vp);
4582 e->e_msgsize = strtol(vp, (char **) NULL, 10);
4583 if (e->e_msgsize == LONG_MAX && errno == ERANGE)
4585 usrerr("552 5.2.3 Message size exceeds maximum value");
4588 if (e->e_msgsize < 0)
4590 usrerr("552 5.2.3 Message size invalid");
4594 else if (sm_strcasecmp(kp, "body") == 0)
4598 usrerr("501 5.5.2 BODY requires a value");
4601 else if (sm_strcasecmp(vp, "8bitmime") == 0)
4603 SevenBitInput = false;
4605 else if (sm_strcasecmp(vp, "7bit") == 0)
4607 SevenBitInput = true;
4611 usrerr("501 5.5.4 Unknown BODY type %s", vp);
4614 e->e_bodytype = sm_rpool_strdup_x(e->e_rpool, vp);
4616 else if (sm_strcasecmp(kp, "envid") == 0)
4618 if (!bitset(SRV_OFFER_DSN, e->e_features))
4620 usrerr("504 5.7.0 Sorry, ENVID not supported, we do not allow DSN");
4625 usrerr("501 5.5.2 ENVID requires a value");
4630 usrerr("501 5.5.4 Syntax error in ENVID parameter value");
4633 if (e->e_envid != NULL)
4635 usrerr("501 5.5.0 Duplicate ENVID parameter");
4638 e->e_envid = sm_rpool_strdup_x(e->e_rpool, vp);
4639 macdefine(&e->e_macro, A_PERM,
4640 macid("{dsn_envid}"), e->e_envid);
4642 else if (sm_strcasecmp(kp, "ret") == 0)
4644 if (!bitset(SRV_OFFER_DSN, e->e_features))
4646 usrerr("504 5.7.0 Sorry, RET not supported, we do not allow DSN");
4651 usrerr("501 5.5.2 RET requires a value");
4654 if (bitset(EF_RET_PARAM, e->e_flags))
4656 usrerr("501 5.5.0 Duplicate RET parameter");
4659 e->e_flags |= EF_RET_PARAM;
4660 if (sm_strcasecmp(vp, "hdrs") == 0)
4661 e->e_flags |= EF_NO_BODY_RETN;
4662 else if (sm_strcasecmp(vp, "full") != 0)
4664 usrerr("501 5.5.2 Bad argument \"%s\" to RET", vp);
4667 macdefine(&e->e_macro, A_TEMP, macid("{dsn_ret}"), vp);
4670 else if (sm_strcasecmp(kp, "auth") == 0)
4674 char *auth_param; /* the value of the AUTH=x */
4675 bool saveQuickAbort = QuickAbort;
4676 bool saveSuprErrs = SuprErrs;
4677 bool saveExitStat = ExitStat;
4681 usrerr("501 5.5.2 AUTH= requires a value");
4684 if (e->e_auth_param != NULL)
4686 usrerr("501 5.5.0 Duplicate AUTH parameter");
4689 if ((q = strchr(vp, ' ')) != NULL)
4692 len = strlen(vp) + 1;
4693 auth_param = xalloc(len);
4694 (void) sm_strlcpy(auth_param, vp, len);
4695 if (!xtextok(auth_param))
4697 usrerr("501 5.5.4 Syntax error in AUTH parameter value");
4698 /* just a warning? */
4702 /* XXX define this always or only if trusted? */
4703 macdefine(&e->e_macro, A_TEMP, macid("{auth_author}"),
4707 ** call Strust_auth to find out whether
4708 ** auth_param is acceptable (trusted)
4709 ** we shouldn't trust it if not authenticated
4710 ** (required by RFC, leave it to ruleset?)
4715 if (strcmp(auth_param, "<>") != 0 &&
4716 (rscheck("trust_auth", auth_param, NULL, e, RSF_RMCOMM, 9,
4717 NULL, NOQID, NULL, NULL) != EX_OK || Errors > 0))
4721 q = e->e_auth_param;
4722 sm_dprintf("auth=\"%.100s\" not trusted user=\"%.100s\"\n",
4723 auth_param, (q == NULL) ? "" : q);
4727 e->e_auth_param = "<>";
4728 # if _FFR_AUTH_PASSING
4729 macdefine(&BlankEnvelope.e_macro, A_PERM,
4730 macid("{auth_author}"), NULL);
4731 # endif /* _FFR_AUTH_PASSING */
4736 sm_dprintf("auth=\"%.100s\" trusted\n", auth_param);
4737 e->e_auth_param = sm_rpool_strdup_x(e->e_rpool,
4740 sm_free(auth_param); /* XXX */
4744 QuickAbort = saveQuickAbort;
4745 SuprErrs = saveSuprErrs;
4746 ExitStat = saveExitStat;
4749 #define PRTCHAR(c) ((isascii(c) && isprint(c)) ? (c) : '?')
4752 ** "by" is only accepted if DeliverByMin >= 0.
4753 ** We maybe could add this to the list of server_features.
4756 else if (sm_strcasecmp(kp, "by") == 0 && DeliverByMin >= 0)
4762 usrerr("501 5.5.2 BY= requires a value");
4766 e->e_deliver_by = strtol(vp, &s, 10);
4767 if (e->e_deliver_by == LONG_MIN ||
4768 e->e_deliver_by == LONG_MAX ||
4769 e->e_deliver_by > 999999999l ||
4770 e->e_deliver_by < -999999999l)
4772 usrerr("501 5.5.2 BY=%s out of range", vp);
4775 if (s == NULL || *s != ';')
4777 usrerr("501 5.5.2 BY= missing ';'");
4781 ++s; /* XXX: spaces allowed? */
4783 switch (tolower(*s))
4786 e->e_dlvr_flag = DLVR_NOTIFY;
4789 e->e_dlvr_flag = DLVR_RETURN;
4790 if (e->e_deliver_by <= 0)
4792 usrerr("501 5.5.4 mode R requires BY time > 0");
4795 if (DeliverByMin > 0 && e->e_deliver_by > 0 &&
4796 e->e_deliver_by < DeliverByMin)
4798 usrerr("555 5.5.2 time %ld less than %ld",
4799 e->e_deliver_by, (long) DeliverByMin);
4804 usrerr("501 5.5.2 illegal by-mode '%c'", PRTCHAR(*s));
4807 ++s; /* XXX: spaces allowed? */
4809 switch (tolower(*s))
4812 e->e_dlvr_flag |= DLVR_TRACE;
4817 usrerr("501 5.5.2 illegal by-trace '%c'", PRTCHAR(*s));
4821 /* XXX: check whether more characters follow? */
4825 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4831 ** RCPT_ESMTP_ARGS -- process ESMTP arguments from RCPT line
4834 ** a -- the address corresponding to the To: parameter.
4835 ** kp -- the parameter key.
4836 ** vp -- the value of that parameter.
4837 ** e -- the envelope.
4844 rcpt_esmtp_args(a, kp, vp, e)
4850 if (sm_strcasecmp(kp, "notify") == 0)
4854 if (!bitset(SRV_OFFER_DSN, e->e_features))
4856 usrerr("504 5.7.0 Sorry, NOTIFY not supported, we do not allow DSN");
4861 usrerr("501 5.5.2 NOTIFY requires a value");
4864 a->q_flags &= ~(QPINGONSUCCESS|QPINGONFAILURE|QPINGONDELAY);
4865 a->q_flags |= QHASNOTIFY;
4866 macdefine(&e->e_macro, A_TEMP, macid("{dsn_notify}"), vp);
4868 if (sm_strcasecmp(vp, "never") == 0)
4870 for (p = vp; p != NULL; vp = p)
4874 s = p = strchr(p, ',');
4877 if (sm_strcasecmp(vp, "success") == 0)
4878 a->q_flags |= QPINGONSUCCESS;
4879 else if (sm_strcasecmp(vp, "failure") == 0)
4880 a->q_flags |= QPINGONFAILURE;
4881 else if (sm_strcasecmp(vp, "delay") == 0)
4882 a->q_flags |= QPINGONDELAY;
4885 usrerr("501 5.5.4 Bad argument \"%s\" to NOTIFY",
4893 else if (sm_strcasecmp(kp, "orcpt") == 0)
4897 if (!bitset(SRV_OFFER_DSN, e->e_features))
4899 usrerr("504 5.7.0 Sorry, ORCPT not supported, we do not allow DSN");
4904 usrerr("501 5.5.2 ORCPT requires a value");
4907 if (a->q_orcpt != NULL)
4909 usrerr("501 5.5.0 Duplicate ORCPT parameter");
4912 p = strchr(vp, ';');
4915 usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4919 if (!isatom(vp) || !xtextok(p + 1))
4922 usrerr("501 5.5.4 Syntax error in ORCPT parameter value");
4926 a->q_orcpt = sm_rpool_strdup_x(e->e_rpool, vp);
4930 usrerr("555 5.5.4 %s parameter unrecognized", kp);
4935 ** PRINTVRFYADDR -- print an entry in the verify queue
4938 ** a -- the address to print.
4939 ** last -- set if this is the last one.
4940 ** vrfy -- set if this is a VRFY command.
4946 ** Prints the appropriate 250 codes.
4948 #define OFFF (3 + 1 + 5 + 1) /* offset in fmt: SMTP reply + enh. code */
4951 printvrfyaddr(a, last, vrfy)
4952 register ADDRESS *a;
4958 if (vrfy && a->q_mailer != NULL &&
4959 !bitnset(M_VRFY250, a->q_mailer->m_flags))
4960 (void) sm_strlcpy(fmtbuf, "252", sizeof(fmtbuf));
4962 (void) sm_strlcpy(fmtbuf, "250", sizeof(fmtbuf));
4963 fmtbuf[3] = last ? ' ' : '-';
4964 (void) sm_strlcpy(&fmtbuf[4], "2.1.5 ", sizeof(fmtbuf) - 4);
4965 if (a->q_fullname == NULL)
4967 if ((a->q_mailer == NULL ||
4968 a->q_mailer->m_addrtype == NULL ||
4969 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4970 strchr(a->q_user, '@') == NULL)
4971 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s@%s>",
4972 sizeof(fmtbuf) - OFFF);
4974 (void) sm_strlcpy(&fmtbuf[OFFF], "<%s>",
4975 sizeof(fmtbuf) - OFFF);
4976 message(fmtbuf, a->q_user, MyHostName);
4980 if ((a->q_mailer == NULL ||
4981 a->q_mailer->m_addrtype == NULL ||
4982 sm_strcasecmp(a->q_mailer->m_addrtype, "rfc822") == 0) &&
4983 strchr(a->q_user, '@') == NULL)
4984 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s@%s>",
4985 sizeof(fmtbuf) - OFFF);
4987 (void) sm_strlcpy(&fmtbuf[OFFF], "%s <%s>",
4988 sizeof(fmtbuf) - OFFF);
4989 message(fmtbuf, a->q_fullname, a->q_user, MyHostName);
4995 ** SASLMECHS -- get list of possible AUTH mechanisms
4998 ** conn -- SASL connection info.
4999 ** mechlist -- output parameter for list of mechanisms.
5006 saslmechs(conn, mechlist)
5010 int len, num, result;
5012 /* "user" is currently unused */
5014 result = sasl_listmech(conn, NULL,
5015 "", " ", "", (const char **) mechlist,
5016 (unsigned int *)&len, &num);
5017 # else /* SASL >= 20000 */
5018 result = sasl_listmech(conn, "user", /* XXX */
5019 "", " ", "", mechlist,
5020 (unsigned int *)&len, (unsigned int *)&num);
5021 # endif /* SASL >= 20000 */
5022 if (result != SASL_OK)
5025 sm_syslog(LOG_WARNING, NOQID,
5026 "AUTH error: listmech=%d, num=%d",
5033 sm_syslog(LOG_INFO, NOQID,
5034 "AUTH: available mech=%s, allowed mech=%s",
5035 *mechlist, AuthMechanisms);
5036 *mechlist = intersect(AuthMechanisms, *mechlist, NULL);
5040 *mechlist = NULL; /* be paranoid... */
5041 if (result == SASL_OK && LogLevel > 9)
5042 sm_syslog(LOG_WARNING, NOQID,
5043 "AUTH warning: no mechanisms");
5050 ** PROXY_POLICY -- define proxy policy for AUTH
5054 ** context -- unused.
5055 ** requested_user -- authorization identity.
5056 ** rlen -- authorization identity length.
5057 ** auth_identity -- authentication identity.
5058 ** alen -- authentication identity length.
5059 ** def_realm -- default user realm.
5060 ** urlen -- user realm length.
5061 ** propctx -- unused.
5067 ** sets {auth_authen} macro.
5071 proxy_policy(conn, context, requested_user, rlen, auth_identity, alen,
5072 def_realm, urlen, propctx)
5075 const char *requested_user;
5077 const char *auth_identity;
5079 const char *def_realm;
5081 struct propctx *propctx;
5083 if (auth_identity == NULL)
5086 macdefine(&BlankEnvelope.e_macro, A_TEMP,
5087 macid("{auth_authen}"),
5088 xtextify((char *) auth_identity, "=<>\")"));
5092 # else /* SASL >= 20000 */
5095 ** PROXY_POLICY -- define proxy policy for AUTH
5098 ** context -- unused.
5099 ** auth_identity -- authentication identity.
5100 ** requested_user -- authorization identity.
5101 ** user -- allowed user (output).
5102 ** errstr -- possible error string (output).
5109 proxy_policy(context, auth_identity, requested_user, user, errstr)
5111 const char *auth_identity;
5112 const char *requested_user;
5114 const char **errstr;
5116 if (user == NULL || auth_identity == NULL)
5118 *user = newstr(auth_identity);
5121 # endif /* SASL >= 20000 */
5126 ** INITSRVTLS -- initialize server side TLS
5129 ** tls_ok -- should tls initialization be done?
5135 ** sets tls_ok_srv which is a static variable in this module.
5136 ** Do NOT remove assignments to it!
5146 /* do NOT remove assignment */
5147 tls_ok_srv = inittls(&srv_ctx, TLS_Srv_Opts, Srv_SSL_Options, true,
5148 SrvCertFile, SrvKeyFile,
5149 CACertPath, CACertFile, DHParams);
5152 #endif /* STARTTLS */
5154 ** SRVFEATURES -- get features for SMTP server
5157 ** e -- envelope (should be session context).
5158 ** clientname -- name of client.
5159 ** features -- default features for this invocation.
5165 /* table with options: it uses just one character, how about strings? */
5169 unsigned int srvf_flag;
5170 } srv_feat_table[] =
5172 { 'A', SRV_OFFER_AUTH },
5173 { 'B', SRV_OFFER_VERB },
5174 { 'C', SRV_REQ_SEC },
5175 { 'D', SRV_OFFER_DSN },
5176 { 'E', SRV_OFFER_ETRN },
5177 { 'L', SRV_REQ_AUTH },
5180 { 'N', SRV_NO_PIPE },
5181 # endif /* _FFR_NO_PIPE */
5182 { 'P', SRV_OFFER_PIPE },
5183 #endif /* PIPELINING */
5184 { 'R', SRV_VRFY_CLT }, /* same as V; not documented */
5185 { 'S', SRV_OFFER_TLS },
5186 /* { 'T', SRV_TMP_FAIL }, */
5187 { 'V', SRV_VRFY_CLT },
5188 { 'X', SRV_OFFER_EXPN },
5189 /* { 'Y', SRV_OFFER_VRFY }, */
5194 srvfeatures(e, clientname, features)
5197 unsigned int features;
5201 char pvpbuf[PSBUFSIZE];
5204 r = rscap("srv_features", clientname, "", e, &pvp, pvpbuf,
5208 if (pvp == NULL || pvp[0] == NULL || (pvp[0][0] & 0377) != CANONNET)
5210 if (pvp[1] != NULL && sm_strncasecmp(pvp[1], "temp", 4) == 0)
5211 return SRV_TMP_FAIL;
5214 ** General rule (see sendmail.h, d_flags):
5215 ** lower case: required/offered, upper case: Not required/available
5217 ** Since we can change some features per daemon, we have both
5218 ** cases here: turn on/off a feature.
5221 for (i = 1; pvp[i] != NULL; i++)
5227 if ((opt = srv_feat_table[j].srvf_opt) == '\0')
5230 sm_syslog(LOG_WARNING, e->e_id,
5231 "srvfeatures: unknown feature %s",
5237 features &= ~(srv_feat_table[j].srvf_flag);
5240 if (c == tolower(opt))
5242 features |= srv_feat_table[j].srvf_flag;
5252 ** HELP -- implement the HELP command.
5255 ** topic -- the topic we want help for.
5262 ** outputs the help file to message output.
5264 #define HELPVSTR "#vers "
5265 #define HELPVERSION 2
5272 register SM_FILE_T *hf;
5277 long sff = SFF_OPENASROOT|SFF_REGONLY;
5280 static int foundvers = -1;
5281 extern char Version[];
5283 if (DontLockReadFiles)
5285 if (!bitnset(DBS_HELPFILEINUNSAFEDIRPATH, DontBlameSendmail))
5286 sff |= SFF_SAFEDIRPATH;
5288 if (HelpFile == NULL ||
5289 (hf = safefopen(HelpFile, O_RDONLY, 0444, sff)) == NULL)
5293 message("502 5.3.0 Sendmail %s -- HELP not implemented",
5298 if (topic == NULL || *topic == '\0')
5309 len = strlen(topic);
5311 while (sm_io_fgets(hf, SM_TIME_DEFAULT, buf, sizeof(buf)) >= 0)
5315 if (foundvers < 0 &&
5316 strncmp(buf, HELPVSTR, strlen(HELPVSTR)) == 0)
5320 if (sm_io_sscanf(buf + strlen(HELPVSTR), "%d",
5326 if (strncmp(buf, topic, len) == 0)
5332 /* print version if no/old vers# in file */
5333 if (foundvers < 2 && !noinfo)
5334 message("214-2.0.0 This is Sendmail version %s", Version);
5336 p = strpbrk(buf, " \t");
5338 p = buf + strlen(buf) - 1;
5345 int lbs = sizeof(buf) - (p - buf);
5347 lbp = translate_dollars(p, p, &lbs);
5348 expand(lbp, inp, sizeof(inp), e);
5353 message("214-2.0.0 %s", p);
5359 message("504 5.3.0 HELP topic \"%.10s\" unknown", topic);
5361 message("214 2.0.0 End of HELP info");
5363 if (foundvers != 0 && foundvers < HELPVERSION)
5366 sm_syslog(LOG_WARNING, e->e_id,
5367 "%s too old (require version %d)",
5368 HelpFile, HELPVERSION);
5370 /* avoid log next time */
5374 (void) sm_io_close(hf, SM_TIME_DEFAULT);
5379 ** RESET_SASLCONN -- reset SASL connection data
5382 ** conn -- SASL connection context
5383 ** hostname -- host name
5384 ** various connection data
5391 reset_saslconn(sasl_conn_t **conn, char *hostname,
5393 char *remoteip, char *localip,
5394 char *auth_id, sasl_ssf_t * ext_ssf)
5395 # else /* SASL >= 20000 */
5396 struct sockaddr_in *saddr_r, struct sockaddr_in *saddr_l,
5397 sasl_external_properties_t * ext_ssf)
5398 # endif /* SASL >= 20000 */
5404 result = sasl_server_new("smtp", hostname, NULL, NULL, NULL,
5407 /* use empty realm: only works in SASL > 1.5.5 */
5408 result = sasl_server_new("smtp", hostname, "", NULL, 0, conn);
5409 # else /* SASL >= 20000 */
5410 /* use no realm -> realm is set to hostname by SASL lib */
5411 result = sasl_server_new("smtp", hostname, NULL, NULL, 0,
5413 # endif /* SASL >= 20000 */
5414 if (result != SASL_OK)
5418 # if NETINET || NETINET6
5419 if (remoteip != NULL && *remoteip != '\0')
5420 result = sasl_setprop(*conn, SASL_IPREMOTEPORT, remoteip);
5421 if (result != SASL_OK)
5424 if (localip != NULL && *localip != '\0')
5425 result = sasl_setprop(*conn, SASL_IPLOCALPORT, localip);
5426 if (result != SASL_OK)
5428 # endif /* NETINET || NETINET6 */
5430 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
5431 if (result != SASL_OK)
5434 result = sasl_setprop(*conn, SASL_AUTH_EXTERNAL, auth_id);
5435 if (result != SASL_OK)
5437 # else /* SASL >= 20000 */
5439 if (saddr_r != NULL)
5440 result = sasl_setprop(*conn, SASL_IP_REMOTE, saddr_r);
5441 if (result != SASL_OK)
5444 if (saddr_l != NULL)
5445 result = sasl_setprop(*conn, SASL_IP_LOCAL, saddr_l);
5446 if (result != SASL_OK)
5448 # endif /* NETINET */
5450 result = sasl_setprop(*conn, SASL_SSF_EXTERNAL, ext_ssf);
5451 if (result != SASL_OK)
5453 # endif /* SASL >= 20000 */