Import sendmail 8.13.7
[dragonfly.git] / contrib / sendmail-8.13.7 / sendmail / headers.c
1 /*
2  * Copyright (c) 1998-2004, 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 #include <sendmail.h>
15
16 SM_RCSID("@(#)$Id: headers.c,v 8.291 2006/03/24 01:01:56 ca Exp $")
17
18 static HDR      *allocheader __P((char *, char *, int, SM_RPOOL_T *));
19 static size_t   fix_mime_header __P((HDR *, ENVELOPE *));
20 static int      priencode __P((char *));
21 static bool     put_vanilla_header __P((HDR *, char *, MCI *));
22
23 /*
24 **  SETUPHEADERS -- initialize headers in symbol table
25 **
26 **      Parameters:
27 **              none
28 **
29 **      Returns:
30 **              none
31 */
32
33 void
34 setupheaders()
35 {
36         struct hdrinfo *hi;
37         STAB *s;
38
39         for (hi = HdrInfo; hi->hi_field != NULL; hi++)
40         {
41                 s = stab(hi->hi_field, ST_HEADER, ST_ENTER);
42                 s->s_header.hi_flags = hi->hi_flags;
43                 s->s_header.hi_ruleset = NULL;
44         }
45 }
46 /*
47 **  CHOMPHEADER -- process and save a header line.
48 **
49 **      Called by collect, readcf, and readqf to deal with header lines.
50 **
51 **      Parameters:
52 **              line -- header as a text line.
53 **              pflag -- flags for chompheader() (from sendmail.h)
54 **              hdrp -- a pointer to the place to save the header.
55 **              e -- the envelope including this header.
56 **
57 **      Returns:
58 **              flags for this header.
59 **
60 **      Side Effects:
61 **              The header is saved on the header list.
62 **              Contents of 'line' are destroyed.
63 */
64
65 static struct hdrinfo   NormalHeader =  { NULL, 0, NULL };
66
67 unsigned long
68 chompheader(line, pflag, hdrp, e)
69         char *line;
70         int pflag;
71         HDR **hdrp;
72         register ENVELOPE *e;
73 {
74         unsigned char mid = '\0';
75         register char *p;
76         register HDR *h;
77         HDR **hp;
78         char *fname;
79         char *fvalue;
80         bool cond = false;
81         bool dropfrom;
82         bool headeronly;
83         STAB *s;
84         struct hdrinfo *hi;
85         bool nullheader = false;
86         BITMAP256 mopts;
87
88         if (tTd(31, 6))
89         {
90                 sm_dprintf("chompheader: ");
91                 xputs(sm_debug_file(), line);
92                 sm_dprintf("\n");
93         }
94
95         headeronly = hdrp != NULL;
96         if (!headeronly)
97                 hdrp = &e->e_header;
98
99         /* strip off options */
100         clrbitmap(mopts);
101         p = line;
102         if (!bitset(pflag, CHHDR_USER) && *p == '?')
103         {
104                 int c;
105                 register char *q;
106
107                 q = strchr(++p, '?');
108                 if (q == NULL)
109                         goto hse;
110
111                 *q = '\0';
112                 c = *p & 0377;
113
114                 /* possibly macro conditional */
115                 if (c == MACROEXPAND)
116                 {
117                         /* catch ?$? */
118                         if (*++p == '\0')
119                         {
120                                 *q = '?';
121                                 goto hse;
122                         }
123
124                         mid = (unsigned char) *p++;
125
126                         /* catch ?$abc? */
127                         if (*p != '\0')
128                         {
129                                 *q = '?';
130                                 goto hse;
131                         }
132                 }
133                 else if (*p == '$')
134                 {
135                         /* catch ?$? */
136                         if (*++p == '\0')
137                         {
138                                 *q = '?';
139                                 goto hse;
140                         }
141
142                         mid = (unsigned char) macid(p);
143                         if (bitset(0200, mid))
144                         {
145                                 p += strlen(macname(mid)) + 2;
146                                 SM_ASSERT(p <= q);
147                         }
148                         else
149                                 p++;
150
151                         /* catch ?$abc? */
152                         if (*p != '\0')
153                         {
154                                 *q = '?';
155                                 goto hse;
156                         }
157                 }
158                 else
159                 {
160                         while (*p != '\0')
161                         {
162                                 if (!isascii(*p))
163                                 {
164                                         *q = '?';
165                                         goto hse;
166                                 }
167
168                                 setbitn(bitidx(*p), mopts);
169                                 cond = true;
170                                 p++;
171                         }
172                 }
173                 p = q + 1;
174         }
175
176         /* find canonical name */
177         fname = p;
178         while (isascii(*p) && isgraph(*p) && *p != ':')
179                 p++;
180         fvalue = p;
181         while (isascii(*p) && isspace(*p))
182                 p++;
183         if (*p++ != ':' || fname == fvalue)
184         {
185 hse:
186                 syserr("553 5.3.0 header syntax error, line \"%s\"", line);
187                 return 0;
188         }
189         *fvalue = '\0';
190
191         /* strip field value on front */
192         if (*p == ' ')
193                 p++;
194         fvalue = p;
195
196         /* if the field is null, go ahead and use the default */
197         while (isascii(*p) && isspace(*p))
198                 p++;
199         if (*p == '\0')
200                 nullheader = true;
201
202         /* security scan: long field names are end-of-header */
203         if (strlen(fname) > 100)
204                 return H_EOH;
205
206         /* check to see if it represents a ruleset call */
207         if (bitset(pflag, CHHDR_DEF))
208         {
209                 char hbuf[50];
210
211                 (void) expand(fvalue, hbuf, sizeof hbuf, e);
212                 for (p = hbuf; isascii(*p) && isspace(*p); )
213                         p++;
214                 if ((*p++ & 0377) == CALLSUBR)
215                 {
216                         auto char *endp;
217                         bool strc;
218
219                         strc = *p == '+';       /* strip comments? */
220                         if (strc)
221                                 ++p;
222                         if (strtorwset(p, &endp, ST_ENTER) > 0)
223                         {
224                                 *endp = '\0';
225                                 s = stab(fname, ST_HEADER, ST_ENTER);
226                                 if (LogLevel > 9 &&
227                                     s->s_header.hi_ruleset != NULL)
228                                         sm_syslog(LOG_WARNING, NOQID,
229                                                   "Warning: redefined ruleset for header=%s, old=%s, new=%s",
230                                                   fname,
231                                                   s->s_header.hi_ruleset, p);
232                                 s->s_header.hi_ruleset = newstr(p);
233                                 if (!strc)
234                                         s->s_header.hi_flags |= H_STRIPCOMM;
235                         }
236                         return 0;
237                 }
238         }
239
240         /* see if it is a known type */
241         s = stab(fname, ST_HEADER, ST_FIND);
242         if (s != NULL)
243                 hi = &s->s_header;
244         else
245                 hi = &NormalHeader;
246
247         if (tTd(31, 9))
248         {
249                 if (s == NULL)
250                         sm_dprintf("no header flags match\n");
251                 else
252                         sm_dprintf("header match, flags=%lx, ruleset=%s\n",
253                                    hi->hi_flags,
254                                    hi->hi_ruleset == NULL ? "<NULL>"
255                                                           : hi->hi_ruleset);
256         }
257
258         /* see if this is a resent message */
259         if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
260             bitset(H_RESENT, hi->hi_flags))
261                 e->e_flags |= EF_RESENT;
262
263         /* if this is an Errors-To: header keep track of it now */
264         if (UseErrorsTo && !bitset(pflag, CHHDR_DEF) && !headeronly &&
265             bitset(H_ERRORSTO, hi->hi_flags))
266                 (void) sendtolist(fvalue, NULLADDR, &e->e_errorqueue, 0, e);
267
268         /* if this means "end of header" quit now */
269         if (!headeronly && bitset(H_EOH, hi->hi_flags))
270                 return hi->hi_flags;
271
272         /*
273         **  Horrible hack to work around problem with Lotus Notes SMTP
274         **  mail gateway, which generates From: headers with newlines in
275         **  them and the <address> on the second line.  Although this is
276         **  legal RFC 822, many MUAs don't handle this properly and thus
277         **  never find the actual address.
278         */
279
280         if (bitset(H_FROM, hi->hi_flags) && SingleLineFromHeader)
281         {
282                 while ((p = strchr(fvalue, '\n')) != NULL)
283                         *p = ' ';
284         }
285
286         /*
287         **  If there is a check ruleset, verify it against the header.
288         */
289
290         if (bitset(pflag, CHHDR_CHECK))
291         {
292                 int rscheckflags;
293                 char *rs;
294
295                 rscheckflags = RSF_COUNT;
296                 if (!bitset(hi->hi_flags, H_FROM|H_RCPT))
297                         rscheckflags |= RSF_UNSTRUCTURED;
298
299                 /* no ruleset? look for default */
300                 rs = hi->hi_ruleset;
301                 if (rs == NULL)
302                 {
303                         s = stab("*", ST_HEADER, ST_FIND);
304                         if (s != NULL)
305                         {
306                                 rs = (&s->s_header)->hi_ruleset;
307                                 if (bitset((&s->s_header)->hi_flags,
308                                            H_STRIPCOMM))
309                                         rscheckflags |= RSF_RMCOMM;
310                         }
311                 }
312                 else if (bitset(hi->hi_flags, H_STRIPCOMM))
313                         rscheckflags |= RSF_RMCOMM;
314                 if (rs != NULL)
315                 {
316                         int l, k;
317                         char qval[MAXNAME];
318
319                         l = 0;
320                         qval[l++] = '"';
321
322                         /* - 3 to avoid problems with " at the end */
323                         /* should be sizeof(qval), not MAXNAME */
324                         for (k = 0; fvalue[k] != '\0' && l < MAXNAME - 3; k++)
325                         {
326                                 switch (fvalue[k])
327                                 {
328                                   /* XXX other control chars? */
329                                   case '\011': /* ht */
330                                   case '\012': /* nl */
331                                   case '\013': /* vt */
332                                   case '\014': /* np */
333                                   case '\015': /* cr */
334                                         qval[l++] = ' ';
335                                         break;
336                                   case '"':
337                                         qval[l++] = '\\';
338                                         /* FALLTHROUGH */
339                                   default:
340                                         qval[l++] = fvalue[k];
341                                         break;
342                                 }
343                         }
344                         qval[l++] = '"';
345                         qval[l] = '\0';
346                         k += strlen(fvalue + k);
347                         if (k >= MAXNAME)
348                         {
349                                 if (LogLevel > 9)
350                                         sm_syslog(LOG_WARNING, e->e_id,
351                                                   "Warning: truncated header '%s' before check with '%s' len=%d max=%d",
352                                                   fname, rs, k, MAXNAME - 1);
353                         }
354                         macdefine(&e->e_macro, A_TEMP,
355                                 macid("{currHeader}"), qval);
356                         macdefine(&e->e_macro, A_TEMP,
357                                 macid("{hdr_name}"), fname);
358
359                         (void) sm_snprintf(qval, sizeof qval, "%d", k);
360                         macdefine(&e->e_macro, A_TEMP, macid("{hdrlen}"), qval);
361 #if _FFR_HDR_TYPE
362                         if (bitset(H_FROM, hi->hi_flags))
363                                 macdefine(&e->e_macro, A_PERM,
364                                         macid("{addr_type}"), "h s");
365                         else if (bitset(H_RCPT, hi->hi_flags))
366                                 macdefine(&e->e_macro, A_PERM,
367                                         macid("{addr_type}"), "h r");
368                         else
369 #endif /* _FFR_HDR_TYPE */
370                                 macdefine(&e->e_macro, A_PERM,
371                                         macid("{addr_type}"), "h");
372                         (void) rscheck(rs, fvalue, NULL, e, rscheckflags, 3,
373                                        NULL, e->e_id);
374                 }
375         }
376
377         /*
378         **  Drop explicit From: if same as what we would generate.
379         **  This is to make MH (which doesn't always give a full name)
380         **  insert the full name information in all circumstances.
381         */
382
383         dropfrom = false;
384         p = "resent-from";
385         if (!bitset(EF_RESENT, e->e_flags))
386                 p += 7;
387         if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
388             !bitset(EF_QUEUERUN, e->e_flags) && sm_strcasecmp(fname, p) == 0)
389         {
390                 if (tTd(31, 2))
391                 {
392                         sm_dprintf("comparing header from (%s) against default (%s or %s)\n",
393                                 fvalue, e->e_from.q_paddr, e->e_from.q_user);
394                 }
395                 if (e->e_from.q_paddr != NULL &&
396                     e->e_from.q_mailer != NULL &&
397                     bitnset(M_LOCALMAILER, e->e_from.q_mailer->m_flags) &&
398                     (strcmp(fvalue, e->e_from.q_paddr) == 0 ||
399                      strcmp(fvalue, e->e_from.q_user) == 0))
400                         dropfrom = true;
401         }
402
403         /* delete default value for this header */
404         for (hp = hdrp; (h = *hp) != NULL; hp = &h->h_link)
405         {
406                 if (sm_strcasecmp(fname, h->h_field) == 0 &&
407                     !bitset(H_USER, h->h_flags) &&
408                     !bitset(H_FORCE, h->h_flags))
409                 {
410                         if (nullheader)
411                         {
412                                 /* user-supplied value was null */
413                                 return 0;
414                         }
415                         if (dropfrom)
416                         {
417                                 /* make this look like the user entered it */
418                                 h->h_flags |= H_USER;
419                                 return hi->hi_flags;
420                         }
421                         h->h_value = NULL;
422                         if (!cond)
423                         {
424                                 /* copy conditions from default case */
425                                 memmove((char *) mopts, (char *) h->h_mflags,
426                                         sizeof mopts);
427                         }
428                         h->h_macro = mid;
429                 }
430         }
431
432         /* create a new node */
433         h = (HDR *) sm_rpool_malloc_x(e->e_rpool, sizeof *h);
434         h->h_field = sm_rpool_strdup_x(e->e_rpool, fname);
435         h->h_value = sm_rpool_strdup_x(e->e_rpool, fvalue);
436         h->h_link = NULL;
437         memmove((char *) h->h_mflags, (char *) mopts, sizeof mopts);
438         h->h_macro = mid;
439         *hp = h;
440         h->h_flags = hi->hi_flags;
441         if (bitset(pflag, CHHDR_USER) || bitset(pflag, CHHDR_QUEUE))
442                 h->h_flags |= H_USER;
443
444         /* strip EOH flag if parsing MIME headers */
445         if (headeronly)
446                 h->h_flags &= ~H_EOH;
447         if (bitset(pflag, CHHDR_DEF))
448                 h->h_flags |= H_DEFAULT;
449         if (cond || mid != '\0')
450                 h->h_flags |= H_CHECK;
451
452         /* hack to see if this is a new format message */
453         if (!bitset(pflag, CHHDR_DEF) && !headeronly &&
454             bitset(H_RCPT|H_FROM, h->h_flags) &&
455             (strchr(fvalue, ',') != NULL || strchr(fvalue, '(') != NULL ||
456              strchr(fvalue, '<') != NULL || strchr(fvalue, ';') != NULL))
457         {
458                 e->e_flags &= ~EF_OLDSTYLE;
459         }
460
461         return h->h_flags;
462 }
463 /*
464 **  ALLOCHEADER -- allocate a header entry
465 **
466 **      Parameters:
467 **              field -- the name of the header field.
468 **              value -- the value of the field.
469 **              flags -- flags to add to h_flags.
470 **              rp -- resource pool for allocations
471 **
472 **      Returns:
473 **              Pointer to a newly allocated and populated HDR.
474 */
475
476 static HDR *
477 allocheader(field, value, flags, rp)
478         char *field;
479         char *value;
480         int flags;
481         SM_RPOOL_T *rp;
482 {
483         HDR *h;
484         STAB *s;
485
486         /* find info struct */
487         s = stab(field, ST_HEADER, ST_FIND);
488
489         /* allocate space for new header */
490         h = (HDR *) sm_rpool_malloc_x(rp, sizeof *h);
491         h->h_field = field;
492         h->h_value = sm_rpool_strdup_x(rp, value);
493         h->h_flags = flags;
494         if (s != NULL)
495                 h->h_flags |= s->s_header.hi_flags;
496         clrbitmap(h->h_mflags);
497         h->h_macro = '\0';
498
499         return h;
500 }
501 /*
502 **  ADDHEADER -- add a header entry to the end of the queue.
503 **
504 **      This bypasses the special checking of chompheader.
505 **
506 **      Parameters:
507 **              field -- the name of the header field.
508 **              value -- the value of the field.
509 **              flags -- flags to add to h_flags.
510 **              e -- envelope.
511 **
512 **      Returns:
513 **              none.
514 **
515 **      Side Effects:
516 **              adds the field on the list of headers for this envelope.
517 */
518
519 void
520 addheader(field, value, flags, e)
521         char *field;
522         char *value;
523         int flags;
524         ENVELOPE *e;
525 {
526         register HDR *h;
527         HDR **hp;
528         HDR **hdrlist = &e->e_header;
529
530         /* find current place in list -- keep back pointer? */
531         for (hp = hdrlist; (h = *hp) != NULL; hp = &h->h_link)
532         {
533                 if (sm_strcasecmp(field, h->h_field) == 0)
534                         break;
535         }
536
537         /* allocate space for new header */
538         h = allocheader(field, value, flags, e->e_rpool);
539         h->h_link = *hp;
540         *hp = h;
541 }
542 /*
543 **  INSHEADER -- insert a header entry at the specified index
544 **
545 **      This bypasses the special checking of chompheader.
546 **
547 **      Parameters:
548 **              idx -- index into the header list at which to insert
549 **              field -- the name of the header field.
550 **              value -- the value of the field.
551 **              flags -- flags to add to h_flags.
552 **              e -- envelope.
553 **
554 **      Returns:
555 **              none.
556 **
557 **      Side Effects:
558 **              inserts the field on the list of headers for this envelope.
559 */
560
561 void
562 insheader(idx, field, value, flags, e)
563         int idx;
564         char *field;
565         char *value;
566         int flags;
567         ENVELOPE *e;
568 {
569         HDR *h, *srch, *last = NULL;
570
571         /* allocate space for new header */
572         h = allocheader(field, value, flags, e->e_rpool);
573
574         /* find insertion position */
575         for (srch = e->e_header; srch != NULL && idx > 0;
576              srch = srch->h_link, idx--)
577                 last = srch;
578
579         if (e->e_header == NULL)
580         {
581                 e->e_header = h;
582                 h->h_link = NULL;
583         }
584         else if (srch == NULL)
585         {
586                 SM_ASSERT(last != NULL);
587                 last->h_link = h;
588                 h->h_link = NULL;
589         }
590         else
591         {
592                 h->h_link = srch->h_link;
593                 srch->h_link = h;
594         }
595 }
596 /*
597 **  HVALUE -- return value of a header.
598 **
599 **      Only "real" fields (i.e., ones that have not been supplied
600 **      as a default) are used.
601 **
602 **      Parameters:
603 **              field -- the field name.
604 **              header -- the header list.
605 **
606 **      Returns:
607 **              pointer to the value part.
608 **              NULL if not found.
609 **
610 **      Side Effects:
611 **              none.
612 */
613
614 char *
615 hvalue(field, header)
616         char *field;
617         HDR *header;
618 {
619         register HDR *h;
620
621         for (h = header; h != NULL; h = h->h_link)
622         {
623                 if (!bitset(H_DEFAULT, h->h_flags) &&
624                     sm_strcasecmp(h->h_field, field) == 0)
625                         return h->h_value;
626         }
627         return NULL;
628 }
629 /*
630 **  ISHEADER -- predicate telling if argument is a header.
631 **
632 **      A line is a header if it has a single word followed by
633 **      optional white space followed by a colon.
634 **
635 **      Header fields beginning with two dashes, although technically
636 **      permitted by RFC822, are automatically rejected in order
637 **      to make MIME work out.  Without this we could have a technically
638 **      legal header such as ``--"foo:bar"'' that would also be a legal
639 **      MIME separator.
640 **
641 **      Parameters:
642 **              h -- string to check for possible headerness.
643 **
644 **      Returns:
645 **              true if h is a header.
646 **              false otherwise.
647 **
648 **      Side Effects:
649 **              none.
650 */
651
652 bool
653 isheader(h)
654         char *h;
655 {
656         register char *s = h;
657
658         if (s[0] == '-' && s[1] == '-')
659                 return false;
660
661         while (*s > ' ' && *s != ':' && *s != '\0')
662                 s++;
663
664         if (h == s)
665                 return false;
666
667         /* following technically violates RFC822 */
668         while (isascii(*s) && isspace(*s))
669                 s++;
670
671         return (*s == ':');
672 }
673 /*
674 **  EATHEADER -- run through the stored header and extract info.
675 **
676 **      Parameters:
677 **              e -- the envelope to process.
678 **              full -- if set, do full processing (e.g., compute
679 **                      message priority).  This should not be set
680 **                      when reading a queue file because some info
681 **                      needed to compute the priority is wrong.
682 **              log -- call logsender()?
683 **
684 **      Returns:
685 **              none.
686 **
687 **      Side Effects:
688 **              Sets a bunch of global variables from information
689 **                      in the collected header.
690 */
691
692 void
693 eatheader(e, full, log)
694         register ENVELOPE *e;
695         bool full;
696         bool log;
697 {
698         register HDR *h;
699         register char *p;
700         int hopcnt = 0;
701         char buf[MAXLINE];
702
703         /*
704         **  Set up macros for possible expansion in headers.
705         */
706
707         macdefine(&e->e_macro, A_PERM, 'f', e->e_sender);
708         macdefine(&e->e_macro, A_PERM, 'g', e->e_sender);
709         if (e->e_origrcpt != NULL && *e->e_origrcpt != '\0')
710                 macdefine(&e->e_macro, A_PERM, 'u', e->e_origrcpt);
711         else
712                 macdefine(&e->e_macro, A_PERM, 'u', NULL);
713
714         /* full name of from person */
715         p = hvalue("full-name", e->e_header);
716         if (p != NULL)
717         {
718                 if (!rfc822_string(p))
719                 {
720                         /*
721                         **  Quote a full name with special characters
722                         **  as a comment so crackaddr() doesn't destroy
723                         **  the name portion of the address.
724                         */
725
726                         p = addquotes(p, e->e_rpool);
727                 }
728                 macdefine(&e->e_macro, A_PERM, 'x', p);
729         }
730
731         if (tTd(32, 1))
732                 sm_dprintf("----- collected header -----\n");
733         e->e_msgid = NULL;
734         for (h = e->e_header; h != NULL; h = h->h_link)
735         {
736                 if (tTd(32, 1))
737                         sm_dprintf("%s: ", h->h_field);
738                 if (h->h_value == NULL)
739                 {
740                         if (tTd(32, 1))
741                                 sm_dprintf("<NULL>\n");
742                         continue;
743                 }
744
745                 /* do early binding */
746                 if (bitset(H_DEFAULT, h->h_flags) &&
747                     !bitset(H_BINDLATE, h->h_flags))
748                 {
749                         if (tTd(32, 1))
750                         {
751                                 sm_dprintf("(");
752                                 xputs(sm_debug_file(), h->h_value);
753                                 sm_dprintf(") ");
754                         }
755                         expand(h->h_value, buf, sizeof buf, e);
756                         if (buf[0] != '\0')
757                         {
758                                 if (bitset(H_FROM, h->h_flags))
759                                         expand(crackaddr(buf, e),
760                                                buf, sizeof buf, e);
761                                 h->h_value = sm_rpool_strdup_x(e->e_rpool, buf);
762                                 h->h_flags &= ~H_DEFAULT;
763                         }
764                 }
765                 if (tTd(32, 1))
766                 {
767                         xputs(sm_debug_file(), h->h_value);
768                         sm_dprintf("\n");
769                 }
770
771                 /* count the number of times it has been processed */
772                 if (bitset(H_TRACE, h->h_flags))
773                         hopcnt++;
774
775                 /* send to this person if we so desire */
776                 if (GrabTo && bitset(H_RCPT, h->h_flags) &&
777                     !bitset(H_DEFAULT, h->h_flags) &&
778                     (!bitset(EF_RESENT, e->e_flags) ||
779                      bitset(H_RESENT, h->h_flags)))
780                 {
781 #if 0
782                         int saveflags = e->e_flags;
783 #endif /* 0 */
784
785                         (void) sendtolist(denlstring(h->h_value, true, false),
786                                           NULLADDR, &e->e_sendqueue, 0, e);
787
788 #if 0
789                         /*
790                         **  Change functionality so a fatal error on an
791                         **  address doesn't affect the entire envelope.
792                         */
793
794                         /* delete fatal errors generated by this address */
795                         if (!bitset(EF_FATALERRS, saveflags))
796                                 e->e_flags &= ~EF_FATALERRS;
797 #endif /* 0 */
798                 }
799
800                 /* save the message-id for logging */
801                 p = "resent-message-id";
802                 if (!bitset(EF_RESENT, e->e_flags))
803                         p += 7;
804                 if (sm_strcasecmp(h->h_field, p) == 0)
805                 {
806                         e->e_msgid = h->h_value;
807                         while (isascii(*e->e_msgid) && isspace(*e->e_msgid))
808                                 e->e_msgid++;
809                         macdefine(&e->e_macro, A_PERM, macid("{msg_id}"),
810                                   e->e_msgid);
811                 }
812         }
813         if (tTd(32, 1))
814                 sm_dprintf("----------------------------\n");
815
816         /* if we are just verifying (that is, sendmail -t -bv), drop out now */
817         if (OpMode == MD_VERIFY)
818                 return;
819
820         /* store hop count */
821         if (hopcnt > e->e_hopcount)
822         {
823                 e->e_hopcount = hopcnt;
824                 (void) sm_snprintf(buf, sizeof buf, "%d", e->e_hopcount);
825                 macdefine(&e->e_macro, A_TEMP, 'c', buf);
826         }
827
828         /* message priority */
829         p = hvalue("precedence", e->e_header);
830         if (p != NULL)
831                 e->e_class = priencode(p);
832         if (e->e_class < 0)
833                 e->e_timeoutclass = TOC_NONURGENT;
834         else if (e->e_class > 0)
835                 e->e_timeoutclass = TOC_URGENT;
836         if (full)
837         {
838                 e->e_msgpriority = e->e_msgsize
839                                  - e->e_class * WkClassFact
840                                  + e->e_nrcpts * WkRecipFact;
841         }
842
843         /* check for DSN to properly set e_timeoutclass */
844         p = hvalue("content-type", e->e_header);
845         if (p != NULL)
846         {
847                 bool oldsupr;
848                 char **pvp;
849                 char pvpbuf[MAXLINE];
850                 extern unsigned char MimeTokenTab[256];
851
852                 /* tokenize header */
853                 oldsupr = SuprErrs;
854                 SuprErrs = true;
855                 pvp = prescan(p, '\0', pvpbuf, sizeof pvpbuf, NULL,
856                               MimeTokenTab, false);
857                 SuprErrs = oldsupr;
858
859                 /* Check if multipart/report */
860                 if (pvp != NULL && pvp[0] != NULL &&
861                     pvp[1] != NULL && pvp[2] != NULL &&
862                     sm_strcasecmp(*pvp++, "multipart") == 0 &&
863                     strcmp(*pvp++, "/") == 0 &&
864                     sm_strcasecmp(*pvp++, "report") == 0)
865                 {
866                         /* Look for report-type=delivery-status */
867                         while (*pvp != NULL)
868                         {
869                                 /* skip to semicolon separator */
870                                 while (*pvp != NULL && strcmp(*pvp, ";") != 0)
871                                         pvp++;
872
873                                 /* skip semicolon */
874                                 if (*pvp++ == NULL || *pvp == NULL)
875                                         break;
876
877                                 /* look for report-type */
878                                 if (sm_strcasecmp(*pvp++, "report-type") != 0)
879                                         continue;
880
881                                 /* skip equal */
882                                 if (*pvp == NULL || strcmp(*pvp, "=") != 0)
883                                         continue;
884
885                                 /* check value */
886                                 if (*++pvp != NULL &&
887                                     sm_strcasecmp(*pvp,
888                                                   "delivery-status") == 0)
889                                         e->e_timeoutclass = TOC_DSN;
890
891                                 /* found report-type, no need to continue */
892                                 break;
893                         }
894                 }
895         }
896
897         /* message timeout priority */
898         p = hvalue("priority", e->e_header);
899         if (p != NULL)
900         {
901                 /* (this should be in the configuration file) */
902                 if (sm_strcasecmp(p, "urgent") == 0)
903                         e->e_timeoutclass = TOC_URGENT;
904                 else if (sm_strcasecmp(p, "normal") == 0)
905                         e->e_timeoutclass = TOC_NORMAL;
906                 else if (sm_strcasecmp(p, "non-urgent") == 0)
907                         e->e_timeoutclass = TOC_NONURGENT;
908                 else if (bitset(EF_RESPONSE, e->e_flags))
909                         e->e_timeoutclass = TOC_DSN;
910         }
911         else if (bitset(EF_RESPONSE, e->e_flags))
912                 e->e_timeoutclass = TOC_DSN;
913
914         /* date message originated */
915         p = hvalue("posted-date", e->e_header);
916         if (p == NULL)
917                 p = hvalue("date", e->e_header);
918         if (p != NULL)
919                 macdefine(&e->e_macro, A_PERM, 'a', p);
920
921         /* check to see if this is a MIME message */
922         if ((e->e_bodytype != NULL &&
923              sm_strcasecmp(e->e_bodytype, "8BITMIME") == 0) ||
924             hvalue("MIME-Version", e->e_header) != NULL)
925         {
926                 e->e_flags |= EF_IS_MIME;
927                 if (HasEightBits)
928                         e->e_bodytype = "8BITMIME";
929         }
930         else if ((p = hvalue("Content-Type", e->e_header)) != NULL)
931         {
932                 /* this may be an RFC 1049 message */
933                 p = strpbrk(p, ";/");
934                 if (p == NULL || *p == ';')
935                 {
936                         /* yep, it is */
937                         e->e_flags |= EF_DONT_MIME;
938                 }
939         }
940
941         /*
942         **  From person in antiquated ARPANET mode
943         **      required by UK Grey Book e-mail gateways (sigh)
944         */
945
946         if (OpMode == MD_ARPAFTP)
947         {
948                 register struct hdrinfo *hi;
949
950                 for (hi = HdrInfo; hi->hi_field != NULL; hi++)
951                 {
952                         if (bitset(H_FROM, hi->hi_flags) &&
953                             (!bitset(H_RESENT, hi->hi_flags) ||
954                              bitset(EF_RESENT, e->e_flags)) &&
955                             (p = hvalue(hi->hi_field, e->e_header)) != NULL)
956                                 break;
957                 }
958                 if (hi->hi_field != NULL)
959                 {
960                         if (tTd(32, 2))
961                                 sm_dprintf("eatheader: setsender(*%s == %s)\n",
962                                         hi->hi_field, p);
963                         setsender(p, e, NULL, '\0', true);
964                 }
965         }
966
967         /*
968         **  Log collection information.
969         */
970
971         if (log && bitset(EF_LOGSENDER, e->e_flags) && LogLevel > 4)
972         {
973                 logsender(e, e->e_msgid);
974                 e->e_flags &= ~EF_LOGSENDER;
975         }
976 }
977 /*
978 **  LOGSENDER -- log sender information
979 **
980 **      Parameters:
981 **              e -- the envelope to log
982 **              msgid -- the message id
983 **
984 **      Returns:
985 **              none
986 */
987
988 void
989 logsender(e, msgid)
990         register ENVELOPE *e;
991         char *msgid;
992 {
993         char *name;
994         register char *sbp;
995         register char *p;
996         char hbuf[MAXNAME + 1];
997         char sbuf[MAXLINE + 1];
998         char mbuf[MAXNAME + 1];
999
1000         /* don't allow newlines in the message-id */
1001         /* XXX do we still need this? sm_syslog() replaces control chars */
1002         if (msgid != NULL)
1003         {
1004                 size_t l;
1005
1006                 l = strlen(msgid);
1007                 if (l > sizeof mbuf - 1)
1008                         l = sizeof mbuf - 1;
1009                 memmove(mbuf, msgid, l);
1010                 mbuf[l] = '\0';
1011                 p = mbuf;
1012                 while ((p = strchr(p, '\n')) != NULL)
1013                         *p++ = ' ';
1014         }
1015
1016         if (bitset(EF_RESPONSE, e->e_flags))
1017                 name = "[RESPONSE]";
1018         else if ((name = macvalue('_', e)) != NULL)
1019                 /* EMPTY */
1020                 ;
1021         else if (RealHostName == NULL)
1022                 name = "localhost";
1023         else if (RealHostName[0] == '[')
1024                 name = RealHostName;
1025         else
1026         {
1027                 name = hbuf;
1028                 (void) sm_snprintf(hbuf, sizeof hbuf, "%.80s", RealHostName);
1029                 if (RealHostAddr.sa.sa_family != 0)
1030                 {
1031                         p = &hbuf[strlen(hbuf)];
1032                         (void) sm_snprintf(p, SPACELEFT(hbuf, p),
1033                                            " (%.100s)",
1034                                            anynet_ntoa(&RealHostAddr));
1035                 }
1036         }
1037
1038         /* some versions of syslog only take 5 printf args */
1039 #if (SYSLOG_BUFSIZE) >= 256
1040         sbp = sbuf;
1041         (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1042                 "from=%.200s, size=%ld, class=%d, nrcpts=%d",
1043                 e->e_from.q_paddr == NULL ? "<NONE>" : e->e_from.q_paddr,
1044                 e->e_msgsize, e->e_class, e->e_nrcpts);
1045         sbp += strlen(sbp);
1046         if (msgid != NULL)
1047         {
1048                 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1049                                 ", msgid=%.100s", mbuf);
1050                 sbp += strlen(sbp);
1051         }
1052         if (e->e_bodytype != NULL)
1053         {
1054                 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1055                                 ", bodytype=%.20s", e->e_bodytype);
1056                 sbp += strlen(sbp);
1057         }
1058         p = macvalue('r', e);
1059         if (p != NULL)
1060         {
1061                 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1062                                 ", proto=%.20s", p);
1063                 sbp += strlen(sbp);
1064         }
1065         p = macvalue(macid("{daemon_name}"), e);
1066         if (p != NULL)
1067         {
1068                 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1069                                 ", daemon=%.20s", p);
1070                 sbp += strlen(sbp);
1071         }
1072         sm_syslog(LOG_INFO, e->e_id, "%.850s, relay=%s", sbuf, name);
1073
1074 #else /* (SYSLOG_BUFSIZE) >= 256 */
1075
1076         sm_syslog(LOG_INFO, e->e_id,
1077                   "from=%s",
1078                   e->e_from.q_paddr == NULL ? "<NONE>"
1079                                             : shortenstring(e->e_from.q_paddr,
1080                                                             83));
1081         sm_syslog(LOG_INFO, e->e_id,
1082                   "size=%ld, class=%ld, nrcpts=%d",
1083                   e->e_msgsize, e->e_class, e->e_nrcpts);
1084         if (msgid != NULL)
1085                 sm_syslog(LOG_INFO, e->e_id,
1086                           "msgid=%s",
1087                           shortenstring(mbuf, 83));
1088         sbp = sbuf;
1089         *sbp = '\0';
1090         if (e->e_bodytype != NULL)
1091         {
1092                 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1093                                 "bodytype=%.20s, ", e->e_bodytype);
1094                 sbp += strlen(sbp);
1095         }
1096         p = macvalue('r', e);
1097         if (p != NULL)
1098         {
1099                 (void) sm_snprintf(sbp, SPACELEFT(sbuf, sbp),
1100                                 "proto=%.20s, ", p);
1101                 sbp += strlen(sbp);
1102         }
1103         sm_syslog(LOG_INFO, e->e_id,
1104                   "%.400srelay=%s", sbuf, name);
1105 #endif /* (SYSLOG_BUFSIZE) >= 256 */
1106 }
1107 /*
1108 **  PRIENCODE -- encode external priority names into internal values.
1109 **
1110 **      Parameters:
1111 **              p -- priority in ascii.
1112 **
1113 **      Returns:
1114 **              priority as a numeric level.
1115 **
1116 **      Side Effects:
1117 **              none.
1118 */
1119
1120 static int
1121 priencode(p)
1122         char *p;
1123 {
1124         register int i;
1125
1126         for (i = 0; i < NumPriorities; i++)
1127         {
1128                 if (sm_strcasecmp(p, Priorities[i].pri_name) == 0)
1129                         return Priorities[i].pri_val;
1130         }
1131
1132         /* unknown priority */
1133         return 0;
1134 }
1135 /*
1136 **  CRACKADDR -- parse an address and turn it into a macro
1137 **
1138 **      This doesn't actually parse the address -- it just extracts
1139 **      it and replaces it with "$g".  The parse is totally ad hoc
1140 **      and isn't even guaranteed to leave something syntactically
1141 **      identical to what it started with.  However, it does leave
1142 **      something semantically identical if possible, else at least
1143 **      syntactically correct.
1144 **
1145 **      For example, it changes "Real Name <real@example.com> (Comment)"
1146 **      to "Real Name <$g> (Comment)".
1147 **
1148 **      This algorithm has been cleaned up to handle a wider range
1149 **      of cases -- notably quoted and backslash escaped strings.
1150 **      This modification makes it substantially better at preserving
1151 **      the original syntax.
1152 **
1153 **      Parameters:
1154 **              addr -- the address to be cracked.
1155 **              e -- the current envelope.
1156 **
1157 **      Returns:
1158 **              a pointer to the new version.
1159 **
1160 **      Side Effects:
1161 **              none.
1162 **
1163 **      Warning:
1164 **              The return value is saved in local storage and should
1165 **              be copied if it is to be reused.
1166 */
1167
1168 #define SM_HAVE_ROOM            ((bp < buflim) && (buflim <= bufend))
1169
1170 /*
1171 **  Append a character to bp if we have room.
1172 **  If not, punt and return $g.
1173 */
1174
1175 #define SM_APPEND_CHAR(c)                                       \
1176         do                                                      \
1177         {                                                       \
1178                 if (SM_HAVE_ROOM)                               \
1179                         *bp++ = (c);                            \
1180                 else                                            \
1181                         goto returng;                           \
1182         } while (0)
1183
1184 #if MAXNAME < 10
1185 ERROR MAXNAME must be at least 10
1186 #endif /* MAXNAME < 10 */
1187
1188 char *
1189 crackaddr(addr, e)
1190         register char *addr;
1191         ENVELOPE *e;
1192 {
1193         register char *p;
1194         register char c;
1195         int cmtlev;                     /* comment level in input string */
1196         int realcmtlev;                 /* comment level in output string */
1197         int anglelev;                   /* angle level in input string */
1198         int copylev;                    /* 0 == in address, >0 copying */
1199         int bracklev;                   /* bracket level for IPv6 addr check */
1200         bool addangle;                  /* put closing angle in output */
1201         bool qmode;                     /* quoting in original string? */
1202         bool realqmode;                 /* quoting in output string? */
1203         bool putgmac = false;           /* already wrote $g */
1204         bool quoteit = false;           /* need to quote next character */
1205         bool gotangle = false;          /* found first '<' */
1206         bool gotcolon = false;          /* found a ':' */
1207         register char *bp;
1208         char *buflim;
1209         char *bufhead;
1210         char *addrhead;
1211         char *bufend;
1212         static char buf[MAXNAME + 1];
1213
1214         if (tTd(33, 1))
1215                 sm_dprintf("crackaddr(%s)\n", addr);
1216
1217         /* strip leading spaces */
1218         while (*addr != '\0' && isascii(*addr) && isspace(*addr))
1219                 addr++;
1220
1221         /*
1222         **  Start by assuming we have no angle brackets.  This will be
1223         **  adjusted later if we find them.
1224         */
1225
1226         buflim = bufend = &buf[sizeof(buf) - 1];
1227         bp = bufhead = buf;
1228         p = addrhead = addr;
1229         copylev = anglelev = cmtlev = realcmtlev = 0;
1230         bracklev = 0;
1231         qmode = realqmode = addangle = false;
1232
1233         while ((c = *p++) != '\0')
1234         {
1235                 /*
1236                 **  Try to keep legal syntax using spare buffer space
1237                 **  (maintained by buflim).
1238                 */
1239
1240                 if (copylev > 0)
1241                         SM_APPEND_CHAR(c);
1242
1243                 /* check for backslash escapes */
1244                 if (c == '\\')
1245                 {
1246                         /* arrange to quote the address */
1247                         if (cmtlev <= 0 && !qmode)
1248                                 quoteit = true;
1249
1250                         if ((c = *p++) == '\0')
1251                         {
1252                                 /* too far */
1253                                 p--;
1254                                 goto putg;
1255                         }
1256                         if (copylev > 0)
1257                                 SM_APPEND_CHAR(c);
1258                         goto putg;
1259                 }
1260
1261                 /* check for quoted strings */
1262                 if (c == '"' && cmtlev <= 0)
1263                 {
1264                         qmode = !qmode;
1265                         if (copylev > 0 && SM_HAVE_ROOM)
1266                         {
1267                                 if (realqmode)
1268                                         buflim--;
1269                                 else
1270                                         buflim++;
1271                                 realqmode = !realqmode;
1272                         }
1273                         continue;
1274                 }
1275                 if (qmode)
1276                         goto putg;
1277
1278                 /* check for comments */
1279                 if (c == '(')
1280                 {
1281                         cmtlev++;
1282
1283                         /* allow space for closing paren */
1284                         if (SM_HAVE_ROOM)
1285                         {
1286                                 buflim--;
1287                                 realcmtlev++;
1288                                 if (copylev++ <= 0)
1289                                 {
1290                                         if (bp != bufhead)
1291                                                 SM_APPEND_CHAR(' ');
1292                                         SM_APPEND_CHAR(c);
1293                                 }
1294                         }
1295                 }
1296                 if (cmtlev > 0)
1297                 {
1298                         if (c == ')')
1299                         {
1300                                 cmtlev--;
1301                                 copylev--;
1302                                 if (SM_HAVE_ROOM)
1303                                 {
1304                                         realcmtlev--;
1305                                         buflim++;
1306                                 }
1307                         }
1308                         continue;
1309                 }
1310                 else if (c == ')')
1311                 {
1312                         /* syntax error: unmatched ) */
1313                         if (copylev > 0 && SM_HAVE_ROOM && bp > bufhead)
1314                                 bp--;
1315                 }
1316
1317                 /* count nesting on [ ... ] (for IPv6 domain literals) */
1318                 if (c == '[')
1319                         bracklev++;
1320                 else if (c == ']')
1321                         bracklev--;
1322
1323                 /* check for group: list; syntax */
1324                 if (c == ':' && anglelev <= 0 && bracklev <= 0 &&
1325                     !gotcolon && !ColonOkInAddr)
1326                 {
1327                         register char *q;
1328
1329                         /*
1330                         **  Check for DECnet phase IV ``::'' (host::user)
1331                         **  or DECnet phase V ``:.'' syntaxes.  The latter
1332                         **  covers ``user@DEC:.tay.myhost'' and
1333                         **  ``DEC:.tay.myhost::user'' syntaxes (bletch).
1334                         */
1335
1336                         if (*p == ':' || *p == '.')
1337                         {
1338                                 if (cmtlev <= 0 && !qmode)
1339                                         quoteit = true;
1340                                 if (copylev > 0)
1341                                 {
1342                                         SM_APPEND_CHAR(c);
1343                                         SM_APPEND_CHAR(*p);
1344                                 }
1345                                 p++;
1346                                 goto putg;
1347                         }
1348
1349                         gotcolon = true;
1350
1351                         bp = bufhead;
1352                         if (quoteit)
1353                         {
1354                                 SM_APPEND_CHAR('"');
1355
1356                                 /* back up over the ':' and any spaces */
1357                                 --p;
1358                                 while (p > addr &&
1359                                        isascii(*--p) && isspace(*p))
1360                                         continue;
1361                                 p++;
1362                         }
1363                         for (q = addrhead; q < p; )
1364                         {
1365                                 c = *q++;
1366                                 if (quoteit && c == '"')
1367                                         SM_APPEND_CHAR('\\');
1368                                 SM_APPEND_CHAR(c);
1369                         }
1370                         if (quoteit)
1371                         {
1372                                 if (bp == &bufhead[1])
1373                                         bp--;
1374                                 else
1375                                         SM_APPEND_CHAR('"');
1376                                 while ((c = *p++) != ':')
1377                                         SM_APPEND_CHAR(c);
1378                                 SM_APPEND_CHAR(c);
1379                         }
1380
1381                         /* any trailing white space is part of group: */
1382                         while (isascii(*p) && isspace(*p))
1383                         {
1384                                 SM_APPEND_CHAR(*p);
1385                                 p++;
1386                         }
1387                         copylev = 0;
1388                         putgmac = quoteit = false;
1389                         bufhead = bp;
1390                         addrhead = p;
1391                         continue;
1392                 }
1393
1394                 if (c == ';' && copylev <= 0 && !ColonOkInAddr)
1395                         SM_APPEND_CHAR(c);
1396
1397                 /* check for characters that may have to be quoted */
1398                 if (strchr(MustQuoteChars, c) != NULL)
1399                 {
1400                         /*
1401                         **  If these occur as the phrase part of a <>
1402                         **  construct, but are not inside of () or already
1403                         **  quoted, they will have to be quoted.  Note that
1404                         **  now (but don't actually do the quoting).
1405                         */
1406
1407                         if (cmtlev <= 0 && !qmode)
1408                                 quoteit = true;
1409                 }
1410
1411                 /* check for angle brackets */
1412                 if (c == '<')
1413                 {
1414                         register char *q;
1415
1416                         /* assume first of two angles is bogus */
1417                         if (gotangle)
1418                                 quoteit = true;
1419                         gotangle = true;
1420
1421                         /* oops -- have to change our mind */
1422                         anglelev = 1;
1423                         if (SM_HAVE_ROOM)
1424                         {
1425                                 if (!addangle)
1426                                         buflim--;
1427                                 addangle = true;
1428                         }
1429
1430                         bp = bufhead;
1431                         if (quoteit)
1432                         {
1433                                 SM_APPEND_CHAR('"');
1434
1435                                 /* back up over the '<' and any spaces */
1436                                 --p;
1437                                 while (p > addr &&
1438                                        isascii(*--p) && isspace(*p))
1439                                         continue;
1440                                 p++;
1441                         }
1442                         for (q = addrhead; q < p; )
1443                         {
1444                                 c = *q++;
1445                                 if (quoteit && c == '"')
1446                                 {
1447                                         SM_APPEND_CHAR('\\');
1448                                         SM_APPEND_CHAR(c);
1449                                 }
1450                                 else
1451                                         SM_APPEND_CHAR(c);
1452                         }
1453                         if (quoteit)
1454                         {
1455                                 if (bp == &buf[1])
1456                                         bp--;
1457                                 else
1458                                         SM_APPEND_CHAR('"');
1459                                 while ((c = *p++) != '<')
1460                                         SM_APPEND_CHAR(c);
1461                                 SM_APPEND_CHAR(c);
1462                         }
1463                         copylev = 0;
1464                         putgmac = quoteit = false;
1465                         continue;
1466                 }
1467
1468                 if (c == '>')
1469                 {
1470                         if (anglelev > 0)
1471                         {
1472                                 anglelev--;
1473                                 if (SM_HAVE_ROOM)
1474                                 {
1475                                         if (addangle)
1476                                                 buflim++;
1477                                         addangle = false;
1478                                 }
1479                         }
1480                         else if (SM_HAVE_ROOM)
1481                         {
1482                                 /* syntax error: unmatched > */
1483                                 if (copylev > 0 && bp > bufhead)
1484                                         bp--;
1485                                 quoteit = true;
1486                                 continue;
1487                         }
1488                         if (copylev++ <= 0)
1489                                 SM_APPEND_CHAR(c);
1490                         continue;
1491                 }
1492
1493                 /* must be a real address character */
1494         putg:
1495                 if (copylev <= 0 && !putgmac)
1496                 {
1497                         if (bp > buf && bp[-1] == ')')
1498                                 SM_APPEND_CHAR(' ');
1499                         SM_APPEND_CHAR(MACROEXPAND);
1500                         SM_APPEND_CHAR('g');
1501                         putgmac = true;
1502                 }
1503         }
1504
1505         /* repair any syntactic damage */
1506         if (realqmode && bp < bufend)
1507                 *bp++ = '"';
1508         while (realcmtlev-- > 0 && bp < bufend)
1509                 *bp++ = ')';
1510         if (addangle && bp < bufend)
1511                 *bp++ = '>';
1512         *bp = '\0';
1513         if (bp < bufend)
1514                 goto success;
1515
1516  returng:
1517         /* String too long, punt */
1518         buf[0] = '<';
1519         buf[1] = MACROEXPAND;
1520         buf[2]= 'g';
1521         buf[3] = '>';
1522         buf[4]= '\0';
1523         sm_syslog(LOG_ALERT, e->e_id,
1524                   "Dropped invalid comments from header address");
1525
1526  success:
1527         if (tTd(33, 1))
1528         {
1529                 sm_dprintf("crackaddr=>`");
1530                 xputs(sm_debug_file(), buf);
1531                 sm_dprintf("'\n");
1532         }
1533         return buf;
1534 }
1535 /*
1536 **  PUTHEADER -- put the header part of a message from the in-core copy
1537 **
1538 **      Parameters:
1539 **              mci -- the connection information.
1540 **              hdr -- the header to put.
1541 **              e -- envelope to use.
1542 **              flags -- MIME conversion flags.
1543 **
1544 **      Returns:
1545 **              true iff header part was written successfully
1546 **
1547 **      Side Effects:
1548 **              none.
1549 */
1550
1551 bool
1552 putheader(mci, hdr, e, flags)
1553         register MCI *mci;
1554         HDR *hdr;
1555         register ENVELOPE *e;
1556         int flags;
1557 {
1558         register HDR *h;
1559         char buf[SM_MAX(MAXLINE,BUFSIZ)];
1560         char obuf[MAXLINE];
1561
1562         if (tTd(34, 1))
1563                 sm_dprintf("--- putheader, mailer = %s ---\n",
1564                         mci->mci_mailer->m_name);
1565
1566         /*
1567         **  If we're in MIME mode, we're not really in the header of the
1568         **  message, just the header of one of the parts of the body of
1569         **  the message.  Therefore MCIF_INHEADER should not be turned on.
1570         */
1571
1572         if (!bitset(MCIF_INMIME, mci->mci_flags))
1573                 mci->mci_flags |= MCIF_INHEADER;
1574
1575         for (h = hdr; h != NULL; h = h->h_link)
1576         {
1577                 register char *p = h->h_value;
1578                 char *q;
1579
1580                 if (tTd(34, 11))
1581                 {
1582                         sm_dprintf("  %s: ", h->h_field);
1583                         xputs(sm_debug_file(), p);
1584                 }
1585
1586                 /* Skip empty headers */
1587                 if (h->h_value == NULL)
1588                         continue;
1589
1590                 /* heuristic shortening of MIME fields to avoid MUA overflows */
1591                 if (MaxMimeFieldLength > 0 &&
1592                     wordinclass(h->h_field,
1593                                 macid("{checkMIMEFieldHeaders}")))
1594                 {
1595                         size_t len;
1596
1597                         len = fix_mime_header(h, e);
1598                         if (len > 0)
1599                         {
1600                                 sm_syslog(LOG_ALERT, e->e_id,
1601                                           "Truncated MIME %s header due to field size (length = %ld) (possible attack)",
1602                                           h->h_field, (unsigned long) len);
1603                                 if (tTd(34, 11))
1604                                         sm_dprintf("  truncated MIME %s header due to field size  (length = %ld) (possible attack)\n",
1605                                                    h->h_field,
1606                                                    (unsigned long) len);
1607                         }
1608                 }
1609
1610                 if (MaxMimeHeaderLength > 0 &&
1611                     wordinclass(h->h_field,
1612                                 macid("{checkMIMETextHeaders}")))
1613                 {
1614                         size_t len;
1615
1616                         len = strlen(h->h_value);
1617                         if (len > (size_t) MaxMimeHeaderLength)
1618                         {
1619                                 h->h_value[MaxMimeHeaderLength - 1] = '\0';
1620                                 sm_syslog(LOG_ALERT, e->e_id,
1621                                           "Truncated long MIME %s header (length = %ld) (possible attack)",
1622                                           h->h_field, (unsigned long) len);
1623                                 if (tTd(34, 11))
1624                                         sm_dprintf("  truncated long MIME %s header (length = %ld) (possible attack)\n",
1625                                                    h->h_field,
1626                                                    (unsigned long) len);
1627                         }
1628                 }
1629
1630                 if (MaxMimeHeaderLength > 0 &&
1631                     wordinclass(h->h_field,
1632                                 macid("{checkMIMEHeaders}")))
1633                 {
1634                         size_t len;
1635
1636                         len = strlen(h->h_value);
1637                         if (shorten_rfc822_string(h->h_value,
1638                                                   MaxMimeHeaderLength))
1639                         {
1640                                 if (len < MaxMimeHeaderLength)
1641                                 {
1642                                         /* we only rebalanced a bogus header */
1643                                         sm_syslog(LOG_ALERT, e->e_id,
1644                                                   "Fixed MIME %s header (possible attack)",
1645                                                   h->h_field);
1646                                         if (tTd(34, 11))
1647                                                 sm_dprintf("  fixed MIME %s header (possible attack)\n",
1648                                                            h->h_field);
1649                                 }
1650                                 else
1651                                 {
1652                                         /* we actually shortened header */
1653                                         sm_syslog(LOG_ALERT, e->e_id,
1654                                                   "Truncated long MIME %s header (length = %ld) (possible attack)",
1655                                                   h->h_field,
1656                                                   (unsigned long) len);
1657                                         if (tTd(34, 11))
1658                                                 sm_dprintf("  truncated long MIME %s header (length = %ld) (possible attack)\n",
1659                                                            h->h_field,
1660                                                            (unsigned long) len);
1661                                 }
1662                         }
1663                 }
1664
1665                 /*
1666                 **  Suppress Content-Transfer-Encoding: if we are MIMEing
1667                 **  and we are potentially converting from 8 bit to 7 bit
1668                 **  MIME.  If converting, add a new CTE header in
1669                 **  mime8to7().
1670                 */
1671
1672                 if (bitset(H_CTE, h->h_flags) &&
1673                     bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME,
1674                            mci->mci_flags) &&
1675                     !bitset(M87F_NO8TO7, flags))
1676                 {
1677                         if (tTd(34, 11))
1678                                 sm_dprintf(" (skipped (content-transfer-encoding))\n");
1679                         continue;
1680                 }
1681
1682                 if (bitset(MCIF_INMIME, mci->mci_flags))
1683                 {
1684                         if (tTd(34, 11))
1685                                 sm_dprintf("\n");
1686                         if (!put_vanilla_header(h, p, mci))
1687                                 goto writeerr;
1688                         continue;
1689                 }
1690
1691                 if (bitset(H_CHECK|H_ACHECK, h->h_flags) &&
1692                     !bitintersect(h->h_mflags, mci->mci_mailer->m_flags) &&
1693                     (h->h_macro == '\0' ||
1694                      (q = macvalue(bitidx(h->h_macro), e)) == NULL ||
1695                      *q == '\0'))
1696                 {
1697                         if (tTd(34, 11))
1698                                 sm_dprintf(" (skipped)\n");
1699                         continue;
1700                 }
1701
1702                 /* handle Resent-... headers specially */
1703                 if (bitset(H_RESENT, h->h_flags) && !bitset(EF_RESENT, e->e_flags))
1704                 {
1705                         if (tTd(34, 11))
1706                                 sm_dprintf(" (skipped (resent))\n");
1707                         continue;
1708                 }
1709
1710                 /* suppress return receipts if requested */
1711                 if (bitset(H_RECEIPTTO, h->h_flags) &&
1712                     (RrtImpliesDsn || bitset(EF_NORECEIPT, e->e_flags)))
1713                 {
1714                         if (tTd(34, 11))
1715                                 sm_dprintf(" (skipped (receipt))\n");
1716                         continue;
1717                 }
1718
1719                 /* macro expand value if generated internally */
1720                 if (bitset(H_DEFAULT, h->h_flags) ||
1721                     bitset(H_BINDLATE, h->h_flags))
1722                 {
1723                         expand(p, buf, sizeof buf, e);
1724                         p = buf;
1725                         if (*p == '\0')
1726                         {
1727                                 if (tTd(34, 11))
1728                                         sm_dprintf(" (skipped -- null value)\n");
1729                                 continue;
1730                         }
1731                 }
1732
1733                 if (bitset(H_BCC, h->h_flags))
1734                 {
1735                         /* Bcc: field -- either truncate or delete */
1736                         if (bitset(EF_DELETE_BCC, e->e_flags))
1737                         {
1738                                 if (tTd(34, 11))
1739                                         sm_dprintf(" (skipped -- bcc)\n");
1740                         }
1741                         else
1742                         {
1743                                 /* no other recipient headers: truncate value */
1744                                 (void) sm_strlcpyn(obuf, sizeof obuf, 2,
1745                                                    h->h_field, ":");
1746                                 if (!putline(obuf, mci))
1747                                         goto writeerr;
1748                         }
1749                         continue;
1750                 }
1751
1752                 if (tTd(34, 11))
1753                         sm_dprintf("\n");
1754
1755                 if (bitset(H_FROM|H_RCPT, h->h_flags))
1756                 {
1757                         /* address field */
1758                         bool oldstyle = bitset(EF_OLDSTYLE, e->e_flags);
1759
1760                         if (bitset(H_FROM, h->h_flags))
1761                                 oldstyle = false;
1762                         commaize(h, p, oldstyle, mci, e);
1763                 }
1764                 else
1765                 {
1766                         if (!put_vanilla_header(h, p, mci))
1767                                 goto writeerr;
1768                 }
1769         }
1770
1771         /*
1772         **  If we are converting this to a MIME message, add the
1773         **  MIME headers (but not in MIME mode!).
1774         */
1775
1776 #if MIME8TO7
1777         if (bitset(MM_MIME8BIT, MimeMode) &&
1778             bitset(EF_HAS8BIT, e->e_flags) &&
1779             !bitset(EF_DONT_MIME, e->e_flags) &&
1780             !bitnset(M_8BITS, mci->mci_mailer->m_flags) &&
1781             !bitset(MCIF_CVT8TO7|MCIF_CVT7TO8|MCIF_INMIME, mci->mci_flags) &&
1782             hvalue("MIME-Version", e->e_header) == NULL)
1783         {
1784                 if (!putline("MIME-Version: 1.0", mci))
1785                         goto writeerr;
1786                 if (hvalue("Content-Type", e->e_header) == NULL)
1787                 {
1788                         (void) sm_snprintf(obuf, sizeof obuf,
1789                                         "Content-Type: text/plain; charset=%s",
1790                                         defcharset(e));
1791                         if (!putline(obuf, mci))
1792                                 goto writeerr;
1793                 }
1794                 if (hvalue("Content-Transfer-Encoding", e->e_header) == NULL
1795                     && !putline("Content-Transfer-Encoding: 8bit", mci))
1796                         goto writeerr;
1797         }
1798 #endif /* MIME8TO7 */
1799         return true;
1800
1801   writeerr:
1802         return false;
1803 }
1804 /*
1805 **  PUT_VANILLA_HEADER -- output a fairly ordinary header
1806 **
1807 **      Parameters:
1808 **              h -- the structure describing this header
1809 **              v -- the value of this header
1810 **              mci -- the connection info for output
1811 **
1812 **      Returns:
1813 **              true iff header was written successfully
1814 */
1815
1816 static bool
1817 put_vanilla_header(h, v, mci)
1818         HDR *h;
1819         char *v;
1820         MCI *mci;
1821 {
1822         register char *nlp;
1823         register char *obp;
1824         int putflags;
1825         char obuf[MAXLINE + 256];       /* additional length for h_field */
1826
1827         putflags = PXLF_HEADER;
1828         if (bitnset(M_7BITHDRS, mci->mci_mailer->m_flags))
1829                 putflags |= PXLF_STRIP8BIT;
1830         (void) sm_snprintf(obuf, sizeof obuf, "%.200s: ", h->h_field);
1831         obp = obuf + strlen(obuf);
1832         while ((nlp = strchr(v, '\n')) != NULL)
1833         {
1834                 int l;
1835
1836                 l = nlp - v;
1837
1838                 /*
1839                 **  XXX This is broken for SPACELEFT()==0
1840                 **  However, SPACELEFT() is always > 0 unless MAXLINE==1.
1841                 */
1842
1843                 if (SPACELEFT(obuf, obp) - 1 < (size_t) l)
1844                         l = SPACELEFT(obuf, obp) - 1;
1845
1846                 (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.*s", l, v);
1847                 if (!putxline(obuf, strlen(obuf), mci, putflags))
1848                         goto writeerr;
1849                 v += l + 1;
1850                 obp = obuf;
1851                 if (*v != ' ' && *v != '\t')
1852                         *obp++ = ' ';
1853         }
1854
1855         /* XXX This is broken for SPACELEFT()==0 */
1856         (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.*s",
1857                            (int) (SPACELEFT(obuf, obp) - 1), v);
1858         return putxline(obuf, strlen(obuf), mci, putflags);
1859
1860   writeerr:
1861         return false;
1862 }
1863 /*
1864 **  COMMAIZE -- output a header field, making a comma-translated list.
1865 **
1866 **      Parameters:
1867 **              h -- the header field to output.
1868 **              p -- the value to put in it.
1869 **              oldstyle -- true if this is an old style header.
1870 **              mci -- the connection information.
1871 **              e -- the envelope containing the message.
1872 **
1873 **      Returns:
1874 **              true iff header field was written successfully
1875 **
1876 **      Side Effects:
1877 **              outputs "p" to file "fp".
1878 */
1879
1880 bool
1881 commaize(h, p, oldstyle, mci, e)
1882         register HDR *h;
1883         register char *p;
1884         bool oldstyle;
1885         register MCI *mci;
1886         register ENVELOPE *e;
1887 {
1888         register char *obp;
1889         int opos;
1890         int omax;
1891         bool firstone = true;
1892         int putflags = PXLF_HEADER;
1893         char **res;
1894         char obuf[MAXLINE + 3];
1895
1896         /*
1897         **  Output the address list translated by the
1898         **  mailer and with commas.
1899         */
1900
1901         if (tTd(14, 2))
1902                 sm_dprintf("commaize(%s: %s)\n", h->h_field, p);
1903
1904         if (bitnset(M_7BITHDRS, mci->mci_mailer->m_flags))
1905                 putflags |= PXLF_STRIP8BIT;
1906
1907         obp = obuf;
1908         (void) sm_snprintf(obp, SPACELEFT(obuf, obp), "%.200s: ",
1909                         h->h_field);
1910
1911         /* opos = strlen(obp); */
1912         opos = strlen(h->h_field) + 2;
1913         if (opos > 202)
1914                 opos = 202;
1915         obp += opos;
1916         omax = mci->mci_mailer->m_linelimit - 2;
1917         if (omax < 0 || omax > 78)
1918                 omax = 78;
1919
1920         /*
1921         **  Run through the list of values.
1922         */
1923
1924         while (*p != '\0')
1925         {
1926                 register char *name;
1927                 register int c;
1928                 char savechar;
1929                 int flags;
1930                 auto int status;
1931
1932                 /*
1933                 **  Find the end of the name.  New style names
1934                 **  end with a comma, old style names end with
1935                 **  a space character.  However, spaces do not
1936                 **  necessarily delimit an old-style name -- at
1937                 **  signs mean keep going.
1938                 */
1939
1940                 /* find end of name */
1941                 while ((isascii(*p) && isspace(*p)) || *p == ',')
1942                         p++;
1943                 name = p;
1944                 res = NULL;
1945                 for (;;)
1946                 {
1947                         auto char *oldp;
1948                         char pvpbuf[PSBUFSIZE];
1949
1950                         res = prescan(p, oldstyle ? ' ' : ',', pvpbuf,
1951                                       sizeof pvpbuf, &oldp, NULL, false);
1952                         p = oldp;
1953 #if _FFR_IGNORE_BOGUS_ADDR
1954                         /* ignore addresses that can't be parsed */
1955                         if (res == NULL)
1956                         {
1957                                 name = p;
1958                                 continue;
1959                         }
1960 #endif /* _FFR_IGNORE_BOGUS_ADDR */
1961
1962                         /* look to see if we have an at sign */
1963                         while (*p != '\0' && isascii(*p) && isspace(*p))
1964                                 p++;
1965
1966                         if (*p != '@')
1967                         {
1968                                 p = oldp;
1969                                 break;
1970                         }
1971                         ++p;
1972                         while (*p != '\0' && isascii(*p) && isspace(*p))
1973                                 p++;
1974                 }
1975                 /* at the end of one complete name */
1976
1977                 /* strip off trailing white space */
1978                 while (p >= name &&
1979                        ((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
1980                         p--;
1981                 if (++p == name)
1982                         continue;
1983
1984                 /*
1985                 **  if prescan() failed go a bit backwards; this is a hack,
1986                 **  there should be some better error recovery.
1987                 */
1988
1989                 if (res == NULL && p > name &&
1990                     !((isascii(*p) && isspace(*p)) || *p == ',' || *p == '\0'))
1991                         --p;
1992                 savechar = *p;
1993                 *p = '\0';
1994
1995                 /* translate the name to be relative */
1996                 flags = RF_HEADERADDR|RF_ADDDOMAIN;
1997                 if (bitset(H_FROM, h->h_flags))
1998                         flags |= RF_SENDERADDR;
1999 #if USERDB
2000                 else if (e->e_from.q_mailer != NULL &&
2001                          bitnset(M_UDBRECIPIENT, e->e_from.q_mailer->m_flags))
2002                 {
2003                         char *q;
2004
2005                         q = udbsender(name, e->e_rpool);
2006                         if (q != NULL)
2007                                 name = q;
2008                 }
2009 #endif /* USERDB */
2010                 status = EX_OK;
2011                 name = remotename(name, mci->mci_mailer, flags, &status, e);
2012                 if (*name == '\0')
2013                 {
2014                         *p = savechar;
2015                         continue;
2016                 }
2017                 name = denlstring(name, false, true);
2018
2019                 /* output the name with nice formatting */
2020                 opos += strlen(name);
2021                 if (!firstone)
2022                         opos += 2;
2023                 if (opos > omax && !firstone)
2024                 {
2025                         (void) sm_strlcpy(obp, ",\n", SPACELEFT(obuf, obp));
2026                         if (!putxline(obuf, strlen(obuf), mci, putflags))
2027                                 goto writeerr;
2028                         obp = obuf;
2029                         (void) sm_strlcpy(obp, "        ", sizeof obuf);
2030                         opos = strlen(obp);
2031                         obp += opos;
2032                         opos += strlen(name);
2033                 }
2034                 else if (!firstone)
2035                 {
2036                         (void) sm_strlcpy(obp, ", ", SPACELEFT(obuf, obp));
2037                         obp += 2;
2038                 }
2039
2040                 while ((c = *name++) != '\0' && obp < &obuf[MAXLINE])
2041                         *obp++ = c;
2042                 firstone = false;
2043                 *p = savechar;
2044         }
2045         if (obp < &obuf[sizeof obuf])
2046                 *obp = '\0';
2047         else
2048                 obuf[sizeof obuf - 1] = '\0';
2049         return putxline(obuf, strlen(obuf), mci, putflags);
2050
2051   writeerr:
2052         return false;
2053 }
2054
2055 /*
2056 **  COPYHEADER -- copy header list
2057 **
2058 **      This routine is the equivalent of newstr for header lists
2059 **
2060 **      Parameters:
2061 **              header -- list of header structures to copy.
2062 **              rpool -- resource pool, or NULL
2063 **
2064 **      Returns:
2065 **              a copy of 'header'.
2066 **
2067 **      Side Effects:
2068 **              none.
2069 */
2070
2071 HDR *
2072 copyheader(header, rpool)
2073         register HDR *header;
2074         SM_RPOOL_T *rpool;
2075 {
2076         register HDR *newhdr;
2077         HDR *ret;
2078         register HDR **tail = &ret;
2079
2080         while (header != NULL)
2081         {
2082                 newhdr = (HDR *) sm_rpool_malloc_x(rpool, sizeof *newhdr);
2083                 STRUCTCOPY(*header, *newhdr);
2084                 *tail = newhdr;
2085                 tail = &newhdr->h_link;
2086                 header = header->h_link;
2087         }
2088         *tail = NULL;
2089
2090         return ret;
2091 }
2092 /*
2093 **  FIX_MIME_HEADER -- possibly truncate/rebalance parameters in a MIME header
2094 **
2095 **      Run through all of the parameters of a MIME header and
2096 **      possibly truncate and rebalance the parameter according
2097 **      to MaxMimeFieldLength.
2098 **
2099 **      Parameters:
2100 **              h -- the header to truncate/rebalance
2101 **              e -- the current envelope
2102 **
2103 **      Returns:
2104 **              length of last offending field, 0 if all ok.
2105 **
2106 **      Side Effects:
2107 **              string modified in place
2108 */
2109
2110 static size_t
2111 fix_mime_header(h, e)
2112         HDR *h;
2113         ENVELOPE *e;
2114 {
2115         char *begin = h->h_value;
2116         char *end;
2117         size_t len = 0;
2118         size_t retlen = 0;
2119
2120         if (begin == NULL || *begin == '\0')
2121                 return 0;
2122
2123         /* Split on each ';' */
2124         /* find_character() never returns NULL */
2125         while ((end = find_character(begin, ';')) != NULL)
2126         {
2127                 char save = *end;
2128                 char *bp;
2129
2130                 *end = '\0';
2131
2132                 len = strlen(begin);
2133
2134                 /* Shorten individual parameter */
2135                 if (shorten_rfc822_string(begin, MaxMimeFieldLength))
2136                 {
2137                         if (len < MaxMimeFieldLength)
2138                         {
2139                                 /* we only rebalanced a bogus field */
2140                                 sm_syslog(LOG_ALERT, e->e_id,
2141                                           "Fixed MIME %s header field (possible attack)",
2142                                           h->h_field);
2143                                 if (tTd(34, 11))
2144                                         sm_dprintf("  fixed MIME %s header field (possible attack)\n",
2145                                                    h->h_field);
2146                         }
2147                         else
2148                         {
2149                                 /* we actually shortened the header */
2150                                 retlen = len;
2151                         }
2152                 }
2153
2154                 /* Collapse the possibly shortened string with rest */
2155                 bp = begin + strlen(begin);
2156                 if (bp != end)
2157                 {
2158                         char *ep = end;
2159
2160                         *end = save;
2161                         end = bp;
2162
2163                         /* copy character by character due to overlap */
2164                         while (*ep != '\0')
2165                                 *bp++ = *ep++;
2166                         *bp = '\0';
2167                 }
2168                 else
2169                         *end = save;
2170                 if (*end == '\0')
2171                         break;
2172
2173                 /* Move past ';' */
2174                 begin = end + 1;
2175         }
2176         return retlen;
2177 }