xref: /netbsd-src/external/ibm-public/postfix/dist/src/smtpstone/smtp-sink.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: smtp-sink.c,v 1.1.1.4 2013/09/25 19:06:36 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	smtp-sink 1
6 /* SUMMARY
7 /*	multi-threaded SMTP/LMTP test server
8 /* SYNOPSIS
9 /* .fi
10 /*	\fBsmtp-sink\fR [\fIoptions\fR] [\fBinet:\fR][\fIhost\fR]:\fIport\fR
11 /*	\fIbacklog\fR
12 /*
13 /*	\fBsmtp-sink\fR [\fIoptions\fR] \fBunix:\fR\fIpathname\fR \fIbacklog\fR
14 /* DESCRIPTION
15 /*	\fBsmtp-sink\fR listens on the named host (or address) and port.
16 /*	It takes SMTP messages from the network and throws them away.
17 /*	The purpose is to measure client performance, not protocol
18 /*	compliance.
19 /*
20 /*	\fBsmtp-sink\fR may also be configured to capture each mail
21 /*	delivery transaction to file. Since disk latencies are large
22 /*	compared to network delays, this mode of operation can
23 /*	reduce the maximal performance by several orders of magnitude.
24 /*
25 /*	Connections can be accepted on IPv4 or IPv6 endpoints, or on
26 /*	UNIX-domain sockets.
27 /*	IPv4 and IPv6 are the default.
28 /*	This program is the complement of the \fBsmtp-source\fR(1) program.
29 /*
30 /*	Note: this is an unsupported test program. No attempt is made
31 /*	to maintain compatibility between successive versions.
32 /*
33 /*	Arguments:
34 /* .IP \fB-4\fR
35 /*	Support IPv4 only. This option has no effect when
36 /*	Postfix is built without IPv6 support.
37 /* .IP \fB-6\fR
38 /*	Support IPv6 only. This option is not available when
39 /*	Postfix is built without IPv6 support.
40 /* .IP \fB-8\fR
41 /*	Do not announce 8BITMIME support.
42 /* .IP \fB-a\fR
43 /*	Do not announce SASL authentication support.
44 /* .IP "\fB-A \fIdelay\fR"
45 /*	Wait \fIdelay\fR seconds after responding to DATA, then
46 /*	abort prematurely with a 550 reply status.  Do not read
47 /*	further input from the client; this is an attempt to block
48 /*	the client before it sends ".".  Specify a zero delay value
49 /*	to abort immediately.
50 /* .IP "\fB-b \fIsoft-bounce-reply\fR"
51 /*	Use \fIsoft-bounce-reply\fR for soft reject responses.  The
52 /*	default reply is "450 4.3.0 Error: command failed".
53 /* .IP "\fB-B \fIhard-bounce-reply\fR"
54 /*	Use \fIhard-bounce-reply\fR for hard reject responses.  The
55 /*	default reply is "500 5.3.0 Error: command failed".
56 /* .IP \fB-c\fR
57 /*	Display running counters that are updated whenever an SMTP
58 /*	session ends, a QUIT command is executed, or when "." is
59 /*	received.
60 /* .IP \fB-C\fR
61 /*	Disable XCLIENT support.
62 /* .IP "\fB-d \fIdump-template\fR"
63 /*	Dump each mail transaction to a single-message file whose
64 /*	name is created by expanding the \fIdump-template\fR via
65 /*	strftime(3) and appending a pseudo-random hexadecimal number
66 /*	(example: "%Y%m%d%H/%M." expands into "2006081203/05.809a62e3").
67 /*	If the template contains "/" characters, missing directories
68 /*	are created automatically.  The message dump format is
69 /*	described below.
70 /* .sp
71 /*	Note: this option keeps one capture file open for every
72 /*	mail transaction in progress.
73 /* .IP "\fB-D \fIdump-template\fR"
74 /*	Append mail transactions to a multi-message dump file whose
75 /*	name is created by expanding the \fIdump-template\fR via
76 /*	strftime(3).
77 /*	If the template contains "/" characters, missing directories
78 /*	are created automatically.  The message dump format is
79 /*	described below.
80 /* .sp
81 /*	Note: this option keeps one capture file open for every
82 /*	mail transaction in progress.
83 /* .IP \fB-e\fR
84 /*	Do not announce ESMTP support.
85 /* .IP \fB-E\fR
86 /*	Do not announce ENHANCEDSTATUSCODES support.
87 /* .IP "\fB-f \fIcommand,command,...\fR"
88 /*	Reject the specified commands with a hard (5xx) error code.
89 /*	This option implies \fB-p\fR.
90 /* .sp
91 /*	Examples of commands are CONNECT, HELO, EHLO, LHLO, MAIL, RCPT, VRFY,
92 /*	DATA, ., RSET, NOOP, and QUIT. Separate command names by
93 /*	white space or commas, and use quotes to protect white space
94 /*	from the shell. Command names are case-insensitive.
95 /* .IP \fB-F\fR
96 /*	Disable XFORWARD support.
97 /* .IP "\fB-h\fI hostname\fR"
98 /*	Use \fIhostname\fR in the SMTP greeting, in the HELO response,
99 /*	and in the EHLO response. The default hostname is "smtp-sink".
100 /* .IP \fB-L\fR
101 /*	Enable LMTP instead of SMTP.
102 /* .IP "\fB-m \fIcount\fR (default: 256)"
103 /*	An upper bound on the maximal number of simultaneous
104 /*	connections that \fBsmtp-sink\fR will handle. This prevents
105 /*	the process from running out of file descriptors. Excess
106 /*	connections will stay queued in the TCP/IP stack.
107 /* .IP "\fB-M \fIcount\fR"
108 /*	Terminate after receiving \fIcount\fR messages.
109 /* .IP "\fB-n \fIcount\fR"
110 /*	Terminate after \fIcount\fR sessions.
111 /* .IP \fB-p\fR
112 /*	Do not announce support for ESMTP command pipelining.
113 /* .IP \fB-P\fR
114 /*	Change the server greeting so that it appears to come through
115 /*	a CISCO PIX system. Implies \fB-e\fR.
116 /* .IP "\fB-q \fIcommand,command,...\fR"
117 /*	Disconnect (without replying) after receiving one of the
118 /*	specified commands.
119 /* .sp
120 /*	Examples of commands are CONNECT, HELO, EHLO, LHLO, MAIL, RCPT, VRFY,
121 /*	DATA, ., RSET, NOOP, and QUIT. Separate command names by
122 /*	white space or commas, and use quotes to protect white space
123 /*	from the shell. Command names are case-insensitive.
124 /* .IP "\fB-Q \fIcommand,command,...\fR"
125 /*	Send a 421 reply and disconnect after receiving one
126 /*	of the specified commands.
127 /* .sp
128 /*	Examples of commands are CONNECT, HELO, EHLO, LHLO, MAIL, RCPT, VRFY,
129 /*	DATA, ., RSET, NOOP, and QUIT. Separate command names by
130 /*	white space or commas, and use quotes to protect white space
131 /*	from the shell. Command names are case-insensitive.
132 /* .IP "\fB-r \fIcommand,command,...\fR"
133 /*	Reject the specified commands with a soft (4xx) error code.
134 /*	This option implies \fB-p\fR.
135 /* .sp
136 /*	Examples of commands are CONNECT, HELO, EHLO, LHLO, MAIL, RCPT, VRFY,
137 /*	DATA, ., RSET, NOOP, and QUIT. Separate command names by
138 /*	white space or commas, and use quotes to protect white space
139 /*	from the shell. Command names are case-insensitive.
140 /* .IP "\fB-R \fIroot-directory\fR"
141 /*	Change the process root directory to the specified location.
142 /*	This option requires super-user privileges. See also the
143 /*	\fB-u\fR option.
144 /* .IP "\fB-s \fIcommand,command,...\fR"
145 /*	Log the named commands to syslogd.
146 /* .sp
147 /*	Examples of commands are CONNECT, HELO, EHLO, LHLO, MAIL, RCPT, VRFY,
148 /*	DATA, ., RSET, NOOP, and QUIT. Separate command names by
149 /*	white space or commas, and use quotes to protect white space
150 /*	from the shell. Command names are case-insensitive.
151 /* .IP "\fB-S start-string\fR"
152 /*	An optional string that is prepended to each message that is
153 /*	written to a dump file (see the dump file format description
154 /*	below). The following C escape sequences are supported: \ea
155 /*	(bell), \eb (backslace), \ef (formfeed), \en (newline), \er
156 /*	(carriage return), \et (horizontal tab), \ev (vertical tab),
157 /*	\e\fIddd\fR (up to three octal digits) and \e\e (the backslash
158 /*	character).
159 /* .IP "\fB-t \fItimeout\fR (default: 100)"
160 /*	Limit the time for receiving a command or sending a response.
161 /*	The time limit is specified in seconds.
162 /* .IP "\fB-T \fIwindowsize\fR"
163 /*	Override the default TCP window size. To work around
164 /*	broken TCP window scaling implementations, specify a
165 /*	value > 0 and < 65536.
166 /* .IP "\fB-u \fIusername\fR"
167 /*	Switch to the specified user privileges after opening the
168 /*	network socket and optionally changing the process root
169 /*	directory. This option is required when the process runs
170 /*	with super-user privileges. See also the \fB-R\fR option.
171 /* .IP \fB-v\fR
172 /*	Show the SMTP conversations.
173 /* .IP "\fB-w \fIdelay\fR"
174 /*	Wait \fIdelay\fR seconds before responding to a DATA command.
175 /* .IP "\fB-W \fIcommand:delay[:odds]\fR"
176 /*	Wait \fIdelay\fR seconds before responding to \fIcommand\fR.
177 /*	If \fIodds\fR is also specified (a number between 1-99
178 /*	inclusive), wait for a random multiple of \fIdelay\fR. The
179 /*	random multiplier is equal to the number of times the program
180 /*	needs to roll a dice with a range of 0..99 inclusive, before
181 /*	the dice produces a result greater than or equal to \fIodds\fR.
182 /* .IP [\fBinet:\fR][\fIhost\fR]:\fIport\fR
183 /*	Listen on network interface \fIhost\fR (default: any interface)
184 /*	TCP port \fIport\fR. Both \fIhost\fR and \fIport\fR may be
185 /*	specified in numeric or symbolic form.
186 /* .IP \fBunix:\fR\fIpathname\fR
187 /*	Listen on the UNIX-domain socket at \fIpathname\fR.
188 /* .IP \fIbacklog\fR
189 /*	The maximum length the queue of pending connections,
190 /*	as defined by the \fBlisten\fR(2) system call.
191 /* DUMP FILE FORMAT
192 /* .ad
193 /* .fi
194 /*	Each dumped message contains a sequence of text lines,
195 /*	terminated with the newline character. The sequence of
196 /*	information is as follows:
197 /* .IP \(bu
198 /*	The optional string specified with the \fB-S\fR option.
199 /* .IP \(bu
200 /*	The \fBsmtp-sink\fR generated headers as documented below.
201 /* .IP \(bu
202 /*	The message header and body as received from the SMTP client.
203 /* .IP \(bu
204 /*	An empty line.
205 /* .PP
206 /*	The format of the \fBsmtp-sink\fR generated headers is as
207 /*	follows:
208 /* .IP "\fBX-Client-Addr: \fItext\fR"
209 /*	The client IP address without enclosing []. An IPv6 address
210 /*	is prefixed with "ipv6:". This record is always present.
211 /* .IP "\fBX-Client-Proto: \fItext\fR"
212 /*	The client protocol: SMTP, ESMTP or LMTP. This record is
213 /*	always present.
214 /* .IP "\fBX-Helo-Args: \fItext\fR"
215 /*	The arguments of the last HELO or EHLO command before this
216 /*	mail delivery transaction. This record is present only if
217 /*	the client sent a recognizable HELO or EHLO command before
218 /*	the DATA command.
219 /* .IP "\fBX-Mail-Args: \fItext\fR"
220 /*	The arguments of the MAIL command that started this mail
221 /*	delivery transaction. This record is present exactly once.
222 /* .IP "\fBX-Rcpt-Args: \fItext\fR"
223 /*	The arguments of an RCPT command within this mail delivery
224 /*	transaction. There is one record for each RCPT command, and
225 /*	they are in the order as sent by the client.
226 /* .IP "\fBReceived: \fItext\fR"
227 /*	A message header for compatibility with mail processing
228 /*	software. This three-line header marks the end of the headers
229 /*	provided by \fBsmtp-sink\fR, and is formatted as follows:
230 /* .RS
231 /* .IP "\fBfrom \fIhelo\fB ([\fIaddr\fB])\fR"
232 /*	The HELO or EHLO command argument and client IP address.
233 /*	If the client did not send HELO or EHLO, the client IP
234 /*	address is used instead.
235 /* .IP "\fBby \fIhost\fB (smtp-sink) with \fIproto\fB id \fIrandom\fB;\fR"
236 /*	The hostname specified with the \fB-h\fR option, the client
237 /*	protocol (see \fBX-Client-Proto\fR above), and the pseudo-random
238 /*	portion of the per-message capture file name.
239 /* .IP \fItime-stamp\fR
240 /*	A time stamp as defined in RFC 2822.
241 /* .RE
242 /* SEE ALSO
243 /*	smtp-source(1), SMTP/LMTP message generator
244 /* LICENSE
245 /* .ad
246 /* .fi
247 /*	The Secure Mailer license must be distributed with this software.
248 /* AUTHOR(S)
249 /*	Wietse Venema
250 /*	IBM T.J. Watson Research
251 /*	P.O. Box 704
252 /*	Yorktown Heights, NY 10598, USA
253 /*--*/
254 
255 /* System library. */
256 
257 #include <sys_defs.h>
258 #include <sys/socket.h>
259 #include <sys/wait.h>
260 #include <sys/stat.h>
261 #include <unistd.h>
262 #include <string.h>
263 #include <stdlib.h>
264 #include <fcntl.h>
265 #include <syslog.h>
266 #include <signal.h>
267 #include <time.h>
268 #include <ctype.h>
269 
270 #ifdef STRCASECMP_IN_STRINGS_H
271 #include <strings.h>
272 #endif
273 
274 /* Utility library. */
275 
276 #include <msg.h>
277 #include <vstring.h>
278 #include <vstream.h>
279 #include <vstring_vstream.h>
280 #include <get_hostname.h>
281 #include <listen.h>
282 #include <events.h>
283 #include <mymalloc.h>
284 #include <iostuff.h>
285 #include <msg_vstream.h>
286 #include <stringops.h>
287 #include <sane_accept.h>
288 #include <inet_proto.h>
289 #include <myaddrinfo.h>
290 #include <make_dirs.h>
291 #include <myrand.h>
292 #include <chroot_uid.h>
293 
294 /* Global library. */
295 
296 #include <smtp_stream.h>
297 #include <mail_date.h>
298 #include <mail_version.h>
299 
300 /* Application-specific. */
301 
302 typedef struct SINK_STATE {
303     VSTREAM *stream;
304     VSTRING *buffer;
305     int     data_state;
306     int     (*read_fn) (struct SINK_STATE *);
307     int     in_mail;
308     int     rcpts;
309     char   *push_back_ptr;
310     /* Capture file information for fake Received: header */
311     MAI_HOSTADDR_STR client_addr;	/* IP address */
312     char   *addr_prefix;		/* ipv6: or empty */
313     char   *helo_args;			/* text after HELO or EHLO */
314     const char *client_proto;		/* SMTP, ESMTP, LMTP */
315     time_t  start_time;			/* MAIL command time */
316     int     id;				/* pseudo-random */
317     VSTREAM *dump_file;			/* dump file or null */
318     void    (*delayed_response) (struct SINK_STATE *state, const char *);
319     char   *delayed_args;
320 } SINK_STATE;
321 
322 #define ST_ANY			0
323 #define ST_CR			1
324 #define ST_CR_LF		2
325 #define ST_CR_LF_DOT		3
326 #define ST_CR_LF_DOT_CR		4
327 #define ST_CR_LF_DOT_CR_LF	5
328 
329 #define PUSH_BACK_PEEK(state)		(*(state)->push_back_ptr != 0)
330 #define PUSH_BACK_GET(state)		(*(state)->push_back_ptr++)
331 #define PUSH_BACK_SET(state, text)	((state)->push_back_ptr = (text))
332 
333 #ifndef DEF_MAX_CLIENT_COUNT
334 #define DEF_MAX_CLIENT_COUNT	256
335 #endif
336 
337 #define SOFT_ERROR_RESP		"450 4.3.0 Error: command failed"
338 #define HARD_ERROR_RESP		"500 5.3.0 Error: command failed"
339 
340  /*
341   * We can't rely on vstream auto-flushing, so we have to prepare for the
342   * next read request.
343   */
344 #define SMTP_FLUSH(fp) do { \
345     if (vstream_peek(fp) <= 0 && readable(vstream_fileno(fp)) <= 0) \
346         smtp_flush(fp); \
347     } while (0)
348 
349 static int var_tmout = 100;
350 static int var_max_line_length = 2048;
351 static char *var_myhostname;
352 static char *soft_error_resp = SOFT_ERROR_RESP;
353 static char *hard_error_resp = HARD_ERROR_RESP;
354 static int command_read(SINK_STATE *);
355 static int data_read(SINK_STATE *);
356 static void disconnect(SINK_STATE *);
357 static void read_timeout(int, char *);
358 static void read_event(int, char *);
359 static int count;
360 static int sess_count;
361 static int quit_count;
362 static int mesg_count;
363 static int max_quit_count;
364 static int max_msg_quit_count;
365 static int disable_pipelining;
366 static int disable_8bitmime;
367 static int disable_esmtp;
368 static int enable_lmtp;
369 static int pretend_pix;
370 static int disable_saslauth;
371 static int disable_xclient;
372 static int disable_xforward;
373 static int disable_enh_status;
374 static int max_client_count = DEF_MAX_CLIENT_COUNT;
375 static int client_count;
376 static int sock;
377 static int abort_delay = -1;
378 
379 static char *single_template;		/* individual template */
380 static char *shared_template;		/* shared template */
381 static VSTRING *start_string;		/* dump content prefix */
382 
383 static INET_PROTO_INFO *proto_info;
384 
385 #define STR(x)	vstring_str(x)
386 
387 /* do_stats - show counters */
388 
389 static void do_stats(void)
390 {
391     vstream_printf("sess=%d quit=%d mesg=%d\r",
392 		   sess_count, quit_count, mesg_count);
393     vstream_fflush(VSTREAM_OUT);
394 }
395 
396 /* hard_err_resp - generic hard error response */
397 
398 static void hard_err_resp(SINK_STATE *state)
399 {
400     smtp_printf(state->stream, "%s", hard_error_resp);
401     SMTP_FLUSH(state->stream);
402 }
403 
404 /* soft_err_resp - generic soft error response */
405 
406 static void soft_err_resp(SINK_STATE *state)
407 {
408     smtp_printf(state->stream, "%s", soft_error_resp);
409     SMTP_FLUSH(state->stream);
410 }
411 
412 /* exp_path_template - expand template pathname, static result */
413 
414 static VSTRING *exp_path_template(const char *template, time_t start_time)
415 {
416     static VSTRING *path_buf = 0;
417     struct tm *lt;
418 
419     if (path_buf == 0)
420 	path_buf = vstring_alloc(100);
421     else
422 	VSTRING_RESET(path_buf);
423     lt = localtime(&start_time);
424     while (strftime(STR(path_buf), vstring_avail(path_buf), template, lt) == 0)
425 	VSTRING_SPACE(path_buf, vstring_avail(path_buf) + 100);
426     VSTRING_SKIP(path_buf);
427     return (path_buf);
428 }
429 
430 /* make_parent_dir - create parent directory or bust */
431 
432 static void make_parent_dir(const char *path, mode_t mode)
433 {
434     const char *parent;
435 
436     parent = sane_dirname((VSTRING *) 0, path);
437     if (make_dirs(parent, mode) < 0)
438 	msg_fatal("mkdir %s: %m", parent);
439 }
440 
441 /* mail_file_open - open mail capture file */
442 
443 static void mail_file_open(SINK_STATE *state)
444 {
445     const char *myname = "mail_file_open";
446     VSTRING *path_buf;
447     ssize_t len;
448     int     tries = 0;
449 
450     /*
451      * Save the start time for later.
452      */
453     time(&(state->start_time));
454 
455     /*
456      * Expand the per-message dumpfile pathname template.
457      */
458     path_buf = exp_path_template(single_template, state->start_time);
459 
460     /*
461      * Append a random hexadecimal string to the pathname and create a new
462      * file. Retry with a different path if the file already exists. Create
463      * intermediate directories on the fly when the template specifies
464      * multiple pathname segments.
465      */
466 #define ID_FORMAT	"%08x"
467 
468     for (len = VSTRING_LEN(path_buf); /* void */ ; vstring_truncate(path_buf, len)) {
469 	if (++tries > 100)
470 	    msg_fatal("%s: something is looping", myname);
471 	state->id = myrand();
472 	vstring_sprintf_append(path_buf, ID_FORMAT, state->id);
473 	if ((state->dump_file = vstream_fopen(STR(path_buf),
474 					      O_RDWR | O_CREAT | O_EXCL,
475 					      0644)) != 0) {
476 	    break;
477 	} else if (errno == EEXIST) {
478 	    continue;
479 	} else if (errno == ENOENT) {
480 	    make_parent_dir(STR(path_buf), 0755);
481 	    continue;
482 	} else {
483 	    msg_fatal("open %s: %m", STR(path_buf));
484 	}
485     }
486 
487     /*
488      * Don't leave temporary files behind.
489      */
490     if (shared_template != 0 && unlink(STR(path_buf)) < 0)
491 	msg_fatal("unlink %s: %m", STR(path_buf));
492 
493     /*
494      * Do initial header records.
495      */
496     if (start_string)
497 	vstream_fprintf(state->dump_file, "%s", STR(start_string));
498     vstream_fprintf(state->dump_file, "X-Client-Addr: %s%s\n",
499 		    state->addr_prefix, state->client_addr.buf);
500     vstream_fprintf(state->dump_file, "X-Client-Proto: %s\n", state->client_proto);
501     if (state->helo_args)
502 	vstream_fprintf(state->dump_file, "X-Helo-Args: %s\n", state->helo_args);
503     /* Note: there may be more than one recipient. */
504 }
505 
506 /* mail_file_finish_header - do final smtp-sink generated header records */
507 
508 static void mail_file_finish_header(SINK_STATE *state)
509 {
510     if (state->helo_args)
511 	vstream_fprintf(state->dump_file, "Received: from %s ([%s%s])\n",
512 			state->helo_args, state->addr_prefix,
513 			state->client_addr.buf);
514     else
515 	vstream_fprintf(state->dump_file, "Received: from [%s%s] ([%s%s])\n",
516 			state->addr_prefix, state->client_addr.buf,
517 			state->addr_prefix, state->client_addr.buf);
518     vstream_fprintf(state->dump_file, "\tby %s (smtp-sink)"
519 		    " with %s id " ID_FORMAT ";\n",
520 		    var_myhostname, state->client_proto, state->id);
521     vstream_fprintf(state->dump_file, "\t%s\n", mail_date(state->start_time));
522 }
523 
524 /* mail_file_cleanup - common cleanup for capture file */
525 
526 static void mail_file_cleanup(SINK_STATE *state)
527 {
528     (void) vstream_fclose(state->dump_file);
529     state->dump_file = 0;
530 }
531 
532 /* mail_file_finish - handle message completion for capture file */
533 
534 static void mail_file_finish(SINK_STATE *state)
535 {
536 
537     /*
538      * Optionally append the captured message to a shared dumpfile.
539      */
540     if (shared_template) {
541 	const char *out_path;
542 	VSTREAM *out_fp;
543 	ssize_t count;
544 
545 	/*
546 	 * Expand the shared dumpfile pathname template.
547 	 */
548 	out_path = STR(exp_path_template(shared_template, state->start_time));
549 
550 	/*
551 	 * Open the shared dump file.
552 	 */
553 #define OUT_OPEN_FLAGS	(O_WRONLY | O_CREAT | O_APPEND)
554 #define OUT_OPEN_MODE	0644
555 
556 	if ((out_fp = vstream_fopen(out_path, OUT_OPEN_FLAGS, OUT_OPEN_MODE))
557 	    == 0 && errno == ENOENT) {
558 	    make_parent_dir(out_path, 0755);
559 	    out_fp = vstream_fopen(out_path, OUT_OPEN_FLAGS, OUT_OPEN_MODE);
560 	}
561 	if (out_fp == 0)
562 	    msg_fatal("open %s: %m", out_path);
563 
564 	/*
565 	 * Append message content from single-message dump file.
566 	 */
567 	if (vstream_fseek(state->dump_file, 0L, SEEK_SET) < 0)
568 	    msg_fatal("seek file %s: %m", VSTREAM_PATH(state->dump_file));
569 	VSTRING_RESET(state->buffer);
570 	for (;;) {
571 	    count = vstream_fread(state->dump_file, STR(state->buffer),
572 				  vstring_avail(state->buffer));
573 	    if (count <= 0)
574 		break;
575 	    if (vstream_fwrite(out_fp, STR(state->buffer), count) != count)
576 		msg_fatal("append file %s: %m", out_path);
577 	}
578 	if (vstream_ferror(state->dump_file))
579 	    msg_fatal("read file %s: %m", VSTREAM_PATH(state->dump_file));
580 	if (vstream_fclose(out_fp))
581 	    msg_fatal("append file %s: %m", out_path);
582     }
583     mail_file_cleanup(state);
584 }
585 
586 /* mail_file_reset - abort mail to capture file */
587 
588 static void mail_file_reset(SINK_STATE *state)
589 {
590     if (shared_template == 0
591 	&& unlink(VSTREAM_PATH(state->dump_file)) < 0
592 	&& errno != ENOENT)
593 	msg_fatal("unlink %s: %m", VSTREAM_PATH(state->dump_file));
594     mail_file_cleanup(state);
595 }
596 
597 /* mail_cmd_reset - reset mail transaction information */
598 
599 static void mail_cmd_reset(SINK_STATE *state)
600 {
601     state->in_mail = 0;
602     /* Not: state->rcpts = 0. This breaks the DOT reply with LMTP. */
603     if (state->dump_file)
604 	mail_file_reset(state);
605 }
606 
607 /* ehlo_response - respond to EHLO command */
608 
609 static void ehlo_response(SINK_STATE *state, const char *args)
610 {
611 #define SKIP(cp, cond) for (/* void */; *cp && (cond); cp++)
612 
613     /* EHLO aborts a mail transaction in progress. */
614     mail_cmd_reset(state);
615     if (enable_lmtp == 0)
616 	state->client_proto = "ESMTP";
617     smtp_printf(state->stream, "250-%s", var_myhostname);
618     if (!disable_pipelining)
619 	smtp_printf(state->stream, "250-PIPELINING");
620     if (!disable_8bitmime)
621 	smtp_printf(state->stream, "250-8BITMIME");
622     if (!disable_saslauth)
623 	smtp_printf(state->stream, "250-AUTH PLAIN LOGIN");
624     if (!disable_xclient)
625 	smtp_printf(state->stream, "250-XCLIENT NAME HELO");
626     if (!disable_xforward)
627 	smtp_printf(state->stream, "250-XFORWARD NAME ADDR PROTO HELO");
628     if (!disable_enh_status)
629 	smtp_printf(state->stream, "250-ENHANCEDSTATUSCODES");
630     /* RFC 821/2821/5321: Format is replycode<SPACE>optional-text<CRLF> */
631     smtp_printf(state->stream, "250 ");
632     SMTP_FLUSH(state->stream);
633     if (single_template) {
634 	if (state->helo_args)
635 	    myfree(state->helo_args);
636 	SKIP(args, ISSPACE(*args));
637 	state->helo_args = mystrdup(args);
638     }
639 }
640 
641 /* helo_response - respond to HELO command */
642 
643 static void helo_response(SINK_STATE *state, const char *args)
644 {
645     /* HELO aborts a mail transaction in progress. */
646     mail_cmd_reset(state);
647     state->client_proto = "SMTP";
648     smtp_printf(state->stream, "250 %s", var_myhostname);
649     SMTP_FLUSH(state->stream);
650     if (single_template) {
651 	if (state->helo_args)
652 	    myfree(state->helo_args);
653 	SKIP(args, ISSPACE(*args));
654 	state->helo_args = mystrdup(args);
655     }
656 }
657 
658 /* ok_response - send 250 OK */
659 
660 static void ok_response(SINK_STATE *state, const char *unused_args)
661 {
662     smtp_printf(state->stream, "250 2.0.0 Ok");
663     SMTP_FLUSH(state->stream);
664 }
665 
666 /* rset_response - reset, send 250 OK */
667 
668 static void rset_response(SINK_STATE *state, const char *unused_args)
669 {
670     mail_cmd_reset(state);
671     smtp_printf(state->stream, "250 2.1.0 Ok");
672     SMTP_FLUSH(state->stream);
673 }
674 
675 /* mail_response - reset recipient count, send 250 OK */
676 
677 static void mail_response(SINK_STATE *state, const char *args)
678 {
679     if (state->in_mail) {
680 	smtp_printf(state->stream, "503 5.5.1 Error: nested MAIL command");
681 	SMTP_FLUSH(state->stream);
682 	return;
683     }
684     state->in_mail++;
685     state->rcpts = 0;
686     smtp_printf(state->stream, "250 2.1.0 Ok");
687     SMTP_FLUSH(state->stream);
688     if (single_template) {
689 	mail_file_open(state);
690 	SKIP(args, *args != ':');
691 	SKIP(args, *args == ':');
692 	SKIP(args, ISSPACE(*args));
693 	vstream_fprintf(state->dump_file, "X-Mail-Args: %s\n", args);
694     }
695 }
696 
697 /* rcpt_response - bump recipient count, send 250 OK */
698 
699 static void rcpt_response(SINK_STATE *state, const char *args)
700 {
701     if (state->in_mail == 0) {
702 	smtp_printf(state->stream, "503 5.5.1 Error: need MAIL command");
703 	SMTP_FLUSH(state->stream);
704 	return;
705     }
706     state->rcpts++;
707     smtp_printf(state->stream, "250 2.1.5 Ok");
708     SMTP_FLUSH(state->stream);
709     /* Note: there may be more than one recipient per mail transaction. */
710     if (state->dump_file) {
711 	SKIP(args, *args != ':');
712 	SKIP(args, *args == ':');
713 	SKIP(args, ISSPACE(*args));
714 	vstream_fprintf(state->dump_file, "X-Rcpt-Args: %s\n", args);
715     }
716 }
717 
718 /* abort_event - delayed abort after DATA command */
719 
720 static void abort_event(int unused_event, char *context)
721 {
722     SINK_STATE *state = (SINK_STATE *) context;
723 
724     smtp_printf(state->stream, "550 This violates SMTP");
725     SMTP_FLUSH(state->stream);
726     disconnect(state);
727 }
728 
729 /* data_response - respond to DATA command */
730 
731 static void data_response(SINK_STATE *state, const char *unused_args)
732 {
733     if (state->in_mail == 0 || state->rcpts == 0) {
734 	smtp_printf(state->stream, "503 5.5.1 Error: need RCPT command");
735 	SMTP_FLUSH(state->stream);
736 	return;
737     }
738     /* Not: ST_ANY. */
739     state->data_state = ST_CR_LF;
740     smtp_printf(state->stream, "354 End data with <CR><LF>.<CR><LF>");
741     SMTP_FLUSH(state->stream);
742     if (abort_delay < 0) {
743 	state->read_fn = data_read;
744     } else {
745 	/* Stop reading, send premature 550, and disconnect. */
746 	event_disable_readwrite(vstream_fileno(state->stream));
747 	event_cancel_timer(read_event, (char *) state);
748 	event_request_timer(abort_event, (char *) state, abort_delay);
749     }
750     if (state->dump_file)
751 	mail_file_finish_header(state);
752 }
753 
754 /* dot_resp_hard - hard error response to . command */
755 
756 static void dot_resp_hard(SINK_STATE *state)
757 {
758     if (enable_lmtp) {
759 	while (state->rcpts-- > 0)	/* XXX this could block */
760 	    smtp_printf(state->stream, "%s", hard_error_resp);
761     } else {
762 	smtp_printf(state->stream, "%s", hard_error_resp);
763     }
764     SMTP_FLUSH(state->stream);
765 }
766 
767 /* dot_resp_soft - soft error response to . command */
768 
769 static void dot_resp_soft(SINK_STATE *state)
770 {
771     if (enable_lmtp) {
772 	while (state->rcpts-- > 0)	/* XXX this could block */
773 	    smtp_printf(state->stream, "%s", soft_error_resp);
774     } else {
775 	smtp_printf(state->stream, "%s", soft_error_resp);
776     }
777     SMTP_FLUSH(state->stream);
778 }
779 
780 /* dot_response - response to . command */
781 
782 static void dot_response(SINK_STATE *state, const char *unused_args)
783 {
784     if (enable_lmtp) {
785 	while (state->rcpts-- > 0)	/* XXX this could block */
786 	    smtp_printf(state->stream, "250 2.2.0 Ok");
787     } else {
788 	smtp_printf(state->stream, "250 2.0.0 Ok");
789     }
790     SMTP_FLUSH(state->stream);
791 }
792 
793 /* quit_response - respond to QUIT command */
794 
795 static void quit_response(SINK_STATE *state, const char *unused_args)
796 {
797     smtp_printf(state->stream, "221 Bye");
798     smtp_flush(state->stream);			/* not: SMTP_FLUSH */
799     if (count)
800 	quit_count++;
801 }
802 
803 /* conn_response - respond to connect command */
804 
805 static void conn_response(SINK_STATE *state, const char *unused_args)
806 {
807     if (pretend_pix)
808 	smtp_printf(state->stream, "220 ********");
809     else if (disable_esmtp)
810 	smtp_printf(state->stream, "220 %s", var_myhostname);
811     else
812 	smtp_printf(state->stream, "220 %s ESMTP", var_myhostname);
813     SMTP_FLUSH(state->stream);
814 }
815 
816 /* delay_event - delayed command response */
817 
818 static void delay_event(int unused_event, char *context)
819 {
820     SINK_STATE *state = (SINK_STATE *) context;
821 
822     switch (vstream_setjmp(state->stream)) {
823 
824     default:
825 	msg_panic("unknown read/write error");
826 	/* NOTREACHED */
827 
828     case SMTP_ERR_TIME:
829 	msg_warn("write timeout");
830 	disconnect(state);
831 	return;
832 
833     case SMTP_ERR_EOF:
834 	msg_warn("lost connection");
835 	disconnect(state);
836 	return;
837 
838     case 0:
839 	state->delayed_response(state, state->delayed_args);
840 	myfree(state->delayed_args);
841 	state->delayed_args = 0;
842 	break;
843     }
844 
845     if (state->delayed_response == quit_response) {
846 	disconnect(state);
847 	return;
848     }
849     state->delayed_response = 0;
850 
851     /* Resume input event handling after the delayed response. */
852     event_enable_read(vstream_fileno(state->stream), read_event, (char *) state);
853     event_request_timer(read_timeout, (char *) state, var_tmout);
854 }
855 
856 /* data_read - read data from socket */
857 
858 static int data_read(SINK_STATE *state)
859 {
860     int     ch;
861     struct data_trans {
862 	int     state;
863 	int     want;
864 	int     next_state;
865     };
866     static struct data_trans data_trans[] = {
867 	ST_ANY, '\r', ST_CR,
868 	ST_CR, '\n', ST_CR_LF,
869 	ST_CR_LF, '.', ST_CR_LF_DOT,
870 	ST_CR_LF_DOT, '\r', ST_CR_LF_DOT_CR,
871 	ST_CR_LF_DOT_CR, '\n', ST_CR_LF_DOT_CR_LF,
872     };
873     struct data_trans *dp;
874 
875     /*
876      * A read may result in EOF, but is never supposed to time out - a time
877      * out means that we were trying to read when no data was available.
878      */
879     for (;;) {
880 	if ((ch = VSTREAM_GETC(state->stream)) == VSTREAM_EOF)
881 	    return (-1);
882 	for (dp = data_trans; dp->state != state->data_state; dp++)
883 	     /* void */ ;
884 
885 	/*
886 	 * Try to match the current character desired by the state machine.
887 	 * If that fails, try to restart the machine with a match for its
888 	 * first state.  This covers the case of a CR/LF/CR/LF sequence
889 	 * (empty line) right before the end of the message data.
890 	 */
891 	if (ch == dp->want)
892 	    state->data_state = dp->next_state;
893 	else if (ch == data_trans[0].want)
894 	    state->data_state = data_trans[0].next_state;
895 	else
896 	    state->data_state = ST_ANY;
897 	if (state->dump_file) {
898 	    if (ch != '\r' && state->data_state != ST_CR_LF_DOT)
899 		VSTREAM_PUTC(ch, state->dump_file);
900 	    if (vstream_ferror(state->dump_file))
901 		msg_fatal("append file %s: %m", VSTREAM_PATH(state->dump_file));
902 	}
903 	if (state->data_state == ST_CR_LF_DOT_CR_LF) {
904 	    PUSH_BACK_SET(state, ".\r\n");
905 	    state->read_fn = command_read;
906 	    state->data_state = ST_ANY;
907 	    if (state->dump_file)
908 		mail_file_finish(state);
909 	    mail_cmd_reset(state);
910 	    if (count || max_msg_quit_count > 0) {
911 		mesg_count++;
912 		if (count)
913 		    do_stats();
914 		if (max_msg_quit_count > 0 && mesg_count >= max_msg_quit_count)
915 		    exit(0);
916 	    }
917 	    break;
918 	}
919 
920 	/*
921 	 * We must avoid blocking I/O, so get out of here as soon as both the
922 	 * VSTREAM and kernel read buffers dry up.
923 	 */
924 	if (vstream_peek(state->stream) <= 0
925 	    && readable(vstream_fileno(state->stream)) <= 0)
926 	    return (0);
927     }
928     return (0);
929 }
930 
931  /*
932   * The table of all SMTP commands that we can handle.
933   */
934 typedef struct SINK_COMMAND {
935     const char *name;
936     void    (*response) (SINK_STATE *, const char *);
937     void    (*hard_response) (SINK_STATE *);
938     void    (*soft_response) (SINK_STATE *);
939     int     flags;
940     int     delay;
941     int     delay_odds;
942 } SINK_COMMAND;
943 
944 #define FLAG_ENABLE	(1<<0)		/* command is enabled */
945 #define FLAG_SYSLOG	(1<<1)		/* log the command */
946 #define FLAG_HARD_ERR	(1<<2)		/* report hard error */
947 #define FLAG_SOFT_ERR	(1<<3)		/* report soft error */
948 #define FLAG_DISCONNECT	(1<<4)		/* disconnect */
949 #define FLAG_CLOSE	(1<<5)		/* say goodbye and disconnect */
950 
951 static SINK_COMMAND command_table[] = {
952     "connect", conn_response, hard_err_resp, soft_err_resp, 0, 0, 0,
953     "helo", helo_response, hard_err_resp, soft_err_resp, 0, 0, 0,
954     "ehlo", ehlo_response, hard_err_resp, soft_err_resp, 0, 0, 0,
955     "lhlo", ehlo_response, hard_err_resp, soft_err_resp, 0, 0, 0,
956     "xclient", ok_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
957     "xforward", ok_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
958     "auth", ok_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
959     "mail", mail_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
960     "rcpt", rcpt_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
961     "data", data_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
962     ".", dot_response, dot_resp_hard, dot_resp_soft, FLAG_ENABLE, 0, 0,
963     "rset", rset_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
964     "noop", ok_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
965     "vrfy", ok_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
966     "quit", quit_response, hard_err_resp, soft_err_resp, FLAG_ENABLE, 0, 0,
967     0,
968 };
969 
970 /* reset_cmd_flags - reset per-command command flags */
971 
972 static void reset_cmd_flags(const char *cmd, int flags)
973 {
974     SINK_COMMAND *cmdp;
975 
976     for (cmdp = command_table; cmdp->name != 0; cmdp++)
977 	if (strcasecmp(cmd, cmdp->name) == 0)
978 	    break;
979     if (cmdp->name == 0)
980 	msg_fatal("unknown command: %s", cmd);
981     cmdp->flags &= ~flags;
982 }
983 
984 /* set_cmd_flags - set per-command command flags */
985 
986 static void set_cmd_flags(const char *cmd, int flags)
987 {
988     SINK_COMMAND *cmdp;
989 
990     for (cmdp = command_table; cmdp->name != 0; cmdp++)
991 	if (strcasecmp(cmd, cmdp->name) == 0)
992 	    break;
993     if (cmdp->name == 0)
994 	msg_fatal("unknown command: %s", cmd);
995     cmdp->flags |= flags;
996 }
997 
998 /* set_cmds_flags - set per-command flags for multiple commands */
999 
1000 static void set_cmds_flags(const char *cmds, int flags)
1001 {
1002     char   *saved_cmds;
1003     char   *cp;
1004     char   *cmd;
1005 
1006     saved_cmds = cp = mystrdup(cmds);
1007     while ((cmd = mystrtok(&cp, " \t\r\n,")) != 0)
1008 	set_cmd_flags(cmd, flags);
1009     myfree(saved_cmds);
1010 }
1011 
1012 /* set_cmd_delay - set per-command delay */
1013 
1014 static void set_cmd_delay(const char *cmd, int delay, int odds)
1015 {
1016     SINK_COMMAND *cmdp;
1017 
1018     for (cmdp = command_table; cmdp->name != 0; cmdp++)
1019 	if (strcasecmp(cmd, cmdp->name) == 0)
1020 	    break;
1021     if (cmdp->name == 0)
1022 	msg_fatal("unknown command: %s", cmd);
1023 
1024     if (delay <= 0)
1025 	msg_fatal("non-positive '%s' delay", cmd);
1026     if (odds < 0 || odds > 99)
1027 	msg_fatal("delay odds for '%s' out of range", cmd);
1028 
1029     cmdp->delay = delay;
1030     cmdp->delay_odds = odds;
1031 }
1032 
1033 /* set_cmd_delay_arg - set per-command delay from option argument */
1034 
1035 static void set_cmd_delay_arg(char *arg)
1036 {
1037     char   *cp;
1038     char   *saved_arg;
1039     char   *cmd;
1040     char   *delay;
1041     char   *odds;
1042 
1043     saved_arg = cp = mystrdup(arg);
1044     cmd = mystrtok(&cp, ":");
1045     delay = mystrtok(&cp, ":");
1046     if (cmd == 0 || delay == 0)
1047 	msg_fatal("invalid command delay argument: %s", arg);
1048     odds = mystrtok(&cp, "");
1049     set_cmd_delay(cmd, atoi(delay), odds ? atoi(odds) : 0);
1050     myfree(saved_arg);
1051 }
1052 
1053 /* command_resp - respond to command */
1054 
1055 static int command_resp(SINK_STATE *state, SINK_COMMAND *cmdp,
1056 			        const char *command, const char *args)
1057 {
1058     /* We use raw syslog. Sanitize data content and length. */
1059     if (cmdp->flags & FLAG_SYSLOG)
1060 	syslog(LOG_INFO, "%s %.100s", command, args);
1061     if (cmdp->flags & FLAG_DISCONNECT)
1062 	return (-1);
1063     if (cmdp->flags & FLAG_CLOSE) {
1064 	smtp_printf(state->stream, "421 4.0.0 Server closing connection");
1065 	return (-1);
1066     }
1067     if (cmdp->flags & FLAG_HARD_ERR) {
1068 	cmdp->hard_response(state);
1069 	return (0);
1070     }
1071     if (cmdp->flags & FLAG_SOFT_ERR) {
1072 	cmdp->soft_response(state);
1073 	return (0);
1074     }
1075     if (cmdp->delay > 0) {
1076 	int     delay = cmdp->delay;
1077 
1078 	if (cmdp->delay_odds > 0)
1079 	    for (delay = 0;
1080 	     ((int) (100.0 * rand() / (RAND_MAX + 1.0))) < cmdp->delay_odds;
1081 		 delay += cmdp->delay)
1082 		 /* NOP */ ;
1083 	/* Suspend input event handling while delaying the command response. */
1084 	event_disable_readwrite(vstream_fileno(state->stream));
1085 	event_cancel_timer(read_timeout, (char *) state);
1086 	event_request_timer(delay_event, (char *) state, delay);
1087 	state->delayed_response = cmdp->response;
1088 	state->delayed_args = mystrdup(args);
1089     } else {
1090 	cmdp->response(state, args);
1091 	if (cmdp->response == quit_response)
1092 	    return (-1);
1093     }
1094     return (0);
1095 }
1096 
1097 /* command_read - talk the SMTP protocol, server side */
1098 
1099 static int command_read(SINK_STATE *state)
1100 {
1101     char   *command;
1102     SINK_COMMAND *cmdp;
1103     int     ch;
1104     struct cmd_trans {
1105 	int     state;
1106 	int     want;
1107 	int     next_state;
1108     };
1109     static struct cmd_trans cmd_trans[] = {
1110 	ST_ANY, '\r', ST_CR,
1111 	ST_CR, '\n', ST_CR_LF,
1112 	0, 0, 0,
1113     };
1114     struct cmd_trans *cp;
1115     char   *ptr;
1116 
1117     /*
1118      * A read may result in EOF, but is never supposed to time out - a time
1119      * out means that we were trying to read when no data was available.
1120      */
1121 #define NEXT_CHAR(state) \
1122     (PUSH_BACK_PEEK(state) ? PUSH_BACK_GET(state) : VSTREAM_GETC(state->stream))
1123 
1124     if (state->data_state == ST_CR_LF)
1125 	state->data_state = ST_ANY;		/* XXX */
1126     for (;;) {
1127 	if ((ch = NEXT_CHAR(state)) == VSTREAM_EOF)
1128 	    return (-1);
1129 
1130 	/*
1131 	 * Sanity check. We don't want to store infinitely long commands.
1132 	 */
1133 	if (VSTRING_LEN(state->buffer) >= var_max_line_length) {
1134 	    msg_warn("command line too long");
1135 	    return (-1);
1136 	}
1137 	VSTRING_ADDCH(state->buffer, ch);
1138 
1139 	/*
1140 	 * Try to match the current character desired by the state machine.
1141 	 * If that fails, try to restart the machine with a match for its
1142 	 * first state.
1143 	 */
1144 	for (cp = cmd_trans; cp->state != state->data_state; cp++)
1145 	    if (cp->want == 0)
1146 		msg_panic("command_read: unknown state: %d", state->data_state);
1147 	if (ch == cp->want)
1148 	    state->data_state = cp->next_state;
1149 	else if (ch == cmd_trans[0].want)
1150 	    state->data_state = cmd_trans[0].next_state;
1151 	else
1152 	    state->data_state = ST_ANY;
1153 	if (state->data_state == ST_CR_LF)
1154 	    break;
1155 
1156 	/*
1157 	 * We must avoid blocking I/O, so get out of here as soon as both the
1158 	 * VSTREAM and kernel read buffers dry up.
1159 	 *
1160 	 * XXX Solaris non-blocking read() may fail on a socket when ioctl
1161 	 * FIONREAD reports there is unread data. Diagnosis by Max Pashkov.
1162 	 * As a workaround we use readable() (which uses poll or select())
1163 	 * instead of peek_fd() (which uses ioctl FIONREAD). Workaround added
1164 	 * 20020604.
1165 	 */
1166 	if (PUSH_BACK_PEEK(state) == 0 && vstream_peek(state->stream) <= 0
1167 	    && readable(vstream_fileno(state->stream)) <= 0)
1168 	    return (0);
1169     }
1170 
1171     /*
1172      * Properly terminate the result, and reset the buffer write pointer for
1173      * reading the next command. This is ugly, but not as ugly as trying to
1174      * deal with all the early returns below.
1175      */
1176     vstring_truncate(state->buffer, VSTRING_LEN(state->buffer) - 2);
1177     VSTRING_TERMINATE(state->buffer);
1178     state->data_state = ST_CR_LF;
1179     VSTRING_RESET(state->buffer);
1180 
1181     /*
1182      * Got a complete command line. Parse it.
1183      */
1184     ptr = vstring_str(state->buffer);
1185     if (msg_verbose)
1186 	msg_info("%s", ptr);
1187     if ((command = mystrtok(&ptr, " \t")) == 0) {
1188 	smtp_printf(state->stream, "500 5.5.2 Error: unknown command");
1189 	SMTP_FLUSH(state->stream);
1190 	return (0);
1191     }
1192     for (cmdp = command_table; cmdp->name != 0; cmdp++)
1193 	if (strcasecmp(command, cmdp->name) == 0)
1194 	    break;
1195     if (cmdp->name == 0 || (cmdp->flags & FLAG_ENABLE) == 0) {
1196 	smtp_printf(state->stream, "500 5.5.1 Error: unknown command");
1197 	SMTP_FLUSH(state->stream);
1198 	return (0);
1199     }
1200     return (command_resp(state, cmdp, command, printable(ptr, '?')));
1201 }
1202 
1203 /* read_timeout - handle timer event */
1204 
1205 static void read_timeout(int unused_event, char *context)
1206 {
1207     SINK_STATE *state = (SINK_STATE *) context;
1208 
1209     /*
1210      * We don't send anything to the client, because we would have to set up
1211      * an smtp_stream exception handler first. And that is just too much
1212      * trouble.
1213      */
1214     msg_warn("read timeout");
1215     disconnect(state);
1216 }
1217 
1218 /* read_event - handle command or data read events */
1219 
1220 static void read_event(int unused_event, char *context)
1221 {
1222     SINK_STATE *state = (SINK_STATE *) context;
1223 
1224     /*
1225      * The input reading routine not only reads input (with vstream calls)
1226      * but also produces output (with smtp_stream calls). Because the output
1227      * routines can raise timeout or EOF exceptions with vstream_longjmp(),
1228      * the input reading routine needs to set up corresponding exception
1229      * handlers with vstream_setjmp(). Guarding the input operations in the
1230      * same manner is not useful: we must read input in non-blocking mode, so
1231      * we never get called when the socket stays unreadable too long. And EOF
1232      * is already trivial to detect with the vstream calls.
1233      */
1234     do {
1235 	switch (vstream_setjmp(state->stream)) {
1236 
1237 	default:
1238 	    msg_panic("unknown read/write error");
1239 	    /* NOTREACHED */
1240 
1241 	case SMTP_ERR_TIME:
1242 	    msg_warn("write timeout");
1243 	    disconnect(state);
1244 	    return;
1245 
1246 	case SMTP_ERR_EOF:
1247 	    msg_warn("lost connection");
1248 	    disconnect(state);
1249 	    return;
1250 
1251 	case 0:
1252 	    if (state->read_fn(state) < 0) {
1253 		if (msg_verbose)
1254 		    msg_info("disconnect");
1255 		disconnect(state);
1256 		return;
1257 	    }
1258 	}
1259     } while (PUSH_BACK_PEEK(state) != 0 || vstream_peek(state->stream) > 0);
1260 
1261     /*
1262      * Reset the idle timer. Wait until the next input event, or until the
1263      * idle timer goes off.
1264      */
1265     event_request_timer(read_timeout, (char *) state, var_tmout);
1266 }
1267 
1268 static void connect_event(int, char *);
1269 
1270 /* disconnect - handle disconnection events */
1271 
1272 static void disconnect(SINK_STATE *state)
1273 {
1274     event_disable_readwrite(vstream_fileno(state->stream));
1275     event_cancel_timer(read_timeout, (char *) state);
1276     if (count) {
1277 	sess_count++;
1278 	do_stats();
1279     }
1280     vstream_fclose(state->stream);
1281     vstring_free(state->buffer);
1282     /* Clean up file capture attributes. */
1283     if (state->helo_args)
1284 	myfree(state->helo_args);
1285     /* Delete incomplete mail transaction. */
1286     mail_cmd_reset(state);
1287     if (state->delayed_args)
1288 	myfree(state->delayed_args);
1289     myfree((char *) state);
1290     if (max_quit_count > 0 && quit_count >= max_quit_count)
1291 	exit(0);
1292     if (client_count-- == max_client_count)
1293 	event_enable_read(sock, connect_event, (char *) 0);
1294 }
1295 
1296 /* connect_event - handle connection events */
1297 
1298 static void connect_event(int unused_event, char *unused_context)
1299 {
1300     struct sockaddr sa;
1301     SOCKADDR_SIZE len = sizeof(sa);
1302     SINK_STATE *state;
1303     int     fd;
1304 
1305     if ((fd = sane_accept(sock, &sa, &len)) >= 0) {
1306 	/* Safety: limit the number of open sockets and capture files. */
1307 	if (++client_count == max_client_count)
1308 	    event_disable_readwrite(sock);
1309 	state = (SINK_STATE *) mymalloc(sizeof(*state));
1310 	if (strchr((char *) proto_info->sa_family_list, sa.sa_family))
1311 	    SOCKADDR_TO_HOSTADDR(&sa, len, &state->client_addr,
1312 				 (MAI_SERVPORT_STR *) 0, sa.sa_family);
1313 	else
1314 	    strncpy(state->client_addr.buf, "local", sizeof("local"));
1315 	if (msg_verbose)
1316 	    msg_info("connect (%s %s)",
1317 #ifdef AF_LOCAL
1318 		     sa.sa_family == AF_LOCAL ? "AF_LOCAL" :
1319 #else
1320 		     sa.sa_family == AF_UNIX ? "AF_UNIX" :
1321 #endif
1322 		     sa.sa_family == AF_INET ? "AF_INET" :
1323 #ifdef AF_INET6
1324 		     sa.sa_family == AF_INET6 ? "AF_INET6" :
1325 #endif
1326 		     "unknown protocol family",
1327 		     state->client_addr.buf);
1328 	non_blocking(fd, NON_BLOCKING);
1329 	state->stream = vstream_fdopen(fd, O_RDWR);
1330 	vstream_tweak_sock(state->stream);
1331 	state->buffer = vstring_alloc(1024);
1332 	state->read_fn = command_read;
1333 	state->data_state = ST_ANY;
1334 	PUSH_BACK_SET(state, "");
1335 	smtp_timeout_setup(state->stream, var_tmout);
1336 	state->in_mail = 0;
1337 	state->rcpts = 0;
1338 	state->delayed_response = 0;
1339 	state->delayed_args = 0;
1340 	/* Initialize file capture attributes. */
1341 #ifdef AF_INET6
1342 	if (sa.sa_family == AF_INET6)
1343 	    state->addr_prefix = "ipv6:";
1344 	else
1345 #endif
1346 	    state->addr_prefix = "";
1347 
1348 	state->helo_args = 0;
1349 	state->client_proto = enable_lmtp ? "LMTP" : "SMTP";
1350 	state->start_time = 0;
1351 	state->id = 0;
1352 	state->dump_file = 0;
1353 
1354 	/*
1355 	 * We use the smtp_stream module to produce output. That module
1356 	 * throws an exception via vstream_longjmp() in case of a timeout or
1357 	 * lost connection error. Therefore we must prepare to handle these
1358 	 * exceptions with vstream_setjmp().
1359 	 */
1360 	switch (vstream_setjmp(state->stream)) {
1361 
1362 	default:
1363 	    msg_panic("unknown read/write error");
1364 	    /* NOTREACHED */
1365 
1366 	case SMTP_ERR_TIME:
1367 	    msg_warn("write timeout");
1368 	    disconnect(state);
1369 	    return;
1370 
1371 	case SMTP_ERR_EOF:
1372 	    msg_warn("lost connection");
1373 	    disconnect(state);
1374 	    return;
1375 
1376 	case 0:
1377 	    if (command_resp(state, command_table, "connect", "") < 0)
1378 		disconnect(state);
1379 	    else if (command_table->delay == 0) {
1380 		event_enable_read(fd, read_event, (char *) state);
1381 		event_request_timer(read_timeout, (char *) state, var_tmout);
1382 	    }
1383 	}
1384     }
1385 }
1386 
1387 /* usage - explain */
1388 
1389 static void usage(char *myname)
1390 {
1391     msg_fatal("usage: %s [-468acCeEFLpPv] [-A abort_delay] [-b soft_bounce_reply] [-B hard_bounce_reply] [-d dump-template] [-D dump-template] [-f commands] [-h hostname] [-m max_concurrency] [-M message_quit_count] [-n quit_count] [-q commands] [-r commands] [-R root-dir] [-s commands] [-S start-string] [-u user_privs] [-w delay] [host]:port backlog", myname);
1392 }
1393 
1394 MAIL_VERSION_STAMP_DECLARE;
1395 
1396 int     main(int argc, char **argv)
1397 {
1398     int     backlog;
1399     int     ch;
1400     int     delay;
1401     const char *protocols = INET_PROTO_NAME_ALL;
1402     const char *root_dir = 0;
1403     const char *user_privs = 0;
1404 
1405     /*
1406      * Fingerprint executables and core dumps.
1407      */
1408     MAIL_VERSION_STAMP_ALLOCATE;
1409 
1410     /*
1411      * Fix 20051207.
1412      */
1413     signal(SIGPIPE, SIG_IGN);
1414 
1415     /*
1416      * Initialize diagnostics.
1417      */
1418     msg_vstream_init(argv[0], VSTREAM_ERR);
1419 
1420     /*
1421      * Parse JCL.
1422      */
1423     while ((ch = GETOPT(argc, argv, "468aA:b:B:cCd:D:eEf:Fh:Ln:m:M:pPq:Q:r:R:s:S:t:T:u:vw:W:")) > 0) {
1424 	switch (ch) {
1425 	case '4':
1426 	    protocols = INET_PROTO_NAME_IPV4;
1427 	    break;
1428 	case '6':
1429 	    protocols = INET_PROTO_NAME_IPV6;
1430 	    break;
1431 	case '8':
1432 	    disable_8bitmime = 1;
1433 	    break;
1434 	case 'a':
1435 	    disable_saslauth = 1;
1436 	    break;
1437 	case 'A':
1438 	    if (!alldig(optarg) || (abort_delay = atoi(optarg)) < 0)
1439 		usage(argv[0]);
1440 	    break;
1441 	case 'b':
1442 	    if (optarg[0] != '4' || strspn(optarg, "0123456789") != 3) {
1443 		msg_error("bad soft error reply: %s", optarg);
1444 		usage(argv[0]);
1445 	    } else
1446 		soft_error_resp = optarg;
1447 	    break;
1448 	case 'B':
1449 	    if (optarg[0] != '5' || strspn(optarg, "0123456789") != 3) {
1450 		msg_error("bad hard error reply: %s", optarg);
1451 		usage(argv[0]);
1452 	    } else
1453 		hard_error_resp = optarg;
1454 	    break;
1455 	case 'c':
1456 	    count++;
1457 	    break;
1458 	case 'C':
1459 	    disable_xclient = 1;
1460 	    reset_cmd_flags("xclient", FLAG_ENABLE);
1461 	    break;
1462 	case 'd':
1463 	    single_template = optarg;
1464 	    break;
1465 	case 'D':
1466 	    shared_template = optarg;
1467 	    break;
1468 	case 'e':
1469 	    disable_esmtp = 1;
1470 	    break;
1471 	case 'E':
1472 	    disable_enh_status = 1;
1473 	    break;
1474 	case 'f':
1475 	    set_cmds_flags(optarg, FLAG_HARD_ERR);
1476 	    disable_pipelining = 1;
1477 	    break;
1478 	case 'F':
1479 	    disable_xforward = 1;
1480 	    reset_cmd_flags("xforward", FLAG_ENABLE);
1481 	    break;
1482 	case 'h':
1483 	    var_myhostname = optarg;
1484 	    break;
1485 	case 'L':
1486 	    enable_lmtp = 1;
1487 	    break;
1488 	case 'm':
1489 	    if ((max_client_count = atoi(optarg)) <= 0)
1490 		msg_fatal("bad concurrency limit: %s", optarg);
1491 	    break;
1492 	case 'M':
1493 	    if ((max_msg_quit_count = atoi(optarg)) <= 0)
1494 		msg_fatal("bad message quit count: %s", optarg);
1495 	    break;
1496 	case 'n':
1497 	    if ((max_quit_count = atoi(optarg)) <= 0)
1498 		msg_fatal("bad quit count: %s", optarg);
1499 	    break;
1500 	case 'p':
1501 	    disable_pipelining = 1;
1502 	    break;
1503 	case 'P':
1504 	    pretend_pix = 1;
1505 	    disable_esmtp = 1;
1506 	    break;
1507 	case 'q':
1508 	    set_cmds_flags(optarg, FLAG_DISCONNECT);
1509 	    break;
1510 	case 'Q':
1511 	    set_cmds_flags(optarg, FLAG_CLOSE);
1512 	    break;
1513 	case 'r':
1514 	    set_cmds_flags(optarg, FLAG_SOFT_ERR);
1515 	    disable_pipelining = 1;
1516 	    break;
1517 	case 'R':
1518 	    root_dir = optarg;
1519 	    break;
1520 	case 's':
1521 	    openlog(basename(argv[0]), LOG_PID, LOG_MAIL);
1522 	    set_cmds_flags(optarg, FLAG_SYSLOG);
1523 	    break;
1524 	case 'S':
1525 	    start_string = vstring_alloc(10);
1526 	    unescape(start_string, optarg);
1527 	    break;
1528 	case 't':
1529 	    if ((var_tmout = atoi(optarg)) <= 0)
1530 		msg_fatal("bad timeout: %s", optarg);
1531 	    break;
1532 	case 'T':
1533 	    if ((inet_windowsize = atoi(optarg)) <= 0)
1534 		msg_fatal("bad TCP window size: %s", optarg);
1535 	    break;
1536 	case 'u':
1537 	    user_privs = optarg;
1538 	    break;
1539 	case 'v':
1540 	    msg_verbose++;
1541 	    break;
1542 	case 'w':
1543 	    if ((delay = atoi(optarg)) <= 0)
1544 		usage(argv[0]);
1545 	    set_cmd_delay("data", delay, 0);
1546 	    break;
1547 	case 'W':
1548 	    set_cmd_delay_arg(optarg);
1549 	    break;
1550 	default:
1551 	    usage(argv[0]);
1552 	}
1553     }
1554     if (argc - optind != 2)
1555 	usage(argv[0]);
1556     if ((backlog = atoi(argv[optind + 1])) <= 0)
1557 	usage(argv[0]);
1558     if (single_template && shared_template)
1559 	msg_fatal("use only one of -d or -D, but not both");
1560     if (geteuid() == 0 && user_privs == 0)
1561 	msg_fatal("-u option is required if running as root");
1562 
1563     /*
1564      * Initialize.
1565      */
1566     if (var_myhostname == 0)
1567 	var_myhostname = "smtp-sink";
1568     set_cmds_flags(enable_lmtp ? "lhlo" :
1569 		   disable_esmtp ? "helo" :
1570 		   "helo, ehlo", FLAG_ENABLE);
1571     proto_info = inet_proto_init("protocols", protocols);
1572     if (strncmp(argv[optind], "unix:", 5) == 0) {
1573 	sock = unix_listen(argv[optind] + 5, backlog, BLOCKING);
1574     } else {
1575 	if (strncmp(argv[optind], "inet:", 5) == 0)
1576 	    argv[optind] += 5;
1577 	sock = inet_listen(argv[optind], backlog, BLOCKING);
1578     }
1579     if (user_privs)
1580 	chroot_uid(root_dir, user_privs);
1581 
1582     if (single_template)
1583 	mysrand((int) time((time_t *) 0));
1584     else if (shared_template)
1585 	single_template = shared_template;
1586 
1587     /*
1588      * Start the event handler.
1589      */
1590     event_enable_read(sock, connect_event, (char *) 0);
1591     for (;;)
1592 	event_loop(-1);
1593 }
1594