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