xref: /netbsd-src/external/ibm-public/postfix/dist/src/oqmgr/qmgr_deliver.c (revision c7c727fae85036860d5bb848f2730ff419e2b060)
1 /*	$NetBSD: qmgr_deliver.c,v 1.1.1.2 2011/03/02 19:32:23 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	qmgr_deliver 3
6 /* SUMMARY
7 /*	deliver one per-site queue entry to that site
8 /* SYNOPSIS
9 /*	#include "qmgr.h"
10 /*
11 /*	int	qmgr_deliver_concurrency;
12 /*
13 /*	int	qmgr_deliver(transport, fp)
14 /*	QMGR_TRANSPORT *transport;
15 /*	VSTREAM	*fp;
16 /* DESCRIPTION
17 /*	This module implements the client side of the `queue manager
18 /*	to delivery agent' protocol. The queue manager uses
19 /*	asynchronous I/O so that it can drive multiple delivery
20 /*	agents in parallel. Depending on the outcome of a delivery
21 /*	attempt, the status of messages, queues and transports is
22 /*	updated.
23 /*
24 /*	qmgr_deliver_concurrency is a global counter that says how
25 /*	many delivery processes are in use. This can be used, for
26 /*	example, to control the size of the `active' message queue.
27 /*
28 /*	qmgr_deliver() executes when a delivery process announces its
29 /*	availability for the named transport. It arranges for delivery
30 /*	of a suitable queue entry.  The \fIfp\fR argument specifies a
31 /*	stream that is connected to the delivery process, or a null
32 /*	pointer if the transport accepts no connection. Upon completion
33 /*	of delivery (successful or not), the stream is closed, so that the
34 /*	delivery process is released.
35 /* DIAGNOSTICS
36 /* LICENSE
37 /* .ad
38 /* .fi
39 /*	The Secure Mailer license must be distributed with this software.
40 /* AUTHOR(S)
41 /*	Wietse Venema
42 /*	IBM T.J. Watson Research
43 /*	P.O. Box 704
44 /*	Yorktown Heights, NY 10598, USA
45 /*--*/
46 
47 /* System library. */
48 
49 #include <sys_defs.h>
50 #include <time.h>
51 #include <string.h>
52 
53 /* Utility library. */
54 
55 #include <msg.h>
56 #include <vstring.h>
57 #include <vstream.h>
58 #include <vstring_vstream.h>
59 #include <events.h>
60 #include <iostuff.h>
61 #include <stringops.h>
62 #include <mymalloc.h>
63 
64 /* Global library. */
65 
66 #include <mail_queue.h>
67 #include <mail_proto.h>
68 #include <recipient_list.h>
69 #include <mail_params.h>
70 #include <deliver_request.h>
71 #include <verp_sender.h>
72 #include <dsn_util.h>
73 #include <dsn_buf.h>
74 #include <dsb_scan.h>
75 #include <rcpt_print.h>
76 
77 /* Application-specific. */
78 
79 #include "qmgr.h"
80 
81 int     qmgr_deliver_concurrency;
82 
83  /*
84   * Message delivery status codes.
85   */
86 #define DELIVER_STAT_OK		0	/* all recipients delivered */
87 #define DELIVER_STAT_DEFER	1	/* try some recipients later */
88 #define DELIVER_STAT_CRASH	2	/* mailer internal problem */
89 
90 /* qmgr_deliver_initial_reply - retrieve initial delivery process response */
91 
92 static int qmgr_deliver_initial_reply(VSTREAM *stream)
93 {
94     int     stat;
95 
96     if (peekfd(vstream_fileno(stream)) < 0) {
97 	msg_warn("%s: premature disconnect", VSTREAM_PATH(stream));
98 	return (DELIVER_STAT_CRASH);
99     } else if (attr_scan(stream, ATTR_FLAG_STRICT,
100 			 ATTR_TYPE_INT, MAIL_ATTR_STATUS, &stat,
101 			 ATTR_TYPE_END) != 1) {
102 	msg_warn("%s: malformed response", VSTREAM_PATH(stream));
103 	return (DELIVER_STAT_CRASH);
104     } else {
105 	return (stat ? DELIVER_STAT_DEFER : 0);
106     }
107 }
108 
109 /* qmgr_deliver_final_reply - retrieve final delivery process response */
110 
111 static int qmgr_deliver_final_reply(VSTREAM *stream, DSN_BUF *dsb)
112 {
113     int     stat;
114 
115     if (peekfd(vstream_fileno(stream)) < 0) {
116 	msg_warn("%s: premature disconnect", VSTREAM_PATH(stream));
117 	return (DELIVER_STAT_CRASH);
118     } else if (attr_scan(stream, ATTR_FLAG_STRICT,
119 			 ATTR_TYPE_FUNC, dsb_scan, (void *) dsb,
120 			 ATTR_TYPE_INT, MAIL_ATTR_STATUS, &stat,
121 			 ATTR_TYPE_END) != 2) {
122 	msg_warn("%s: malformed response", VSTREAM_PATH(stream));
123 	return (DELIVER_STAT_CRASH);
124     } else {
125 	return (stat ? DELIVER_STAT_DEFER : 0);
126     }
127 }
128 
129 /* qmgr_deliver_send_request - send delivery request to delivery process */
130 
131 static int qmgr_deliver_send_request(QMGR_ENTRY *entry, VSTREAM *stream)
132 {
133     RECIPIENT_LIST list = entry->rcpt_list;
134     RECIPIENT *recipient;
135     QMGR_MESSAGE *message = entry->message;
136     VSTRING *sender_buf = 0;
137     MSG_STATS stats;
138     char   *sender;
139     int     flags;
140 
141     /*
142      * If variable envelope return path is requested, change prefix+@origin
143      * into prefix+user=domain@origin. Note that with VERP there is only one
144      * recipient per delivery.
145      */
146     if (message->verp_delims == 0) {
147 	sender = message->sender;
148     } else {
149 	sender_buf = vstring_alloc(100);
150 	verp_sender(sender_buf, message->verp_delims,
151 		    message->sender, list.info);
152 	sender = vstring_str(sender_buf);
153     }
154 
155     flags = message->tflags
156 	| entry->queue->dflags
157 	| (message->inspect_xport ? DEL_REQ_FLAG_BOUNCE : DEL_REQ_FLAG_DEFLT);
158     (void) QMGR_MSG_STATS(&stats, message);
159     attr_print(stream, ATTR_FLAG_NONE,
160 	       ATTR_TYPE_INT, MAIL_ATTR_FLAGS, flags,
161 	       ATTR_TYPE_STR, MAIL_ATTR_QUEUE, message->queue_name,
162 	       ATTR_TYPE_STR, MAIL_ATTR_QUEUEID, message->queue_id,
163 	       ATTR_TYPE_LONG, MAIL_ATTR_OFFSET, message->data_offset,
164 	       ATTR_TYPE_LONG, MAIL_ATTR_SIZE, message->cont_length,
165 	       ATTR_TYPE_STR, MAIL_ATTR_NEXTHOP, entry->queue->nexthop,
166 	       ATTR_TYPE_STR, MAIL_ATTR_ENCODING, message->encoding,
167 	       ATTR_TYPE_STR, MAIL_ATTR_SENDER, sender,
168 	       ATTR_TYPE_STR, MAIL_ATTR_DSN_ENVID, message->dsn_envid,
169 	       ATTR_TYPE_INT, MAIL_ATTR_DSN_RET, message->dsn_ret,
170 	       ATTR_TYPE_FUNC, msg_stats_print, (void *) &stats,
171     /* XXX Should be encapsulated with ATTR_TYPE_FUNC. */
172 	     ATTR_TYPE_STR, MAIL_ATTR_LOG_CLIENT_NAME, message->client_name,
173 	     ATTR_TYPE_STR, MAIL_ATTR_LOG_CLIENT_ADDR, message->client_addr,
174 	     ATTR_TYPE_STR, MAIL_ATTR_LOG_CLIENT_PORT, message->client_port,
175 	     ATTR_TYPE_STR, MAIL_ATTR_LOG_PROTO_NAME, message->client_proto,
176 	       ATTR_TYPE_STR, MAIL_ATTR_LOG_HELO_NAME, message->client_helo,
177     /* XXX Should be encapsulated with ATTR_TYPE_FUNC. */
178 	       ATTR_TYPE_STR, MAIL_ATTR_SASL_METHOD, message->sasl_method,
179 	     ATTR_TYPE_STR, MAIL_ATTR_SASL_USERNAME, message->sasl_username,
180 	       ATTR_TYPE_STR, MAIL_ATTR_SASL_SENDER, message->sasl_sender,
181     /* XXX Ditto if we want to pass TLS certificate info. */
182 	       ATTR_TYPE_STR, MAIL_ATTR_LOG_IDENT, message->log_ident,
183 	     ATTR_TYPE_STR, MAIL_ATTR_RWR_CONTEXT, message->rewrite_context,
184 	       ATTR_TYPE_INT, MAIL_ATTR_RCPT_COUNT, list.len,
185 	       ATTR_TYPE_END);
186     if (sender_buf != 0)
187 	vstring_free(sender_buf);
188     for (recipient = list.info; recipient < list.info + list.len; recipient++)
189 	attr_print(stream, ATTR_FLAG_NONE,
190 		   ATTR_TYPE_FUNC, rcpt_print, (void *) recipient,
191 		   ATTR_TYPE_END);
192     if (vstream_fflush(stream) != 0) {
193 	msg_warn("write to process (%s): %m", entry->queue->transport->name);
194 	return (-1);
195     } else {
196 	if (msg_verbose)
197 	    msg_info("qmgr_deliver: site `%s'", entry->queue->name);
198 	return (0);
199     }
200 }
201 
202 /* qmgr_deliver_abort - transport response watchdog */
203 
204 static void qmgr_deliver_abort(int unused_event, char *context)
205 {
206     QMGR_ENTRY *entry = (QMGR_ENTRY *) context;
207     QMGR_QUEUE *queue = entry->queue;
208     QMGR_TRANSPORT *transport = queue->transport;
209     QMGR_MESSAGE *message = entry->message;
210 
211     msg_fatal("%s: timeout receiving delivery status from transport: %s",
212 	      message->queue_id, transport->name);
213 }
214 
215 /* qmgr_deliver_update - process delivery status report */
216 
217 static void qmgr_deliver_update(int unused_event, char *context)
218 {
219     QMGR_ENTRY *entry = (QMGR_ENTRY *) context;
220     QMGR_QUEUE *queue = entry->queue;
221     QMGR_TRANSPORT *transport = queue->transport;
222     QMGR_MESSAGE *message = entry->message;
223     static DSN_BUF *dsb;
224     int     status;
225 
226     /*
227      * Release the delivery agent from a "hot" queue entry.
228      */
229 #define QMGR_DELIVER_RELEASE_AGENT(entry) do { \
230 	event_disable_readwrite(vstream_fileno(entry->stream)); \
231 	(void) vstream_fclose(entry->stream); \
232 	entry->stream = 0; \
233 	qmgr_deliver_concurrency--; \
234     } while (0)
235 
236     if (dsb == 0)
237 	dsb = dsb_create();
238 
239     /*
240      * The message transport has responded. Stop the watchdog timer.
241      */
242     event_cancel_timer(qmgr_deliver_abort, context);
243 
244     /*
245      * Retrieve the delivery agent status report. The numerical status code
246      * indicates if delivery should be tried again. The reason text is sent
247      * only when a site should be avoided for a while, so that the queue
248      * manager can log why it does not even try to schedule delivery to the
249      * affected recipients.
250      */
251     status = qmgr_deliver_final_reply(entry->stream, dsb);
252 
253     /*
254      * The mail delivery process failed for some reason (although delivery
255      * may have been successful). Back off with this transport type for a
256      * while. Dispose of queue entries for this transport that await
257      * selection (the todo lists). Stay away from queue entries that have
258      * been selected (the busy lists), or we would have dangling pointers.
259      * The queue itself won't go away before we dispose of the current queue
260      * entry.
261      */
262     if (status == DELIVER_STAT_CRASH) {
263 	message->flags |= DELIVER_STAT_DEFER;
264 #if 0
265 	whatsup = concatenate("unknown ", transport->name,
266 			      " mail transport error", (char *) 0);
267 	qmgr_transport_throttle(transport,
268 				DSN_SIMPLE(&dsb->dsn, "4.3.0", whatsup));
269 	myfree(whatsup);
270 #else
271 	qmgr_transport_throttle(transport,
272 				DSN_SIMPLE(&dsb->dsn, "4.3.0",
273 					   "unknown mail transport error"));
274 #endif
275 	msg_warn("transport %s failure -- see a previous warning/fatal/panic logfile record for the problem description",
276 		 transport->name);
277 
278 	/*
279 	 * Assume the worst and write a defer logfile record for each
280 	 * recipient. This omission was already present in the first queue
281 	 * manager implementation of 199703, and was fixed 200511.
282 	 *
283 	 * To avoid the synchronous qmgr_defer_recipient() operation for each
284 	 * recipient of this queue entry, release the delivery process and
285 	 * move the entry back to the todo queue. Let qmgr_defer_transport()
286 	 * log the recipient asynchronously if possible, and get out of here.
287 	 * Note: if asynchronous logging is not possible,
288 	 * qmgr_defer_transport() eventually invokes qmgr_entry_done() and
289 	 * the entry becomes a dangling pointer.
290 	 */
291 	QMGR_DELIVER_RELEASE_AGENT(entry);
292 	qmgr_entry_unselect(queue, entry);
293 	qmgr_defer_transport(transport, &dsb->dsn);
294 	return;
295     }
296 
297     /*
298      * This message must be tried again.
299      *
300      * If we have a problem talking to this site, back off with this site for a
301      * while; dispose of queue entries for this site that await selection
302      * (the todo list); stay away from queue entries that have been selected
303      * (the busy list), or we would have dangling pointers. The queue itself
304      * won't go away before we dispose of the current queue entry.
305      *
306      * XXX Caution: DSN_COPY() will panic on empty status or reason.
307      */
308 #define SUSPENDED	"delivery temporarily suspended: "
309 
310     if (status == DELIVER_STAT_DEFER) {
311 	message->flags |= DELIVER_STAT_DEFER;
312 	if (VSTRING_LEN(dsb->status)) {
313 	    /* Sanitize the DSN status/reason from the delivery agent. */
314 	    if (!dsn_valid(vstring_str(dsb->status)))
315 		vstring_strcpy(dsb->status, "4.0.0");
316 	    if (VSTRING_LEN(dsb->reason) == 0)
317 		vstring_strcpy(dsb->reason, "unknown error");
318 	    vstring_prepend(dsb->reason, SUSPENDED, sizeof(SUSPENDED) - 1);
319 	    if (QMGR_QUEUE_READY(queue)) {
320 		qmgr_queue_throttle(queue, DSN_FROM_DSN_BUF(dsb));
321 		if (QMGR_QUEUE_THROTTLED(queue))
322 		    qmgr_defer_todo(queue, &dsb->dsn);
323 	    }
324 	}
325     }
326 
327     /*
328      * No problems detected. Mark the transport and queue as alive. The queue
329      * itself won't go away before we dispose of the current queue entry.
330      */
331     if (status != DELIVER_STAT_CRASH && VSTRING_LEN(dsb->reason) == 0) {
332 	qmgr_transport_unthrottle(transport);
333 	qmgr_queue_unthrottle(queue);
334     }
335 
336     /*
337      * Release the delivery process, and give some other queue entry a chance
338      * to be delivered. When all recipients for a message have been tried,
339      * decide what to do next with this message: defer, bounce, delete.
340      */
341     QMGR_DELIVER_RELEASE_AGENT(entry);
342     qmgr_entry_done(entry, QMGR_QUEUE_BUSY);
343 }
344 
345 /* qmgr_deliver - deliver one per-site queue entry */
346 
347 void    qmgr_deliver(QMGR_TRANSPORT *transport, VSTREAM *stream)
348 {
349     QMGR_QUEUE *queue;
350     QMGR_ENTRY *entry;
351     DSN     dsn;
352 
353     /*
354      * Find out if this delivery process is really available. Once elected,
355      * the delivery process is supposed to express its happiness. If there is
356      * a problem, wipe the pending deliveries for this transport. This
357      * routine runs in response to an external event, so it does not run
358      * while some other queue manipulation is happening.
359      */
360     if (stream == 0 || qmgr_deliver_initial_reply(stream) != 0) {
361 #if 0
362 	whatsup = concatenate(transport->name,
363 			      " mail transport unavailable", (char *) 0);
364 	qmgr_transport_throttle(transport,
365 				DSN_SIMPLE(&dsn, "4.3.0", whatsup));
366 	myfree(whatsup);
367 #else
368 	qmgr_transport_throttle(transport,
369 				DSN_SIMPLE(&dsn, "4.3.0",
370 					   "mail transport unavailable"));
371 #endif
372 	qmgr_defer_transport(transport, &dsn);
373 	if (stream)
374 	    (void) vstream_fclose(stream);
375 	return;
376     }
377 
378     /*
379      * Find a suitable queue entry. Things may have changed since this
380      * transport was allocated. If no suitable entry is found,
381      * unceremoniously disconnect from the delivery process. The delivery
382      * agent request reading routine is prepared for the queue manager to
383      * change its mind for no apparent reason.
384      */
385     if ((queue = qmgr_queue_select(transport)) == 0
386 	|| (entry = qmgr_entry_select(queue)) == 0) {
387 	(void) vstream_fclose(stream);
388 	return;
389     }
390 
391     /*
392      * Send the queue file info and recipient info to the delivery process.
393      * If there is a problem, wipe the pending deliveries for this transport.
394      * This routine runs in response to an external event, so it does not run
395      * while some other queue manipulation is happening.
396      */
397     if (qmgr_deliver_send_request(entry, stream) < 0) {
398 	qmgr_entry_unselect(queue, entry);
399 #if 0
400 	whatsup = concatenate(transport->name,
401 			      " mail transport unavailable", (char *) 0);
402 	qmgr_transport_throttle(transport,
403 				DSN_SIMPLE(&dsn, "4.3.0", whatsup));
404 	myfree(whatsup);
405 #else
406 	qmgr_transport_throttle(transport,
407 				DSN_SIMPLE(&dsn, "4.3.0",
408 					   "mail transport unavailable"));
409 #endif
410 	qmgr_defer_transport(transport, &dsn);
411 	/* warning: entry and queue may be dangling pointers here */
412 	(void) vstream_fclose(stream);
413 	return;
414     }
415 
416     /*
417      * If we get this far, go wait for the delivery status report.
418      */
419     qmgr_deliver_concurrency++;
420     entry->stream = stream;
421     event_enable_read(vstream_fileno(stream),
422 		      qmgr_deliver_update, (char *) entry);
423 
424     /*
425      * Guard against broken systems.
426      */
427     event_request_timer(qmgr_deliver_abort, (char *) entry, var_daemon_timeout);
428 }
429