xref: /titanic_50/usr/src/cmd/sendmail/src/envelope.c (revision b9bc7f7832704fda46b4d6b04f3f7be1227dc644)
1 /*
2  * Copyright (c) 1998-2003, 2006 Sendmail, Inc. and its suppliers.
3  *	All rights reserved.
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.
7  *
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.
11  *
12  */
13 
14 #pragma ident	"%Z%%M%	%I%	%E% SMI"
15 
16 #include <sendmail.h>
17 
18 SM_RCSID("@(#)$Id: envelope.c,v 8.304 2007/04/18 17:15:49 ca Exp $")
19 
20 /*
21 **  CLRSESSENVELOPE -- clear session oriented data in an envelope
22 **
23 **	Parameters:
24 **		e -- the envelope to clear.
25 **
26 **	Returns:
27 **		none.
28 */
29 
30 void
31 clrsessenvelope(e)
32 	ENVELOPE *e;
33 {
34 #if SASL
35 	macdefine(&e->e_macro, A_PERM, macid("{auth_type}"), "");
36 	macdefine(&e->e_macro, A_PERM, macid("{auth_authen}"), "");
37 	macdefine(&e->e_macro, A_PERM, macid("{auth_author}"), "");
38 	macdefine(&e->e_macro, A_PERM, macid("{auth_ssf}"), "");
39 #endif /* SASL */
40 #if STARTTLS
41 	macdefine(&e->e_macro, A_PERM, macid("{cert_issuer}"), "");
42 	macdefine(&e->e_macro, A_PERM, macid("{cert_subject}"), "");
43 	macdefine(&e->e_macro, A_PERM, macid("{cipher_bits}"), "");
44 	macdefine(&e->e_macro, A_PERM, macid("{cipher}"), "");
45 	macdefine(&e->e_macro, A_PERM, macid("{tls_version}"), "");
46 	macdefine(&e->e_macro, A_PERM, macid("{verify}"), "");
47 # if _FFR_TLS_1
48 	macdefine(&e->e_macro, A_PERM, macid("{alg_bits}"), "");
49 	macdefine(&e->e_macro, A_PERM, macid("{cn_issuer}"), "");
50 	macdefine(&e->e_macro, A_PERM, macid("{cn_subject}"), "");
51 # endif /* _FFR_TLS_1 */
52 #endif /* STARTTLS */
53 }
54 
55 /*
56 **  NEWENVELOPE -- fill in a new envelope
57 **
58 **	Supports inheritance.
59 **
60 **	Parameters:
61 **		e -- the new envelope to fill in.
62 **		parent -- the envelope to be the parent of e.
63 **		rpool -- either NULL, or a pointer to a resource pool
64 **			from which envelope memory is allocated, and
65 **			to which envelope resources are attached.
66 **
67 **	Returns:
68 **		e.
69 **
70 **	Side Effects:
71 **		none.
72 */
73 
74 ENVELOPE *
75 newenvelope(e, parent, rpool)
76 	register ENVELOPE *e;
77 	register ENVELOPE *parent;
78 	SM_RPOOL_T *rpool;
79 {
80 	int sendmode, dm;
81 
82 	/*
83 	**  This code used to read:
84 	**	if (e == parent && e->e_parent != NULL)
85 	**		parent = e->e_parent;
86 	**  So if e == parent && e->e_parent == NULL then we would
87 	**  set e->e_parent = e, which creates a loop in the e_parent chain.
88 	**  This meant macvalue() could go into an infinite loop.
89 	*/
90 
91 	dm = DM_NOTSET;
92 	if (parent != NULL)
93 	{
94 		char *str;
95 
96 		sendmode = parent->e_sendmode;
97 		str = macvalue(macid("{deliveryMode}"), parent);
98 		if (str != NULL)
99 			dm = (int) str[0];
100 	}
101 	else
102 		sendmode = DM_NOTSET;
103 
104 	if (e == parent)
105 		parent = e->e_parent;
106 	clearenvelope(e, true, rpool);
107 	if (e == CurEnv)
108 		memmove((char *) &e->e_from,
109 			(char *) &NullAddress,
110 			sizeof(e->e_from));
111 	else
112 		memmove((char *) &e->e_from,
113 			(char *) &CurEnv->e_from,
114 			sizeof(e->e_from));
115 	e->e_parent = parent;
116 	assign_queueid(e);
117 	e->e_ctime = curtime();
118 #if _FFR_SESSID
119 	e->e_sessid = e->e_id;
120 #endif /* _FFR_SESSID */
121 	if (parent != NULL)
122 	{
123 		e->e_msgpriority = parent->e_msgsize;
124 #if _FFR_SESSID
125 		if (parent->e_sessid != NULL)
126 			e->e_sessid = sm_rpool_strdup_x(rpool,
127 							parent->e_sessid);
128 #endif /* _FFR_SESSID */
129 
130 		if (parent->e_quarmsg == NULL)
131 		{
132 			e->e_quarmsg = NULL;
133 			macdefine(&e->e_macro, A_PERM,
134 				  macid("{quarantine}"), "");
135 		}
136 		else
137 		{
138 			e->e_quarmsg = sm_rpool_strdup_x(rpool,
139 							 parent->e_quarmsg);
140 			macdefine(&e->e_macro, A_PERM,
141 				  macid("{quarantine}"), e->e_quarmsg);
142 		}
143 	}
144 	e->e_puthdr = putheader;
145 	e->e_putbody = putbody;
146 	if (CurEnv->e_xfp != NULL)
147 		(void) sm_io_flush(CurEnv->e_xfp, SM_TIME_DEFAULT);
148 	if (sendmode != DM_NOTSET)
149 		e->e_sendmode = sendmode;
150 	if (dm != DM_NOTSET)
151 		set_delivery_mode(dm, e);
152 
153 	return e;
154 }
155 
156 /* values for msg_timeout, see also IS_* below for usage (bit layout) */
157 #define MSG_T_O		0x01	/* normal timeout */
158 #define MSG_T_O_NOW	0x02	/* NOW timeout */
159 #define MSG_NOT_BY	0x04	/* Deliver-By time exceeded, mode R */
160 #define MSG_WARN	0x10	/* normal queue warning */
161 #define MSG_WARN_BY	0x20	/* Deliver-By time exceeded, mode N */
162 
163 #define IS_MSG_ERR(x)	(((x) & 0x0f) != 0)	/* return an error */
164 
165 /* immediate return */
166 #define IS_IMM_RET(x)	(((x) & (MSG_T_O_NOW|MSG_NOT_BY)) != 0)
167 #define IS_MSG_WARN(x)	(((x) & 0xf0) != 0)	/* return a warning */
168 
169 /*
170 **  DROPENVELOPE -- deallocate an envelope.
171 **
172 **	Parameters:
173 **		e -- the envelope to deallocate.
174 **		fulldrop -- if set, do return receipts.
175 **		split -- if true, split by recipient if message is queued up
176 **
177 **	Returns:
178 **		none.
179 **
180 **	Side Effects:
181 **		housekeeping necessary to dispose of an envelope.
182 **		Unlocks this queue file.
183 */
184 
185 void
186 dropenvelope(e, fulldrop, split)
187 	register ENVELOPE *e;
188 	bool fulldrop;
189 	bool split;
190 {
191 	bool panic = false;
192 	bool queueit = false;
193 	int msg_timeout = 0;
194 	bool failure_return = false;
195 	bool delay_return = false;
196 	bool success_return = false;
197 	bool pmnotify = bitset(EF_PM_NOTIFY, e->e_flags);
198 	bool done = false;
199 	register ADDRESS *q;
200 	char *id = e->e_id;
201 	time_t now;
202 	char buf[MAXLINE];
203 
204 	if (tTd(50, 1))
205 	{
206 		sm_dprintf("dropenvelope %p: id=", e);
207 		xputs(sm_debug_file(), e->e_id);
208 		sm_dprintf(", flags=");
209 		printenvflags(e);
210 		if (tTd(50, 10))
211 		{
212 			sm_dprintf("sendq=");
213 			printaddr(sm_debug_file(), e->e_sendqueue, true);
214 		}
215 	}
216 
217 	if (LogLevel > 84)
218 		sm_syslog(LOG_DEBUG, id,
219 			  "dropenvelope, e_flags=0x%lx, OpMode=%c, pid=%d",
220 			  e->e_flags, OpMode, (int) CurrentPid);
221 
222 	/* we must have an id to remove disk files */
223 	if (id == NULL)
224 		return;
225 
226 	/* if verify-only mode, we can skip most of this */
227 	if (OpMode == MD_VERIFY)
228 		goto simpledrop;
229 
230 	if (LogLevel > 4 && bitset(EF_LOGSENDER, e->e_flags))
231 		logsender(e, NULL);
232 	e->e_flags &= ~EF_LOGSENDER;
233 
234 	/* post statistics */
235 	poststats(StatFile);
236 
237 	/*
238 	**  Extract state information from dregs of send list.
239 	*/
240 
241 	now = curtime();
242 	if (now >= e->e_ctime + TimeOuts.to_q_return[e->e_timeoutclass])
243 		msg_timeout = MSG_T_O;
244 	if (IS_DLVR_RETURN(e) && e->e_deliver_by > 0 &&
245 	    now >= e->e_ctime + e->e_deliver_by &&
246 	    !bitset(EF_RESPONSE, e->e_flags))
247 	{
248 		msg_timeout = MSG_NOT_BY;
249 		e->e_flags |= EF_FATALERRS|EF_CLRQUEUE;
250 	}
251 	else if (TimeOuts.to_q_return[e->e_timeoutclass] == NOW &&
252 		 !bitset(EF_RESPONSE, e->e_flags))
253 	{
254 		msg_timeout = MSG_T_O_NOW;
255 		e->e_flags |= EF_FATALERRS|EF_CLRQUEUE;
256 	}
257 
258 	e->e_flags &= ~EF_QUEUERUN;
259 	for (q = e->e_sendqueue; q != NULL; q = q->q_next)
260 	{
261 		if (QS_IS_UNDELIVERED(q->q_state))
262 			queueit = true;
263 
264 		/* see if a notification is needed */
265 		if (bitset(QPINGONFAILURE, q->q_flags) &&
266 		    ((IS_MSG_ERR(msg_timeout) &&
267 		      QS_IS_UNDELIVERED(q->q_state)) ||
268 		     QS_IS_BADADDR(q->q_state) ||
269 		     IS_IMM_RET(msg_timeout)))
270 		{
271 			failure_return = true;
272 			if (!done && q->q_owner == NULL &&
273 			    !emptyaddr(&e->e_from))
274 			{
275 				(void) sendtolist(e->e_from.q_paddr, NULLADDR,
276 						  &e->e_errorqueue, 0, e);
277 				done = true;
278 			}
279 		}
280 		else if ((bitset(QPINGONSUCCESS, q->q_flags) &&
281 			  ((QS_IS_SENT(q->q_state) &&
282 			    bitnset(M_LOCALMAILER, q->q_mailer->m_flags)) ||
283 			   bitset(QRELAYED|QEXPANDED|QDELIVERED, q->q_flags))) ||
284 			  bitset(QBYTRACE, q->q_flags) ||
285 			  bitset(QBYNRELAY, q->q_flags))
286 		{
287 			success_return = true;
288 		}
289 	}
290 
291 	if (e->e_class < 0)
292 		e->e_flags |= EF_NO_BODY_RETN;
293 
294 	/*
295 	**  See if the message timed out.
296 	*/
297 
298 	if (!queueit)
299 		/* EMPTY */
300 		/* nothing to do */ ;
301 	else if (IS_MSG_ERR(msg_timeout))
302 	{
303 		if (failure_return)
304 		{
305 			if (msg_timeout == MSG_NOT_BY)
306 			{
307 				(void) sm_snprintf(buf, sizeof(buf),
308 					"delivery time expired %lds",
309 					e->e_deliver_by);
310 			}
311 			else
312 			{
313 				(void) sm_snprintf(buf, sizeof(buf),
314 					"Cannot send message for %s",
315 					pintvl(TimeOuts.to_q_return[e->e_timeoutclass],
316 						false));
317 			}
318 
319 			/* don't free, allocated from e_rpool */
320 			e->e_message = sm_rpool_strdup_x(e->e_rpool, buf);
321 			message(buf);
322 			e->e_flags |= EF_CLRQUEUE;
323 		}
324 		if (msg_timeout == MSG_NOT_BY)
325 		{
326 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
327 				"Delivery time (%lds) expired\n",
328 				e->e_deliver_by);
329 		}
330 		else
331 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
332 				"Message could not be delivered for %s\n",
333 				pintvl(TimeOuts.to_q_return[e->e_timeoutclass],
334 					false));
335 		(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
336 			"Message will be deleted from queue\n");
337 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
338 		{
339 			if (QS_IS_UNDELIVERED(q->q_state))
340 			{
341 				q->q_state = QS_BADADDR;
342 				if (msg_timeout == MSG_NOT_BY)
343 					q->q_status = "5.4.7";
344 				else
345 					q->q_status = "4.4.7";
346 			}
347 		}
348 	}
349 	else
350 	{
351 		if (TimeOuts.to_q_warning[e->e_timeoutclass] > 0 &&
352 		    now >= e->e_ctime +
353 				TimeOuts.to_q_warning[e->e_timeoutclass])
354 			msg_timeout = MSG_WARN;
355 		else if (IS_DLVR_NOTIFY(e) &&
356 			 e->e_deliver_by > 0 &&
357 			 now >= e->e_ctime + e->e_deliver_by)
358 			msg_timeout = MSG_WARN_BY;
359 
360 		if (IS_MSG_WARN(msg_timeout))
361 		{
362 			if (!bitset(EF_WARNING|EF_RESPONSE, e->e_flags) &&
363 			    e->e_class >= 0 &&
364 			    e->e_from.q_paddr != NULL &&
365 			    strcmp(e->e_from.q_paddr, "<>") != 0 &&
366 			    sm_strncasecmp(e->e_from.q_paddr, "owner-", 6) != 0 &&
367 			    (strlen(e->e_from.q_paddr) <= 8 ||
368 			     sm_strcasecmp(&e->e_from.q_paddr[strlen(e->e_from.q_paddr) - 8],
369 					   "-request") != 0))
370 			{
371 				for (q = e->e_sendqueue; q != NULL;
372 				     q = q->q_next)
373 				{
374 					if (QS_IS_UNDELIVERED(q->q_state)
375 #if _FFR_NODELAYDSN_ON_HOLD
376 					    && !bitnset(M_HOLD,
377 							q->q_mailer->m_flags)
378 #endif /* _FFR_NODELAYDSN_ON_HOLD */
379 					   )
380 					{
381 						if (msg_timeout ==
382 						    MSG_WARN_BY &&
383 						    (bitset(QPINGONDELAY,
384 							    q->q_flags) ||
385 						    !bitset(QHASNOTIFY,
386 							    q->q_flags))
387 						   )
388 						{
389 							q->q_flags |= QBYNDELAY;
390 							delay_return = true;
391 						}
392 						if (bitset(QPINGONDELAY,
393 							   q->q_flags))
394 						{
395 							q->q_flags |= QDELAYED;
396 							delay_return = true;
397 						}
398 					}
399 				}
400 			}
401 			if (delay_return)
402 			{
403 				if (msg_timeout == MSG_WARN_BY)
404 				{
405 					(void) sm_snprintf(buf, sizeof(buf),
406 						"Warning: Delivery time (%lds) exceeded",
407 						e->e_deliver_by);
408 				}
409 				else
410 					(void) sm_snprintf(buf, sizeof(buf),
411 						"Warning: could not send message for past %s",
412 						pintvl(TimeOuts.to_q_warning[e->e_timeoutclass],
413 							false));
414 
415 				/* don't free, allocated from e_rpool */
416 				e->e_message = sm_rpool_strdup_x(e->e_rpool,
417 								 buf);
418 				message(buf);
419 				e->e_flags |= EF_WARNING;
420 			}
421 			if (msg_timeout == MSG_WARN_BY)
422 			{
423 				(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
424 					"Warning: Delivery time (%lds) exceeded\n",
425 					e->e_deliver_by);
426 			}
427 			else
428 				(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
429 					"Warning: message still undelivered after %s\n",
430 					pintvl(TimeOuts.to_q_warning[e->e_timeoutclass],
431 					     false));
432 			(void) sm_io_fprintf(e->e_xfp, SM_TIME_DEFAULT,
433 				      "Will keep trying until message is %s old\n",
434 				      pintvl(TimeOuts.to_q_return[e->e_timeoutclass],
435 					     false));
436 		}
437 	}
438 
439 	if (tTd(50, 2))
440 		sm_dprintf("failure_return=%d delay_return=%d success_return=%d queueit=%d\n",
441 			failure_return, delay_return, success_return, queueit);
442 
443 	/*
444 	**  If we had some fatal error, but no addresses are marked as
445 	**  bad, mark them _all_ as bad.
446 	*/
447 
448 	if (bitset(EF_FATALERRS, e->e_flags) && !failure_return)
449 	{
450 		for (q = e->e_sendqueue; q != NULL; q = q->q_next)
451 		{
452 			if ((QS_IS_OK(q->q_state) ||
453 			     QS_IS_VERIFIED(q->q_state)) &&
454 			    bitset(QPINGONFAILURE, q->q_flags))
455 			{
456 				failure_return = true;
457 				q->q_state = QS_BADADDR;
458 			}
459 		}
460 	}
461 
462 	/*
463 	**  Send back return receipts as requested.
464 	*/
465 
466 	if (success_return && !failure_return && !delay_return && fulldrop &&
467 	    !bitset(PRIV_NORECEIPTS, PrivacyFlags) &&
468 	    strcmp(e->e_from.q_paddr, "<>") != 0)
469 	{
470 		auto ADDRESS *rlist = NULL;
471 
472 		if (tTd(50, 8))
473 			sm_dprintf("dropenvelope(%s): sending return receipt\n",
474 				id);
475 		e->e_flags |= EF_SENDRECEIPT;
476 		(void) sendtolist(e->e_from.q_paddr, NULLADDR, &rlist, 0, e);
477 		(void) returntosender("Return receipt", rlist, RTSF_NO_BODY, e);
478 	}
479 	e->e_flags &= ~EF_SENDRECEIPT;
480 
481 	/*
482 	**  Arrange to send error messages if there are fatal errors.
483 	*/
484 
485 	if ((failure_return || delay_return) && e->e_errormode != EM_QUIET)
486 	{
487 		if (tTd(50, 8))
488 			sm_dprintf("dropenvelope(%s): saving mail\n", id);
489 		panic = savemail(e, !bitset(EF_NO_BODY_RETN, e->e_flags));
490 	}
491 
492 	/*
493 	**  Arrange to send warning messages to postmaster as requested.
494 	*/
495 
496 	if ((failure_return || pmnotify) &&
497 	    PostMasterCopy != NULL &&
498 	    !bitset(EF_RESPONSE, e->e_flags) &&
499 	    e->e_class >= 0)
500 	{
501 		auto ADDRESS *rlist = NULL;
502 		char pcopy[MAXNAME];
503 
504 		if (failure_return)
505 		{
506 			expand(PostMasterCopy, pcopy, sizeof(pcopy), e);
507 
508 			if (tTd(50, 8))
509 				sm_dprintf("dropenvelope(%s): sending postmaster copy to %s\n",
510 					id, pcopy);
511 			(void) sendtolist(pcopy, NULLADDR, &rlist, 0, e);
512 		}
513 		if (pmnotify)
514 			(void) sendtolist("postmaster", NULLADDR,
515 					  &rlist, 0, e);
516 		(void) returntosender(e->e_message, rlist,
517 				      RTSF_PM_BOUNCE|RTSF_NO_BODY, e);
518 	}
519 
520 	/*
521 	**  Instantiate or deinstantiate the queue.
522 	*/
523 
524 simpledrop:
525 	if (tTd(50, 8))
526 		sm_dprintf("dropenvelope(%s): at simpledrop, queueit=%d\n",
527 			id, queueit);
528 	if (!queueit || bitset(EF_CLRQUEUE, e->e_flags))
529 	{
530 		if (tTd(50, 1))
531 		{
532 			sm_dprintf("\n===== Dropping queue files for %s... queueit=%d, e_flags=",
533 				e->e_id, queueit);
534 			printenvflags(e);
535 		}
536 		if (!panic)
537 		{
538 			if (e->e_dfp != NULL)
539 			{
540 				(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
541 				e->e_dfp = NULL;
542 			}
543 			(void) xunlink(queuename(e, DATAFL_LETTER));
544 		}
545 		if (panic && QueueMode == QM_LOST)
546 		{
547 			/*
548 			**  leave the Qf file behind as
549 			**  the delivery attempt failed.
550 			*/
551 
552 			/* EMPTY */
553 		}
554 		else
555 		if (xunlink(queuename(e, ANYQFL_LETTER)) == 0)
556 		{
557 			/* add to available space in filesystem */
558 			updfs(e, -1, panic ? 0 : -1, "dropenvelope");
559 		}
560 
561 		if (e->e_ntries > 0 && LogLevel > 9)
562 			sm_syslog(LOG_INFO, id, "done; delay=%s, ntries=%d",
563 				  pintvl(curtime() - e->e_ctime, true),
564 				  e->e_ntries);
565 	}
566 	else if (queueit || !bitset(EF_INQUEUE, e->e_flags))
567 	{
568 		if (!split)
569 			queueup(e, false, true);
570 		else
571 		{
572 			ENVELOPE *oldsib;
573 			ENVELOPE *ee;
574 
575 			/*
576 			**  Save old sibling and set it to NULL to avoid
577 			**  queueing up the same envelopes again.
578 			**  This requires that envelopes in that list have
579 			**  been take care of before (or at some other place).
580 			*/
581 
582 			oldsib = e->e_sibling;
583 			e->e_sibling = NULL;
584 			if (!split_by_recipient(e) &&
585 			    bitset(EF_FATALERRS, e->e_flags))
586 			{
587 				syserr("!dropenvelope(%s): cannot commit data file %s, uid=%d",
588 					e->e_id, queuename(e, DATAFL_LETTER),
589 					(int) geteuid());
590 			}
591 			for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
592 				queueup(ee, false, true);
593 			queueup(e, false, true);
594 
595 			/* clean up */
596 			for (ee = e->e_sibling; ee != NULL; ee = ee->e_sibling)
597 			{
598 				/* now unlock the job */
599 				if (tTd(50, 8))
600 					sm_dprintf("dropenvelope(%s): unlocking job\n",
601 						   ee->e_id);
602 				closexscript(ee);
603 				unlockqueue(ee);
604 
605 				/* this envelope is marked unused */
606 				if (ee->e_dfp != NULL)
607 				{
608 					(void) sm_io_close(ee->e_dfp,
609 							   SM_TIME_DEFAULT);
610 					ee->e_dfp = NULL;
611 				}
612 				ee->e_id = NULL;
613 				ee->e_flags &= ~EF_HAS_DF;
614 			}
615 			e->e_sibling = oldsib;
616 		}
617 	}
618 
619 	/* now unlock the job */
620 	if (tTd(50, 8))
621 		sm_dprintf("dropenvelope(%s): unlocking job\n", id);
622 	closexscript(e);
623 	unlockqueue(e);
624 
625 	/* make sure that this envelope is marked unused */
626 	if (e->e_dfp != NULL)
627 	{
628 		(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
629 		e->e_dfp = NULL;
630 	}
631 	e->e_id = NULL;
632 	e->e_flags &= ~EF_HAS_DF;
633 }
634 /*
635 **  CLEARENVELOPE -- clear an envelope without unlocking
636 **
637 **	This is normally used by a child process to get a clean
638 **	envelope without disturbing the parent.
639 **
640 **	Parameters:
641 **		e -- the envelope to clear.
642 **		fullclear - if set, the current envelope is total
643 **			garbage and should be ignored; otherwise,
644 **			release any resources it may indicate.
645 **		rpool -- either NULL, or a pointer to a resource pool
646 **			from which envelope memory is allocated, and
647 **			to which envelope resources are attached.
648 **
649 **	Returns:
650 **		none.
651 **
652 **	Side Effects:
653 **		Closes files associated with the envelope.
654 **		Marks the envelope as unallocated.
655 */
656 
657 void
658 clearenvelope(e, fullclear, rpool)
659 	register ENVELOPE *e;
660 	bool fullclear;
661 	SM_RPOOL_T *rpool;
662 {
663 	register HDR *bh;
664 	register HDR **nhp;
665 	extern ENVELOPE BlankEnvelope;
666 	char **p;
667 
668 	if (!fullclear)
669 	{
670 		/* clear out any file information */
671 		if (e->e_xfp != NULL)
672 			(void) sm_io_close(e->e_xfp, SM_TIME_DEFAULT);
673 		if (e->e_dfp != NULL)
674 			(void) sm_io_close(e->e_dfp, SM_TIME_DEFAULT);
675 		e->e_xfp = e->e_dfp = NULL;
676 	}
677 
678 	/*
679 	**  Copy BlankEnvelope into *e.
680 	**  It is not safe to simply copy pointers to strings;
681 	**  the strings themselves must be copied (or set to NULL).
682 	**  The problem is that when we assign a new string value to
683 	**  a member of BlankEnvelope, we free the old string.
684 	**  We did not need to do this copying in sendmail 8.11 :-(
685 	**  and it is a potential performance hit.  Reference counted
686 	**  strings are one way out.
687 	*/
688 
689 	*e = BlankEnvelope;
690 	e->e_message = NULL;
691 	e->e_qfletter = '\0';
692 	e->e_quarmsg = NULL;
693 	macdefine(&e->e_macro, A_PERM, macid("{quarantine}"), "");
694 
695 	/*
696 	**  Copy the macro table.
697 	**  We might be able to avoid this by zeroing the macro table
698 	**  and always searching BlankEnvelope.e_macro after e->e_macro
699 	**  in macvalue().
700 	*/
701 
702 	for (p = &e->e_macro.mac_table[0];
703 	     p <= &e->e_macro.mac_table[MAXMACROID];
704 	     ++p)
705 	{
706 		if (*p != NULL)
707 			*p = sm_rpool_strdup_x(rpool, *p);
708 	}
709 
710 	/*
711 	**  XXX There are many strings in the envelope structure
712 	**  XXX that we are not attempting to copy here.
713 	**  XXX Investigate this further.
714 	*/
715 
716 	e->e_rpool = rpool;
717 	e->e_macro.mac_rpool = rpool;
718 	if (Verbose)
719 		set_delivery_mode(SM_DELIVER, e);
720 	bh = BlankEnvelope.e_header;
721 	nhp = &e->e_header;
722 	while (bh != NULL)
723 	{
724 		*nhp = (HDR *) sm_rpool_malloc_x(rpool, sizeof(*bh));
725 		memmove((char *) *nhp, (char *) bh, sizeof(*bh));
726 		bh = bh->h_link;
727 		nhp = &(*nhp)->h_link;
728 	}
729 }
730 /*
731 **  INITSYS -- initialize instantiation of system
732 **
733 **	In Daemon mode, this is done in the child.
734 **
735 **	Parameters:
736 **		e -- the envelope to use.
737 **
738 **	Returns:
739 **		none.
740 **
741 **	Side Effects:
742 **		Initializes the system macros, some global variables,
743 **		etc.  In particular, the current time in various
744 **		forms is set.
745 */
746 
747 void
748 initsys(e)
749 	register ENVELOPE *e;
750 {
751 	char buf[10];
752 #ifdef TTYNAME
753 	static char ybuf[60];			/* holds tty id */
754 	register char *p;
755 	extern char *ttyname();
756 #endif /* TTYNAME */
757 
758 	/*
759 	**  Give this envelope a reality.
760 	**	I.e., an id, a transcript, and a creation time.
761 	**  We don't select the queue until all of the recipients are known.
762 	*/
763 
764 	openxscript(e);
765 	e->e_ctime = curtime();
766 	e->e_qfletter = '\0';
767 
768 	/*
769 	**  Set OutChannel to something useful if stdout isn't it.
770 	**	This arranges that any extra stuff the mailer produces
771 	**	gets sent back to the user on error (because it is
772 	**	tucked away in the transcript).
773 	*/
774 
775 	if (OpMode == MD_DAEMON && bitset(EF_QUEUERUN, e->e_flags) &&
776 	    e->e_xfp != NULL)
777 		OutChannel = e->e_xfp;
778 
779 	/*
780 	**  Set up some basic system macros.
781 	*/
782 
783 	/* process id */
784 	(void) sm_snprintf(buf, sizeof(buf), "%d", (int) CurrentPid);
785 	macdefine(&e->e_macro, A_TEMP, 'p', buf);
786 
787 	/* hop count */
788 	(void) sm_snprintf(buf, sizeof(buf), "%d", e->e_hopcount);
789 	macdefine(&e->e_macro, A_TEMP, 'c', buf);
790 
791 	/* time as integer, unix time, arpa time */
792 	settime(e);
793 
794 	/* Load average */
795 	sm_getla();
796 
797 #ifdef TTYNAME
798 	/* tty name */
799 	if (macvalue('y', e) == NULL)
800 	{
801 		p = ttyname(2);
802 		if (p != NULL)
803 		{
804 			if (strrchr(p, '/') != NULL)
805 				p = strrchr(p, '/') + 1;
806 			(void) sm_strlcpy(ybuf, sizeof(ybuf), p);
807 			macdefine(&e->e_macro, A_PERM, 'y', ybuf);
808 		}
809 	}
810 #endif /* TTYNAME */
811 }
812 /*
813 **  SETTIME -- set the current time.
814 **
815 **	Parameters:
816 **		e -- the envelope in which the macros should be set.
817 **
818 **	Returns:
819 **		none.
820 **
821 **	Side Effects:
822 **		Sets the various time macros -- $a, $b, $d, $t.
823 */
824 
825 void
826 settime(e)
827 	register ENVELOPE *e;
828 {
829 	register char *p;
830 	auto time_t now;
831 	char buf[30];
832 	register struct tm *tm;
833 
834 	now = curtime();
835 	(void) sm_snprintf(buf, sizeof(buf), "%ld", (long) now);
836 	macdefine(&e->e_macro, A_TEMP, macid("{time}"), buf);
837 	tm = gmtime(&now);
838 	(void) sm_snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d",
839 			   tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
840 			   tm->tm_hour, tm->tm_min);
841 	macdefine(&e->e_macro, A_TEMP, 't', buf);
842 	(void) sm_strlcpy(buf, ctime(&now), sizeof(buf));
843 	p = strchr(buf, '\n');
844 	if (p != NULL)
845 		*p = '\0';
846 	macdefine(&e->e_macro, A_TEMP, 'd', buf);
847 	macdefine(&e->e_macro, A_TEMP, 'b', arpadate(buf));
848 	if (macvalue('a', e) == NULL)
849 		macdefine(&e->e_macro, A_PERM, 'a', macvalue('b', e));
850 }
851 /*
852 **  OPENXSCRIPT -- Open transcript file
853 **
854 **	Creates a transcript file for possible eventual mailing or
855 **	sending back.
856 **
857 **	Parameters:
858 **		e -- the envelope to create the transcript in/for.
859 **
860 **	Returns:
861 **		none
862 **
863 **	Side Effects:
864 **		Creates the transcript file.
865 */
866 
867 #ifndef O_APPEND
868 # define O_APPEND	0
869 #endif /* ! O_APPEND */
870 
871 void
872 openxscript(e)
873 	register ENVELOPE *e;
874 {
875 	register char *p;
876 
877 	if (e->e_xfp != NULL)
878 		return;
879 
880 #if 0
881 	if (e->e_lockfp == NULL && bitset(EF_INQUEUE, e->e_flags))
882 		syserr("openxscript: job not locked");
883 #endif /* 0 */
884 
885 	p = queuename(e, XSCRPT_LETTER);
886 	e->e_xfp = bfopen(p, FileMode, XscriptFileBufferSize,
887 			  SFF_NOTEXCL|SFF_OPENASROOT);
888 
889 	if (e->e_xfp == NULL)
890 	{
891 		syserr("Can't create transcript file %s", p);
892 		e->e_xfp = sm_io_open(SmFtStdio, SM_TIME_DEFAULT,
893 				      SM_PATH_DEVNULL, SM_IO_RDWR, NULL);
894 		if (e->e_xfp == NULL)
895 			syserr("!Can't open %s", SM_PATH_DEVNULL);
896 	}
897 	(void) sm_io_setvbuf(e->e_xfp, SM_TIME_DEFAULT, NULL, SM_IO_LBF, 0);
898 	if (tTd(46, 9))
899 	{
900 		sm_dprintf("openxscript(%s):\n  ", p);
901 		dumpfd(sm_io_getinfo(e->e_xfp, SM_IO_WHAT_FD, NULL), true,
902 		       false);
903 	}
904 }
905 /*
906 **  CLOSEXSCRIPT -- close the transcript file.
907 **
908 **	Parameters:
909 **		e -- the envelope containing the transcript to close.
910 **
911 **	Returns:
912 **		none.
913 **
914 **	Side Effects:
915 **		none.
916 */
917 
918 void
919 closexscript(e)
920 	register ENVELOPE *e;
921 {
922 	if (e->e_xfp == NULL)
923 		return;
924 #if 0
925 	if (e->e_lockfp == NULL)
926 		syserr("closexscript: job not locked");
927 #endif /* 0 */
928 	(void) sm_io_close(e->e_xfp, SM_TIME_DEFAULT);
929 	e->e_xfp = NULL;
930 }
931 /*
932 **  SETSENDER -- set the person who this message is from
933 **
934 **	Under certain circumstances allow the user to say who
935 **	s/he is (using -f or -r).  These are:
936 **	1.  The user's uid is zero (root).
937 **	2.  The user's login name is in an approved list (typically
938 **	    from a network server).
939 **	3.  The address the user is trying to claim has a
940 **	    "!" character in it (since #2 doesn't do it for
941 **	    us if we are dialing out for UUCP).
942 **	A better check to replace #3 would be if the
943 **	effective uid is "UUCP" -- this would require me
944 **	to rewrite getpwent to "grab" uucp as it went by,
945 **	make getname more nasty, do another passwd file
946 **	scan, or compile the UID of "UUCP" into the code,
947 **	all of which are reprehensible.
948 **
949 **	Assuming all of these fail, we figure out something
950 **	ourselves.
951 **
952 **	Parameters:
953 **		from -- the person we would like to believe this message
954 **			is from, as specified on the command line.
955 **		e -- the envelope in which we would like the sender set.
956 **		delimptr -- if non-NULL, set to the location of the
957 **			trailing delimiter.
958 **		delimchar -- the character that will delimit the sender
959 **			address.
960 **		internal -- set if this address is coming from an internal
961 **			source such as an owner alias.
962 **
963 **	Returns:
964 **		none.
965 **
966 **	Side Effects:
967 **		sets sendmail's notion of who the from person is.
968 */
969 
970 void
971 setsender(from, e, delimptr, delimchar, internal)
972 	char *from;
973 	register ENVELOPE *e;
974 	char **delimptr;
975 	int delimchar;
976 	bool internal;
977 {
978 	register char **pvp;
979 	char *realname = NULL;
980 	char *bp;
981 	char buf[MAXNAME + 2];
982 	char pvpbuf[PSBUFSIZE];
983 	extern char *FullName;
984 
985 	if (tTd(45, 1))
986 		sm_dprintf("setsender(%s)\n", from == NULL ? "" : from);
987 
988 	/* may be set from earlier calls */
989 	macdefine(&e->e_macro, A_PERM, 'x', "");
990 
991 	/*
992 	**  Figure out the real user executing us.
993 	**	Username can return errno != 0 on non-errors.
994 	*/
995 
996 	if (bitset(EF_QUEUERUN, e->e_flags) || OpMode == MD_SMTP ||
997 	    OpMode == MD_ARPAFTP || OpMode == MD_DAEMON)
998 		realname = from;
999 	if (realname == NULL || realname[0] == '\0')
1000 		realname = username();
1001 
1002 	if (ConfigLevel < 2)
1003 		SuprErrs = true;
1004 
1005 	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s");
1006 
1007 	/* preset state for then clause in case from == NULL */
1008 	e->e_from.q_state = QS_BADADDR;
1009 	e->e_from.q_flags = 0;
1010 	if (from == NULL ||
1011 	    parseaddr(from, &e->e_from, RF_COPYALL|RF_SENDERADDR,
1012 		      delimchar, delimptr, e, false) == NULL ||
1013 	    QS_IS_BADADDR(e->e_from.q_state) ||
1014 	    e->e_from.q_mailer == ProgMailer ||
1015 	    e->e_from.q_mailer == FileMailer ||
1016 	    e->e_from.q_mailer == InclMailer)
1017 	{
1018 		/* log garbage addresses for traceback */
1019 		if (from != NULL && LogLevel > 2)
1020 		{
1021 			char *p;
1022 			char ebuf[MAXNAME * 2 + 2];
1023 
1024 			p = macvalue('_', e);
1025 			if (p == NULL)
1026 			{
1027 				char *host = RealHostName;
1028 
1029 				if (host == NULL)
1030 					host = MyHostName;
1031 				(void) sm_snprintf(ebuf, sizeof(ebuf),
1032 						   "%.*s@%.*s", MAXNAME,
1033 						   realname, MAXNAME, host);
1034 				p = ebuf;
1035 			}
1036 			sm_syslog(LOG_NOTICE, e->e_id,
1037 				  "setsender: %s: invalid or unparsable, received from %s",
1038 				  shortenstring(from, 83), p);
1039 		}
1040 		if (from != NULL)
1041 		{
1042 			if (!QS_IS_BADADDR(e->e_from.q_state))
1043 			{
1044 				/* it was a bogus mailer in the from addr */
1045 				e->e_status = "5.1.7";
1046 				usrerrenh(e->e_status,
1047 					  "553 Invalid sender address");
1048 			}
1049 			SuprErrs = true;
1050 		}
1051 		if (from == realname ||
1052 		    parseaddr(from = realname,
1053 			      &e->e_from, RF_COPYALL|RF_SENDERADDR, ' ',
1054 			      NULL, e, false) == NULL)
1055 		{
1056 			char nbuf[100];
1057 
1058 			SuprErrs = true;
1059 			expand("\201n", nbuf, sizeof(nbuf), e);
1060 			from = sm_rpool_strdup_x(e->e_rpool, nbuf);
1061 			if (parseaddr(from, &e->e_from, RF_COPYALL, ' ',
1062 				      NULL, e, false) == NULL &&
1063 			    parseaddr(from = "postmaster", &e->e_from,
1064 				      RF_COPYALL, ' ', NULL, e, false) == NULL)
1065 				syserr("553 5.3.0 setsender: can't even parse postmaster!");
1066 		}
1067 	}
1068 	else
1069 		FromFlag = true;
1070 	e->e_from.q_state = QS_SENDER;
1071 	if (tTd(45, 5))
1072 	{
1073 		sm_dprintf("setsender: QS_SENDER ");
1074 		printaddr(sm_debug_file(), &e->e_from, false);
1075 	}
1076 	SuprErrs = false;
1077 
1078 #if USERDB
1079 	if (bitnset(M_CHECKUDB, e->e_from.q_mailer->m_flags))
1080 	{
1081 		register char *p;
1082 
1083 		p = udbsender(e->e_from.q_user, e->e_rpool);
1084 		if (p != NULL)
1085 			from = p;
1086 	}
1087 #endif /* USERDB */
1088 
1089 	if (bitnset(M_HASPWENT, e->e_from.q_mailer->m_flags))
1090 	{
1091 		SM_MBDB_T user;
1092 
1093 		if (!internal)
1094 		{
1095 			/* if the user already given fullname don't redefine */
1096 			if (FullName == NULL)
1097 				FullName = macvalue('x', e);
1098 			if (FullName != NULL)
1099 			{
1100 				if (FullName[0] == '\0')
1101 					FullName = NULL;
1102 				else
1103 					FullName = newstr(FullName);
1104 			}
1105 		}
1106 
1107 		if (e->e_from.q_user[0] != '\0' &&
1108 		    sm_mbdb_lookup(e->e_from.q_user, &user) == EX_OK)
1109 		{
1110 			/*
1111 			**  Process passwd file entry.
1112 			*/
1113 
1114 			/* extract home directory */
1115 			if (*user.mbdb_homedir == '\0')
1116 				e->e_from.q_home = NULL;
1117 			else if (strcmp(user.mbdb_homedir, "/") == 0)
1118 				e->e_from.q_home = "";
1119 			else
1120 				e->e_from.q_home = sm_rpool_strdup_x(e->e_rpool,
1121 							user.mbdb_homedir);
1122 			macdefine(&e->e_macro, A_PERM, 'z', e->e_from.q_home);
1123 
1124 			/* extract user and group id */
1125 			if (user.mbdb_uid != SM_NO_UID)
1126 			{
1127 				e->e_from.q_uid = user.mbdb_uid;
1128 				e->e_from.q_gid = user.mbdb_gid;
1129 				e->e_from.q_flags |= QGOODUID;
1130 			}
1131 
1132 			/* extract full name from passwd file */
1133 			if (FullName == NULL && !internal &&
1134 			    user.mbdb_fullname[0] != '\0' &&
1135 			    strcmp(user.mbdb_name, e->e_from.q_user) == 0)
1136 			{
1137 				FullName = newstr(user.mbdb_fullname);
1138 			}
1139 		}
1140 		else
1141 		{
1142 			e->e_from.q_home = NULL;
1143 		}
1144 		if (FullName != NULL && !internal)
1145 			macdefine(&e->e_macro, A_TEMP, 'x', FullName);
1146 	}
1147 	else if (!internal && OpMode != MD_DAEMON && OpMode != MD_SMTP)
1148 	{
1149 		if (e->e_from.q_home == NULL)
1150 		{
1151 			e->e_from.q_home = getenv("HOME");
1152 			if (e->e_from.q_home != NULL)
1153 			{
1154 				if (*e->e_from.q_home == '\0')
1155 					e->e_from.q_home = NULL;
1156 				else if (strcmp(e->e_from.q_home, "/") == 0)
1157 					e->e_from.q_home++;
1158 			}
1159 		}
1160 		e->e_from.q_uid = RealUid;
1161 		e->e_from.q_gid = RealGid;
1162 		e->e_from.q_flags |= QGOODUID;
1163 	}
1164 
1165 	/*
1166 	**  Rewrite the from person to dispose of possible implicit
1167 	**	links in the net.
1168 	*/
1169 
1170 	pvp = prescan(from, delimchar, pvpbuf, sizeof(pvpbuf), NULL,
1171 			IntTokenTab, false);
1172 	if (pvp == NULL)
1173 	{
1174 		/* don't need to give error -- prescan did that already */
1175 		if (LogLevel > 2)
1176 			sm_syslog(LOG_NOTICE, e->e_id,
1177 				  "cannot prescan from (%s)",
1178 				  shortenstring(from, MAXSHORTSTR));
1179 		finis(true, true, ExitStat);
1180 	}
1181 	(void) REWRITE(pvp, 3, e);
1182 	(void) REWRITE(pvp, 1, e);
1183 	(void) REWRITE(pvp, 4, e);
1184 	macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
1185 	bp = buf + 1;
1186 	cataddr(pvp, NULL, bp, sizeof(buf) - 2, '\0', false);
1187 	if (*bp == '@' && !bitnset(M_NOBRACKET, e->e_from.q_mailer->m_flags))
1188 	{
1189 		/* heuristic: route-addr: add angle brackets */
1190 		(void) sm_strlcat(bp, ">", sizeof(buf) - 1);
1191 		*--bp = '<';
1192 	}
1193 	e->e_sender = sm_rpool_strdup_x(e->e_rpool, bp);
1194 	macdefine(&e->e_macro, A_PERM, 'f', e->e_sender);
1195 
1196 	/* save the domain spec if this mailer wants it */
1197 	if (e->e_from.q_mailer != NULL &&
1198 	    bitnset(M_CANONICAL, e->e_from.q_mailer->m_flags))
1199 	{
1200 		char **lastat;
1201 
1202 		/* get rid of any pesky angle brackets */
1203 		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), "e s");
1204 		(void) REWRITE(pvp, 3, e);
1205 		(void) REWRITE(pvp, 1, e);
1206 		(void) REWRITE(pvp, 4, e);
1207 		macdefine(&e->e_macro, A_PERM, macid("{addr_type}"), NULL);
1208 
1209 		/* strip off to the last "@" sign */
1210 		for (lastat = NULL; *pvp != NULL; pvp++)
1211 		{
1212 			if (strcmp(*pvp, "@") == 0)
1213 				lastat = pvp;
1214 		}
1215 		if (lastat != NULL)
1216 		{
1217 			e->e_fromdomain = copyplist(lastat, true, e->e_rpool);
1218 			if (tTd(45, 3))
1219 			{
1220 				sm_dprintf("Saving from domain: ");
1221 				printav(sm_debug_file(), e->e_fromdomain);
1222 			}
1223 		}
1224 	}
1225 }
1226 /*
1227 **  PRINTENVFLAGS -- print envelope flags for debugging
1228 **
1229 **	Parameters:
1230 **		e -- the envelope with the flags to be printed.
1231 **
1232 **	Returns:
1233 **		none.
1234 */
1235 
1236 struct eflags
1237 {
1238 	char		*ef_name;
1239 	unsigned long	ef_bit;
1240 };
1241 
1242 static struct eflags	EnvelopeFlags[] =
1243 {
1244 	{ "OLDSTYLE",		EF_OLDSTYLE	},
1245 	{ "INQUEUE",		EF_INQUEUE	},
1246 	{ "NO_BODY_RETN",	EF_NO_BODY_RETN	},
1247 	{ "CLRQUEUE",		EF_CLRQUEUE	},
1248 	{ "SENDRECEIPT",	EF_SENDRECEIPT	},
1249 	{ "FATALERRS",		EF_FATALERRS	},
1250 	{ "DELETE_BCC",		EF_DELETE_BCC	},
1251 	{ "RESPONSE",		EF_RESPONSE	},
1252 	{ "RESENT",		EF_RESENT	},
1253 	{ "VRFYONLY",		EF_VRFYONLY	},
1254 	{ "WARNING",		EF_WARNING	},
1255 	{ "QUEUERUN",		EF_QUEUERUN	},
1256 	{ "GLOBALERRS",		EF_GLOBALERRS	},
1257 	{ "PM_NOTIFY",		EF_PM_NOTIFY	},
1258 	{ "METOO",		EF_METOO	},
1259 	{ "LOGSENDER",		EF_LOGSENDER	},
1260 	{ "NORECEIPT",		EF_NORECEIPT	},
1261 	{ "HAS8BIT",		EF_HAS8BIT	},
1262 	{ "NL_NOT_EOL",		EF_NL_NOT_EOL	},
1263 	{ "CRLF_NOT_EOL",	EF_CRLF_NOT_EOL	},
1264 	{ "RET_PARAM",		EF_RET_PARAM	},
1265 	{ "HAS_DF",		EF_HAS_DF	},
1266 	{ "IS_MIME",		EF_IS_MIME	},
1267 	{ "DONT_MIME",		EF_DONT_MIME	},
1268 	{ "DISCARD",		EF_DISCARD	},
1269 	{ "TOOBIG",		EF_TOOBIG	},
1270 	{ "SPLIT",		EF_SPLIT	},
1271 	{ "UNSAFE",		EF_UNSAFE	},
1272 	{ NULL,			0		}
1273 };
1274 
1275 void
1276 printenvflags(e)
1277 	register ENVELOPE *e;
1278 {
1279 	register struct eflags *ef;
1280 	bool first = true;
1281 
1282 	sm_dprintf("%lx", e->e_flags);
1283 	for (ef = EnvelopeFlags; ef->ef_name != NULL; ef++)
1284 	{
1285 		if (!bitset(ef->ef_bit, e->e_flags))
1286 			continue;
1287 		if (first)
1288 			sm_dprintf("<%s", ef->ef_name);
1289 		else
1290 			sm_dprintf(",%s", ef->ef_name);
1291 		first = false;
1292 	}
1293 	if (!first)
1294 		sm_dprintf(">\n");
1295 }
1296