Many: drop support for *mbox-rfc4155* - a no-brainer..
[s-mailx.git] / head.c
blob67c2fb53f30dd7d79c774926f45199eea3fb7217
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Routines for processing and detecting headlines.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2016 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
35 #undef n_FILE
36 #define n_FILE head
38 #ifndef HAVE_AMALGAMATION
39 # include "nail.h"
40 #endif
42 #ifdef HAVE_IDNA
43 # if HAVE_IDNA == HAVE_IDNA_LIBIDNA
44 # include <idna.h>
45 # include <idn-free.h>
46 # include <stringprep.h>
47 # elif HAVE_IDNA == HAVE_IDNA_IDNKIT
48 # include <idn/api.h>
49 # endif
50 #endif
52 struct cmatch_data {
53 size_t tlen; /* Length of .tdata */
54 char const *tdata; /* Template date - see _cmatch_data[] */
57 /* Template characters for cmatch_data.tdata:
58 * 'A' An upper case char
59 * 'a' A lower case char
60 * ' ' A space
61 * '0' A digit
62 * 'O' An optional digit or space
63 * ':' A colon
64 * '+' Either a plus or a minus sign */
65 static struct cmatch_data const _cmatch_data[] = {
66 { 24, "Aaa Aaa O0 00:00:00 0000" }, /* BSD/ISO C90 ctime */
67 { 28, "Aaa Aaa O0 00:00:00 AAA 0000" }, /* BSD tmz */
68 { 21, "Aaa Aaa O0 00:00 0000" }, /* SysV ctime */
69 { 25, "Aaa Aaa O0 00:00 AAA 0000" }, /* SysV tmz */
70 /* RFC 822-alike From_ lines do not conform to RFC 4155, but seem to be used
71 * in the wild (by UW-imap) */
72 { 30, "Aaa Aaa O0 00:00:00 0000 +0000" },
73 /* RFC 822 with zone spec; 1. military, 2. UT, 3. north america time
74 * zone strings; note that 1. is strictly speaking not correct as some
75 * letters are not used, and 2. is not because only "UT" is defined */
76 #define __reuse "Aaa Aaa O0 00:00:00 0000 AAA"
77 { 28 - 2, __reuse }, { 28 - 1, __reuse }, { 28 - 0, __reuse },
78 { 0, NULL }
80 #define _DATE_MINLEN 21
82 /* Skip over "word" as found in From_ line */
83 static char const * _from__skipword(char const *wp);
85 /* Match the date string against the date template (tp), return if match.
86 * See _cmatch_data[] for template character description */
87 static int _cmatch(size_t len, char const *date,
88 char const *tp);
90 /* Check whether date is a valid 'From_' date.
91 * (Rather ctime(3) generated dates, according to RFC 4155) */
92 static int _is_date(char const *date);
94 /* Convert the domain part of a skinned address to IDNA.
95 * If an error occurs before Unicode information is available, revert the IDNA
96 * error to a normal CHAR one so that the error message doesn't talk Unicode */
97 #ifdef HAVE_IDNA
98 static struct addrguts * _idna_apply(struct addrguts *agp);
99 #endif
101 /* Classify and check a (possibly skinned) header body according to RFC
102 * *addr-spec* rules; if it (is assumed to has been) skinned it may however be
103 * also a file or a pipe command, so check that first, then.
104 * Otherwise perform content checking and isolate the domain part (for IDNA) */
105 static int _addrspec_check(int doskin, struct addrguts *agp);
107 /* Return the next header field found in the given message.
108 * Return >= 0 if something found, < 0 elsewise.
109 * "colon" is set to point to the colon in the header.
110 * Must deal with \ continuations & other such fraud */
111 static int gethfield(FILE *f, char **linebuf, size_t *linesize,
112 int rem, char **colon);
114 static int msgidnextc(char const **cp, int *status);
116 /* Count the occurances of c in str */
117 static int charcount(char *str, int c);
119 static char const * nexttoken(char const *cp);
121 static char const *
122 _from__skipword(char const *wp)
124 char c = 0;
125 NYD2_ENTER;
127 if (wp != NULL) {
128 while ((c = *wp++) != '\0' && !blankchar(c)) {
129 if (c == '"') {
130 while ((c = *wp++) != '\0' && c != '"')
132 if (c != '"')
133 --wp;
136 for (; blankchar(c); c = *wp++)
139 NYD2_LEAVE;
140 return (c == 0 ? NULL : wp - 1);
143 static int
144 _cmatch(size_t len, char const *date, char const *tp)
146 int ret = 0;
147 NYD2_ENTER;
149 while (len--) {
150 char c = date[len];
151 switch (tp[len]) {
152 case 'a':
153 if (!lowerchar(c))
154 goto jleave;
155 break;
156 case 'A':
157 if (!upperchar(c))
158 goto jleave;
159 break;
160 case ' ':
161 if (c != ' ')
162 goto jleave;
163 break;
164 case '0':
165 if (!digitchar(c))
166 goto jleave;
167 break;
168 case 'O':
169 if (c != ' ' && !digitchar(c))
170 goto jleave;
171 break;
172 case ':':
173 if (c != ':')
174 goto jleave;
175 break;
176 case '+':
177 if (c != '+' && c != '-')
178 goto jleave;
179 break;
182 ret = 1;
183 jleave:
184 NYD2_LEAVE;
185 return ret;
188 static int
189 _is_date(char const *date)
191 struct cmatch_data const *cmdp;
192 size_t dl;
193 int rv = 0;
194 NYD2_ENTER;
196 if ((dl = strlen(date)) >= _DATE_MINLEN)
197 for (cmdp = _cmatch_data; cmdp->tdata != NULL; ++cmdp)
198 if (dl == cmdp->tlen && (rv = _cmatch(dl, date, cmdp->tdata)))
199 break;
200 NYD2_LEAVE;
201 return rv;
204 #ifdef HAVE_IDNA
205 # if HAVE_IDNA == HAVE_IDNA_LIBIDNA
206 static struct addrguts *
207 _idna_apply(struct addrguts *agp)
209 char *idna_utf8, *idna_ascii, *cs;
210 size_t sz, i;
211 NYD_ENTER;
213 sz = agp->ag_slen - agp->ag_sdom_start;
214 assert(sz > 0);
215 idna_utf8 = ac_alloc(sz +1);
216 memcpy(idna_utf8, agp->ag_skinned + agp->ag_sdom_start, sz);
217 idna_utf8[sz] = '\0';
219 /* GNU Libidn settles on top of iconv(3) without any fallback, so let's just
220 * let it perform the charset conversion, if any should be necessary */
221 if (!(options & OPT_UNICODE)) {
222 char const *tcs = charset_get_lc();
223 idna_ascii = idna_utf8;
224 idna_utf8 = stringprep_convert(idna_ascii, "UTF-8", tcs);
225 i = (idna_utf8 == NULL && errno == EINVAL);
226 ac_free(idna_ascii);
228 if (idna_utf8 == NULL) {
229 if (i)
230 n_err(_("Cannot convert from %s to %s\n"), tcs, "UTF-8");
231 agp->ag_n_flags ^= NAME_ADDRSPEC_ERR_IDNA | NAME_ADDRSPEC_ERR_CHAR;
232 goto jleave;
236 if (idna_to_ascii_8z(idna_utf8, &idna_ascii, 0) != IDNA_SUCCESS) {
237 agp->ag_n_flags ^= NAME_ADDRSPEC_ERR_IDNA | NAME_ADDRSPEC_ERR_CHAR;
238 goto jleave1;
241 /* Replace the domain part of .ag_skinned with IDNA version */
242 sz = strlen(idna_ascii);
243 i = agp->ag_sdom_start;
244 cs = salloc(agp->ag_slen - i + sz +1);
245 memcpy(cs, agp->ag_skinned, i);
246 memcpy(cs + i, idna_ascii, sz);
247 i += sz;
248 cs[i] = '\0';
250 agp->ag_skinned = cs;
251 agp->ag_slen = i;
252 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags,
253 NAME_NAME_SALLOC | NAME_SKINNED | NAME_IDNA, 0);
255 idn_free(idna_ascii);
256 jleave1:
257 if (options & OPT_UNICODE)
258 ac_free(idna_utf8);
259 else
260 idn_free(idna_utf8);
261 jleave:
262 NYD_LEAVE;
263 return agp;
266 # elif HAVE_IDNA == HAVE_IDNA_IDNKIT /* IDNA==LIBIDNA */
267 static struct addrguts *
268 _idna_apply(struct addrguts *agp)
270 char *idna_in, *idna_out, *cs;
271 size_t sz, i;
272 idn_result_t r;
273 NYD_ENTER;
275 sz = agp->ag_slen - agp->ag_sdom_start;
276 assert(sz > 0);
277 idna_in = ac_alloc(sz +1);
278 memcpy(idna_in, agp->ag_skinned + agp->ag_sdom_start, sz);
279 idna_in[sz] = '\0';
281 for (idna_out = NULL, sz = HOST_NAME_MAX +1;; sz += HOST_NAME_MAX) {
282 idna_out = ac_alloc(sz);
284 r = idn_encodename(IDN_ENCODE_APP, idna_in, idna_out, sz);
285 switch (r) {
286 case idn_success:
287 case idn_buffer_overflow:
288 break;
289 case idn_invalid_encoding:
290 n_err(_("Cannot convert from %s to %s\n"), charset_get_lc(), "UTF-8");
291 /* FALLTHRU */
292 default:
293 agp->ag_n_flags ^= NAME_ADDRSPEC_ERR_IDNA | NAME_ADDRSPEC_ERR_CHAR;
294 goto jleave;
297 if (r == idn_success)
298 break;
299 ac_free(idna_out);
302 /* Replace the domain part of .ag_skinned with IDNA version */
303 sz = strlen(idna_out);
304 i = agp->ag_sdom_start;
305 cs = salloc(agp->ag_slen - i + sz +1);
306 memcpy(cs, agp->ag_skinned, i);
307 memcpy(cs + i, idna_out, sz);
308 i += sz;
309 cs[i] = '\0';
311 agp->ag_skinned = cs;
312 agp->ag_slen = i;
313 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags,
314 NAME_NAME_SALLOC | NAME_SKINNED | NAME_IDNA, 0);
316 jleave:
317 ac_free(idna_out);
318 ac_free(idna_in);
319 NYD_LEAVE;
320 return agp;
322 # endif /* IDNA==IDNKIT */
323 #endif /* HAVE_IDNA */
325 static int
326 _addrspec_check(int skinned, struct addrguts *agp)
328 char *addr, *p;
329 bool_t in_quote;
330 ui8_t in_domain, hadat;
331 union {char c; unsigned char u;} c;
332 #ifdef HAVE_IDNA
333 ui8_t use_idna;
334 #endif
335 NYD_ENTER;
337 #ifdef HAVE_IDNA
338 use_idna = ok_blook(idna_disable) ? 0 : 1;
339 #endif
340 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
341 addr = agp->ag_skinned;
343 if (agp->ag_iaddr_aend - agp->ag_iaddr_start == 0) {
344 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
345 goto jleave;
348 /* If the field is not a recipient, it cannot be a file or a pipe */
349 if (!skinned)
350 goto jaddr_check;
352 /* When changing any of the following adjust any RECIPIENTADDRSPEC;
353 * grep the latter for the complete picture */
354 if (*addr == '|') {
355 agp->ag_n_flags |= NAME_ADDRSPEC_ISPIPE;
356 goto jleave;
358 if (addr[0] == '/' || (addr[0] == '.' && addr[1] == '/'))
359 goto jisfile;
360 if (memchr(addr, '@', agp->ag_slen) == NULL) {
361 if (*addr == '+')
362 goto jisfile;
363 for (p = addr; (c.c = *p); ++p) {
364 if (c.c == '!' || c.c == '%')
365 break;
366 if (c.c == '/') {
367 jisfile:
368 agp->ag_n_flags |= NAME_ADDRSPEC_ISFILE;
369 goto jleave;
374 jaddr_check:
375 in_quote = FAL0;
376 in_domain = hadat = 0;
378 for (p = addr; (c.c = *p++) != '\0';) {
379 if (c.c == '"') {
380 in_quote = !in_quote;
381 } else if (c.u < 040 || c.u >= 0177) { /* TODO no magics: !bodychar()? */
382 #ifdef HAVE_IDNA
383 if (in_domain && use_idna > 0) {
384 if (use_idna == 1)
385 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_IDNA,
386 c.u);
387 use_idna = 2;
388 } else
389 #endif
390 break;
391 } else if (in_domain == 2) {
392 if ((c.c == ']' && *p != '\0') || c.c == '\\' || whitechar(c.c))
393 break;
394 } else if (in_quote && in_domain == 0) {
395 /*EMPTY*/;
396 } else if (c.c == '\\' && *p != '\0') {
397 ++p;
398 } else if (c.c == '@') {
399 if (hadat++ > 0) {
400 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_ATSEQ,
401 c.u);
402 goto jleave;
404 agp->ag_sdom_start = PTR2SIZE(p - addr);
405 agp->ag_n_flags |= NAME_ADDRSPEC_ISADDR; /* TODO .. really? */
406 in_domain = (*p == '[') ? 2 : 1;
407 continue;
408 } else if (c.c == '(' || c.c == ')' || c.c == '<' || c.c == '>' ||
409 c.c == ',' || c.c == ';' || c.c == ':' || c.c == '\\' ||
410 c.c == '[' || c.c == ']')
411 break;
412 hadat = 0;
414 if (c.c != '\0') {
415 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_CHAR, c.u);
416 goto jleave;
419 if (!(agp->ag_n_flags & NAME_ADDRSPEC_ISADDR))
420 agp->ag_n_flags |= NAME_ADDRSPEC_ISNAME;
422 #ifdef HAVE_IDNA
423 if (use_idna == 2)
424 agp = _idna_apply(agp);
425 #endif
426 jleave:
427 NYD_LEAVE;
428 return ((agp->ag_n_flags & NAME_ADDRSPEC_INVALID) != 0);
431 static int
432 gethfield(FILE *f, char **linebuf, size_t *linesize, int rem, char **colon)
434 char *line2 = NULL, *cp, *cp2;
435 size_t line2size = 0;
436 int c, isenc;
437 NYD2_ENTER;
439 if (*linebuf == NULL)
440 *linebuf = srealloc(*linebuf, *linesize = 1);
441 **linebuf = '\0';
442 for (;;) {
443 if (--rem < 0) {
444 rem = -1;
445 break;
447 if ((c = readline_restart(f, linebuf, linesize, 0)) <= 0) {
448 rem = -1;
449 break;
451 for (cp = *linebuf; fieldnamechar(*cp); ++cp)
453 if (cp > *linebuf)
454 while (blankchar(*cp))
455 ++cp;
456 if (*cp != ':' || cp == *linebuf)
457 continue;
459 /* I guess we got a headline. Handle wraparound */
460 *colon = cp;
461 cp = *linebuf + c;
462 for (;;) {
463 isenc = 0;
464 while (PTRCMP(--cp, >=, *linebuf) && blankchar(*cp))
466 cp++;
467 if (rem <= 0)
468 break;
469 if (PTRCMP(cp - 8, >=, *linebuf) && cp[-1] == '=' && cp[-2] == '?')
470 isenc |= 1;
471 ungetc(c = getc(f), f);
472 if (!blankchar(c))
473 break;
474 c = readline_restart(f, &line2, &line2size, 0);
475 if (c < 0)
476 break;
477 --rem;
478 for (cp2 = line2; blankchar(*cp2); ++cp2)
480 c -= (int)PTR2SIZE(cp2 - line2);
481 if (cp2[0] == '=' && cp2[1] == '?' && c > 8)
482 isenc |= 2;
483 if (PTRCMP(cp + c, >=, *linebuf + *linesize - 2)) {
484 size_t diff = PTR2SIZE(cp - *linebuf),
485 colondiff = PTR2SIZE(*colon - *linebuf);
486 *linebuf = srealloc(*linebuf, *linesize += c + 2);
487 cp = &(*linebuf)[diff];
488 *colon = &(*linebuf)[colondiff];
490 if (isenc != 3)
491 *cp++ = ' ';
492 memcpy(cp, cp2, c);
493 cp += c;
495 *cp = '\0';
497 if (line2 != NULL)
498 free(line2);
499 break;
501 NYD2_LEAVE;
502 return rem;
505 static int
506 msgidnextc(char const **cp, int *status)
508 int c;
509 NYD2_ENTER;
511 assert(cp != NULL);
512 assert(*cp != NULL);
513 assert(status != NULL);
515 for (;;) {
516 if (*status & 01) {
517 if (**cp == '"') {
518 *status &= ~01;
519 (*cp)++;
520 continue;
522 if (**cp == '\\') {
523 (*cp)++;
524 if (**cp == '\0')
525 goto jeof;
527 goto jdfl;
529 switch (**cp) {
530 case '(':
531 *cp = skip_comment(&(*cp)[1]);
532 continue;
533 case '>':
534 case '\0':
535 jeof:
536 c = '\0';
537 goto jleave;
538 case '"':
539 (*cp)++;
540 *status |= 01;
541 continue;
542 case '@':
543 *status |= 02;
544 /*FALLTHRU*/
545 default:
546 jdfl:
547 c = *(*cp)++ & 0377;
548 c = (*status & 02) ? lowerconv(c) : c;
549 goto jleave;
552 jleave:
553 NYD2_LEAVE;
554 return c;
557 static int
558 charcount(char *str, int c)
560 char *cp;
561 int i;
562 NYD2_ENTER;
564 for (i = 0, cp = str; *cp; ++cp)
565 if (*cp == c)
566 ++i;
567 NYD2_LEAVE;
568 return i;
571 static char const *
572 nexttoken(char const *cp)
574 NYD2_ENTER;
575 for (;;) {
576 if (*cp == '\0') {
577 cp = NULL;
578 break;
581 if (*cp == '(') {
582 size_t nesting = 1;
584 do switch (*++cp) {
585 case '(':
586 ++nesting;
587 break;
588 case ')':
589 --nesting;
590 break;
591 } while (nesting > 0 && *cp != '\0'); /* XXX error? */
592 } else if (blankchar(*cp) || *cp == ',')
593 ++cp;
594 else
595 break;
597 NYD2_LEAVE;
598 return cp;
601 FL char const *
602 myaddrs(struct header *hp)
604 struct name *np;
605 char const *rv, *mta;
606 NYD_ENTER;
608 if (hp != NULL && (np = hp->h_from) != NULL) {
609 if ((rv = np->n_fullname) != NULL)
610 goto jleave;
611 if ((rv = np->n_name) != NULL)
612 goto jleave;
615 if ((rv = ok_vlook(from)) != NULL)
616 goto jleave;
618 /* When invoking *sendmail* directly, it's its task to generate an otherwise
619 * undeterminable From: address. However, if the user sets *hostname*,
620 * accept his desire */
621 if (ok_vlook(hostname) != NULL)
622 goto jnodename;
623 if (ok_vlook(smtp) != NULL || /* TODO obsolete -> mta */
624 /* TODO pretty hacky for now (this entire fun), later: url_creat()! */
625 ((mta = ok_vlook(mta)) != NULL &&
626 (mta = n_servbyname(mta, NULL)) != NULL && *mta != '\0'))
627 goto jnodename;
628 jleave:
629 NYD_LEAVE;
630 return rv;
632 jnodename:{
633 char *hn, *cp;
634 size_t i;
636 hn = nodename(1);
637 i = strlen(myname) + strlen(hn) + 1 +1;
638 rv = cp = salloc(i);
639 sstpcpy(sstpcpy(sstpcpy(cp, myname), "@"), hn);
641 goto jleave;
644 FL char const *
645 myorigin(struct header *hp)
647 char const *rv = NULL, *ccp;
648 struct name *np;
649 NYD_ENTER;
651 if ((ccp = myaddrs(hp)) != NULL &&
652 (np = lextract(ccp, GEXTRA | GFULL)) != NULL)
653 rv = (np->n_flink != NULL) ? ok_vlook(sender) : ccp;
654 NYD_LEAVE;
655 return rv;
658 FL int
659 is_head(char const *linebuf, size_t linelen, bool_t compat)
661 char date[FROM_DATEBUF];
662 int rv;
663 NYD2_ENTER;
665 if ((rv = (linelen >= 5 && !memcmp(linebuf, "From ", 5))) && !compat)
666 rv = (extract_date_from_from_(linebuf, linelen, date) && _is_date(date));
667 NYD2_LEAVE;
668 return rv;
671 FL int
672 extract_date_from_from_(char const *line, size_t linelen,
673 char datebuf[FROM_DATEBUF])
675 int rv = 0;
676 char const *cp = line;
677 NYD_ENTER;
679 /* "From " */
680 cp = _from__skipword(cp);
681 if (cp == NULL)
682 goto jerr;
683 /* "addr-spec " */
684 cp = _from__skipword(cp);
685 if (cp == NULL)
686 goto jerr;
687 if (cp[0] == 't' && cp[1] == 't' && cp[2] == 'y') {
688 cp = _from__skipword(cp);
689 if (cp == NULL)
690 goto jerr;
692 /* It seems there are invalid MBOX archives in the wild, compare
693 * . http://bugs.debian.org/624111
694 * . [Mutt] #3868: mutt should error if the imported mailbox is invalid
695 * What they do is that they obfuscate the address to "name at host",
696 * and even "name at host dot dom dot dom. I think we should handle that */
697 else if(cp[0] == 'a' && cp[1] == 't' && cp[2] == ' '){
698 cp += 3;
699 jat_dot:
700 cp = _from__skipword(cp);
701 if (cp == NULL)
702 goto jerr;
703 if(cp[0] == 'd' && cp[1] == 'o' && cp[2] == 't' && cp[3] == ' '){
704 cp += 4;
705 goto jat_dot;
709 linelen -= PTR2SIZE(cp - line);
710 if (linelen < _DATE_MINLEN)
711 goto jerr;
712 if (cp[linelen - 1] == '\n') {
713 --linelen;
714 /* (Rather IMAP/POP3 only) */
715 if (cp[linelen - 1] == '\r')
716 --linelen;
717 if (linelen < _DATE_MINLEN)
718 goto jerr;
720 if (linelen >= FROM_DATEBUF)
721 goto jerr;
723 rv = 1;
724 jleave:
725 memcpy(datebuf, cp, linelen);
726 datebuf[linelen] = '\0';
727 NYD_LEAVE;
728 return rv;
729 jerr:
730 cp = _("<Unknown date>");
731 linelen = strlen(cp);
732 if (linelen >= FROM_DATEBUF)
733 linelen = FROM_DATEBUF;
734 goto jleave;
737 FL void
738 extract_header(FILE *fp, struct header *hp, si8_t *checkaddr_err)
740 /* See the prototype declaration for the hairy relationship of
741 * options&OPT_t_FLAG and/or pstate&PS_t_FLAG in here */
742 struct n_header_field **hftail;
743 struct header nh, *hq = &nh;
744 char *linebuf = NULL /* TODO line pool */, *colon;
745 size_t linesize = 0, seenfields = 0;
746 int lc, c;
747 char const *val, *cp;
748 NYD_ENTER;
750 memset(hq, 0, sizeof *hq);
751 if ((pstate & PS_t_FLAG) && (options & OPT_t_FLAG)) {
752 hq->h_to = hp->h_to;
753 hq->h_cc = hp->h_cc;
754 hq->h_bcc = hp->h_bcc;
756 hftail = &hq->h_user_headers;
758 for (lc = 0; readline_restart(fp, &linebuf, &linesize, 0) > 0; ++lc)
761 /* TODO yippieia, cat(check(lextract)) :-) */
762 rewind(fp);
763 while ((lc = gethfield(fp, &linebuf, &linesize, lc, &colon)) >= 0) {
764 struct name *np;
766 /* We explicitly allow EAF_NAME for some addressees since aliases are not
767 * yet expanded when we parse these! */
768 if ((val = thisfield(linebuf, "to")) != NULL) {
769 ++seenfields;
770 hq->h_to = cat(hq->h_to, checkaddrs(lextract(val, GTO | GFULL),
771 EACM_NORMAL | EAF_NAME, checkaddr_err));
772 } else if ((val = thisfield(linebuf, "cc")) != NULL) {
773 ++seenfields;
774 hq->h_cc = cat(hq->h_cc, checkaddrs(lextract(val, GCC | GFULL),
775 EACM_NORMAL | EAF_NAME, checkaddr_err));
776 } else if ((val = thisfield(linebuf, "bcc")) != NULL) {
777 ++seenfields;
778 hq->h_bcc = cat(hq->h_bcc, checkaddrs(lextract(val, GBCC | GFULL),
779 EACM_NORMAL | EAF_NAME, checkaddr_err));
780 } else if ((val = thisfield(linebuf, "from")) != NULL) {
781 if (!(pstate & PS_t_FLAG) || (options & OPT_t_FLAG)) {
782 ++seenfields;
783 hq->h_from = cat(hq->h_from,
784 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
785 EACM_STRICT, NULL));
787 } else if ((val = thisfield(linebuf, "reply-to")) != NULL) {
788 ++seenfields;
789 hq->h_replyto = cat(hq->h_replyto,
790 checkaddrs(lextract(val, GEXTRA | GFULL), EACM_STRICT, NULL));
791 } else if ((val = thisfield(linebuf, "sender")) != NULL) {
792 if (!(pstate & PS_t_FLAG) || (options & OPT_t_FLAG)) {
793 ++seenfields;
794 hq->h_sender = cat(hq->h_sender, /* TODO cat? check! */
795 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
796 EACM_STRICT, NULL));
797 } else
798 goto jebadhead;
799 } else if ((val = thisfield(linebuf, "subject")) != NULL ||
800 (val = thisfield(linebuf, "subj")) != NULL) {
801 ++seenfields;
802 for (cp = val; blankchar(*cp); ++cp)
804 hq->h_subject = (hq->h_subject != NULL)
805 ? save2str(hq->h_subject, cp) : savestr(cp);
807 /* The remaining are mostly hacked in and thus TODO -- at least in
808 * TODO respect to their content checking */
809 else if((val = thisfield(linebuf, "message-id")) != NULL){
810 if(pstate & PS_t_FLAG){
811 np = checkaddrs(lextract(val, GREF),
812 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
813 NULL);
814 if (np == NULL || np->n_flink != NULL)
815 goto jebadhead;
816 ++seenfields;
817 hq->h_message_id = np;
818 }else
819 goto jebadhead;
820 }else if((val = thisfield(linebuf, "in-reply-to")) != NULL){
821 if(pstate & PS_t_FLAG){
822 np = checkaddrs(lextract(val, GREF),
823 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
824 NULL);
825 if (np == NULL || np->n_flink != NULL)
826 goto jebadhead;
827 ++seenfields;
828 hq->h_in_reply_to = np;
829 }else
830 goto jebadhead;
831 }else if((val = thisfield(linebuf, "references")) != NULL){
832 if(pstate & PS_t_FLAG){
833 ++seenfields;
834 /* TODO Limit number of references TODO better on parser side */
835 hq->h_ref = cat(hq->h_ref, checkaddrs(extract(val, GREF),
836 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
837 NULL));
838 }else
839 goto jebadhead;
841 /* and that is very hairy */
842 else if((val = thisfield(linebuf, "mail-followup-to")) != NULL){
843 if(pstate & PS_t_FLAG){
844 ++seenfields;
845 hq->h_mft = cat(hq->h_mft, checkaddrs(lextract(val, GEXTRA | GFULL),
846 /*EACM_STRICT | TODO '/' valid!! | EACM_NOLOG | */EACM_NONAME,
847 checkaddr_err));
848 }else
849 goto jebadhead;
851 /* A free-form user header; gethfield() did some verification already.. */
852 else{
853 struct n_header_field *hfp;
854 ui32_t nl, bl;
855 char const *nstart;
857 for(nstart = cp = linebuf;; ++cp)
858 if(!fieldnamechar(*cp))
859 break;
860 nl = (ui32_t)PTR2SIZE(cp - nstart);
862 while(blankchar(*cp))
863 ++cp;
864 if(*cp++ != ':'){
865 jebadhead:
866 n_err(_("Ignoring header field: %s\n"), linebuf);
867 continue;
869 while(blankchar(*cp))
870 ++cp;
871 bl = (ui32_t)strlen(cp) +1;
873 ++seenfields;
874 *hftail = hfp = salloc(VSTRUCT_SIZEOF(struct n_header_field, hf_dat) +
875 nl +1 + bl);
876 hftail = &hfp->hf_next;
877 hfp->hf_next = NULL;
878 hfp->hf_nl = nl;
879 hfp->hf_bl = bl - 1;
880 memcpy(hfp->hf_dat, nstart, nl);
881 hfp->hf_dat[nl++] = '\0';
882 memcpy(hfp->hf_dat + nl, cp, bl);
886 /* In case the blank line after the header has been edited out. Otherwise,
887 * fetch the header separator */
888 if (linebuf != NULL) {
889 if (linebuf[0] != '\0') {
890 for (cp = linebuf; *(++cp) != '\0';)
892 fseek(fp, (long)-PTR2SIZE(1 + cp - linebuf), SEEK_CUR);
893 } else {
894 if ((c = getc(fp)) != '\n' && c != EOF)
895 ungetc(c, fp);
899 if (seenfields > 0) {
900 hp->h_to = hq->h_to;
901 hp->h_cc = hq->h_cc;
902 hp->h_bcc = hq->h_bcc;
903 hp->h_from = hq->h_from;
904 hp->h_replyto = hq->h_replyto;
905 hp->h_sender = hq->h_sender;
906 if (hq->h_subject != NULL || !(pstate & PS_t_FLAG) ||
907 !(options & OPT_t_FLAG))
908 hp->h_subject = hq->h_subject;
909 hp->h_user_headers = hq->h_user_headers;
911 if (pstate & PS_t_FLAG) {
912 hp->h_ref = hq->h_ref;
913 hp->h_message_id = hq->h_message_id;
914 hp->h_in_reply_to = hq->h_in_reply_to;
915 hp->h_mft = hq->h_mft;
917 /* And perform additional validity checks so that we don't bail later
918 * on TODO this is good and the place where this should occur,
919 * TODO unfortunately a lot of other places do again and blabla */
920 if (pstate & PS_t_FLAG) {
921 if (hp->h_from == NULL)
922 hp->h_from = option_r_arg;
923 else if (hp->h_from->n_flink != NULL && hp->h_sender == NULL)
924 hp->h_sender = lextract(ok_vlook(sender),
925 GEXTRA | GFULL | GFULLEXTRA);
928 } else
929 n_err(_("Restoring deleted header lines\n"));
931 if (linebuf != NULL)
932 free(linebuf);
933 NYD_LEAVE;
936 FL char *
937 hfield_mult(char const *field, struct message *mp, int mult)
939 FILE *ibuf;
940 int lc;
941 struct str hfs;
942 size_t linesize = 0; /* TODO line pool */
943 char *linebuf = NULL, *colon;
944 char const *hfield;
945 NYD_ENTER;
947 /* There are (spam) messages which have header bytes which are many KB when
948 * joined, so resize a single heap storage until we are done if we shall
949 * collect a field that may have multiple bodies; only otherwise use the
950 * string dope directly */
951 memset(&hfs, 0, sizeof hfs);
953 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
954 goto jleave;
955 if ((lc = mp->m_lines - 1) < 0)
956 goto jleave;
958 if ((mp->m_flag & MNOFROM) == 0 &&
959 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
960 goto jleave;
961 while (lc > 0) {
962 if ((lc = gethfield(ibuf, &linebuf, &linesize, lc, &colon)) < 0)
963 break;
964 if ((hfield = thisfield(linebuf, field)) != NULL && *hfield != '\0') {
965 if (mult)
966 n_str_add_buf(&hfs, hfield, strlen(hfield));
967 else {
968 hfs.s = savestr(hfield);
969 break;
974 jleave:
975 if (linebuf != NULL)
976 free(linebuf);
977 if (mult && hfs.s != NULL) {
978 colon = savestrbuf(hfs.s, hfs.l);
979 free(hfs.s);
980 hfs.s = colon;
982 NYD_LEAVE;
983 return hfs.s;
986 FL char const *
987 thisfield(char const *linebuf, char const *field)
989 char const *rv = NULL;
990 NYD2_ENTER;
992 while (lowerconv(*linebuf) == lowerconv(*field)) {
993 ++linebuf;
994 ++field;
996 if (*field != '\0')
997 goto jleave;
999 while (blankchar(*linebuf))
1000 ++linebuf;
1001 if (*linebuf++ != ':')
1002 goto jleave;
1004 while (blankchar(*linebuf)) /* TODO header parser.. strip trailing WS?!? */
1005 ++linebuf;
1006 rv = linebuf;
1007 jleave:
1008 NYD2_LEAVE;
1009 return rv;
1012 FL char *
1013 nameof(struct message *mp, int reptype)
1015 char *cp, *cp2;
1016 NYD_ENTER;
1018 cp = skin(name1(mp, reptype));
1019 if (reptype != 0 || charcount(cp, '!') < 2)
1020 goto jleave;
1021 cp2 = strrchr(cp, '!');
1022 --cp2;
1023 while (cp2 > cp && *cp2 != '!')
1024 --cp2;
1025 if (*cp2 == '!')
1026 cp = cp2 + 1;
1027 jleave:
1028 NYD_LEAVE;
1029 return cp;
1032 FL char const *
1033 skip_comment(char const *cp)
1035 size_t nesting;
1036 NYD_ENTER;
1038 for (nesting = 1; nesting > 0 && *cp; ++cp) {
1039 switch (*cp) {
1040 case '\\':
1041 if (cp[1])
1042 ++cp;
1043 break;
1044 case '(':
1045 ++nesting;
1046 break;
1047 case ')':
1048 --nesting;
1049 break;
1052 NYD_LEAVE;
1053 return cp;
1056 FL char const *
1057 routeaddr(char const *name)
1059 char const *np, *rp = NULL;
1060 NYD_ENTER;
1062 for (np = name; *np; np++) {
1063 switch (*np) {
1064 case '(':
1065 np = skip_comment(np + 1) - 1;
1066 break;
1067 case '"':
1068 while (*np) {
1069 if (*++np == '"')
1070 break;
1071 if (*np == '\\' && np[1])
1072 np++;
1074 break;
1075 case '<':
1076 rp = np;
1077 break;
1078 case '>':
1079 goto jleave;
1082 rp = NULL;
1083 jleave:
1084 NYD_LEAVE;
1085 return rp;
1088 FL enum expand_addr_flags
1089 expandaddr_to_eaf(void)
1091 struct eafdesc {
1092 char const *eafd_name;
1093 bool_t eafd_is_target;
1094 ui8_t eafd_andoff;
1095 ui8_t eafd_or;
1096 } const eafa[] = {
1097 {"restrict", FAL0, EAF_TARGET_MASK, EAF_RESTRICT | EAF_RESTRICT_TARGETS},
1098 {"fail", FAL0, EAF_NONE, EAF_FAIL},
1099 {"all", TRU1, EAF_NONE, EAF_TARGET_MASK},
1100 {"file", TRU1, EAF_NONE, EAF_FILE},
1101 {"pipe", TRU1, EAF_NONE, EAF_PIPE},
1102 {"name", TRU1, EAF_NONE, EAF_NAME},
1103 {"addr", TRU1, EAF_NONE, EAF_ADDR}
1104 }, *eafp;
1106 char *buf;
1107 enum expand_addr_flags rv;
1108 char const *cp;
1109 NYD2_ENTER;
1111 if ((cp = ok_vlook(expandaddr)) == NULL)
1112 rv = EAF_RESTRICT_TARGETS;
1113 else if (*cp == '\0')
1114 rv = EAF_TARGET_MASK;
1115 else {
1116 rv = EAF_TARGET_MASK;
1118 for (buf = savestr(cp); (cp = n_strsep(&buf, ',', TRU1)) != NULL;) {
1119 bool_t minus;
1121 if ((minus = (*cp == '-')) || *cp == '+')
1122 ++cp;
1123 for (eafp = eafa;; ++eafp) {
1124 if (eafp == eafa + NELEM(eafa)) {
1125 if (options & OPT_D_V)
1126 n_err(_("Unknown *expandaddr* value: %s\n"), cp);
1127 break;
1128 } else if (!asccasecmp(cp, eafp->eafd_name)) {
1129 if (!minus) {
1130 rv &= ~eafp->eafd_andoff;
1131 rv |= eafp->eafd_or;
1132 } else {
1133 if (eafp->eafd_is_target)
1134 rv &= ~eafp->eafd_or;
1135 else if (options & OPT_D_V)
1136 n_err(_("minus - prefix invalid for *expandaddr* value: "
1137 "%s\n"), --cp);
1139 break;
1140 } else if (!asccasecmp(cp, "noalias")) { /* TODO v15 OBSOLETE */
1141 OBSOLETE(_("*expandaddr*: noalias is henceforth -name"));
1142 rv &= ~EAF_NAME;
1143 break;
1148 if ((rv & EAF_RESTRICT) && (options & (OPT_INTERACTIVE | OPT_TILDE_FLAG)))
1149 rv |= EAF_TARGET_MASK;
1150 else if (options & OPT_D_V) {
1151 if (!(rv & EAF_TARGET_MASK))
1152 n_err(_("*expandaddr* doesn't allow any addressees\n"));
1153 else if ((rv & EAF_FAIL) && (rv & EAF_TARGET_MASK) == EAF_TARGET_MASK)
1154 n_err(_("*expandaddr* with fail, but no restrictions to apply\n"));
1157 NYD2_LEAVE;
1158 return rv;
1161 FL si8_t
1162 is_addr_invalid(struct name *np, enum expand_addr_check_mode eacm)
1164 char cbuf[sizeof "'\\U12340'"];
1165 enum expand_addr_flags eaf;
1166 char const *cs;
1167 int f;
1168 si8_t rv;
1169 NYD_ENTER;
1171 f = np->n_flags;
1173 if ((rv = ((f & NAME_ADDRSPEC_INVALID) != 0))) {
1174 if ((eacm & EACM_NOLOG) || (f & NAME_ADDRSPEC_ERR_EMPTY)) {
1176 } else {
1177 ui32_t c;
1178 char const *fmt = "'\\x%02X'";
1179 bool_t ok8bit = TRU1;
1181 if (f & NAME_ADDRSPEC_ERR_IDNA) {
1182 cs = _("Invalid domain name: %s, character %s\n");
1183 fmt = "'\\U%04X'";
1184 ok8bit = FAL0;
1185 } else if (f & NAME_ADDRSPEC_ERR_ATSEQ)
1186 cs = _("%s contains invalid %s sequence\n");
1187 else
1188 cs = _("%s contains invalid character %s\n");
1190 c = NAME_ADDRSPEC_ERR_GETWC(f);
1191 snprintf(cbuf, sizeof cbuf,
1192 (ok8bit && c >= 040 && c <= 0177 ? "'%c'" : fmt), c);
1193 goto jprint;
1195 goto jleave;
1198 /* *expandaddr* stuff */
1199 if (!(rv = ((eacm & EACM_MODE_MASK) != EACM_NONE)))
1200 goto jleave;
1202 eaf = expandaddr_to_eaf();
1204 if ((eacm & EACM_STRICT) && (f & NAME_ADDRSPEC_ISFILEORPIPE)) {
1205 if (eaf & EAF_FAIL)
1206 rv = -rv;
1207 cs = _("%s%s: file or pipe addressees not allowed here\n");
1208 if (eacm & EACM_NOLOG)
1209 goto jleave;
1210 else
1211 goto j0print;
1214 eaf |= (eacm & EAF_TARGET_MASK);
1215 if (eacm & EACM_NONAME)
1216 eaf &= ~EAF_NAME;
1218 if (eaf == EAF_NONE) {
1219 rv = FAL0;
1220 goto jleave;
1222 if (eaf & EAF_FAIL)
1223 rv = -rv;
1225 if (!(eaf & EAF_FILE) && (f & NAME_ADDRSPEC_ISFILE)) {
1226 cs = _("%s%s: *expandaddr* doesn't allow file target\n");
1227 if (eacm & EACM_NOLOG)
1228 goto jleave;
1229 } else if (!(eaf & EAF_PIPE) && (f & NAME_ADDRSPEC_ISPIPE)) {
1230 cs = _("%s%s: *expandaddr* doesn't allow command pipe target\n");
1231 if (eacm & EACM_NOLOG)
1232 goto jleave;
1233 } else if (!(eaf & EAF_NAME) && (f & NAME_ADDRSPEC_ISNAME)) {
1234 cs = _("%s%s: *expandaddr* doesn't allow user name target\n");
1235 if (eacm & EACM_NOLOG)
1236 goto jleave;
1237 } else if (!(eaf & EAF_ADDR) && (f & NAME_ADDRSPEC_ISADDR)) {
1238 cs = _("%s%s: *expandaddr* doesn't allow mail address target\n");
1239 if (eacm & EACM_NOLOG)
1240 goto jleave;
1241 } else {
1242 rv = FAL0;
1243 goto jleave;
1246 j0print:
1247 cbuf[0] = '\0';
1248 jprint:
1249 n_err(cs, n_shell_quote_cp(np->n_name, TRU1), cbuf);
1250 jleave:
1251 NYD_LEAVE;
1252 return rv;
1255 FL char *
1256 skin(char const *name)
1258 struct addrguts ag;
1259 char *ret = NULL;
1260 NYD_ENTER;
1262 if (name != NULL) {
1263 addrspec_with_guts(1, name, &ag);
1264 ret = ag.ag_skinned;
1265 if (!(ag.ag_n_flags & NAME_NAME_SALLOC))
1266 ret = savestrbuf(ret, ag.ag_slen);
1268 NYD_LEAVE;
1269 return ret;
1272 /* TODO addrspec_with_guts: RFC 5322
1273 * TODO addrspec_with_guts: trim whitespace ETC. ETC. ETC.!!! */
1274 FL int
1275 addrspec_with_guts(int doskin, char const *name, struct addrguts *agp)
1277 char const *cp;
1278 char *cp2, *bufend, *nbuf, c, gotlt, gotaddr, lastsp;
1279 int rv = 1;
1280 NYD_ENTER;
1282 memset(agp, 0, sizeof *agp);
1284 if ((agp->ag_input = name) == NULL || (agp->ag_ilen = strlen(name)) == 0) {
1285 agp->ag_skinned = UNCONST(""); /* ok: NAME_SALLOC is not set */
1286 agp->ag_slen = 0;
1287 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
1288 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
1289 goto jleave;
1292 if (!doskin || !anyof(name, "(< ")) {
1293 /*agp->ag_iaddr_start = 0;*/
1294 agp->ag_iaddr_aend = agp->ag_ilen;
1295 agp->ag_skinned = UNCONST(name); /* (NAME_SALLOC not set) */
1296 agp->ag_slen = agp->ag_ilen;
1297 agp->ag_n_flags = NAME_SKINNED;
1298 goto jcheck;
1301 /* Something makes us think we have to perform the skin operation */
1302 nbuf = ac_alloc(agp->ag_ilen + 1);
1303 /*agp->ag_iaddr_start = 0;*/
1304 cp2 = bufend = nbuf;
1305 gotlt = gotaddr = lastsp = 0;
1307 for (cp = name++; (c = *cp++) != '\0'; ) {
1308 switch (c) {
1309 case '(':
1310 cp = skip_comment(cp);
1311 lastsp = 0;
1312 break;
1313 case '"':
1314 /* Start of a "quoted-string".
1315 * Copy it in its entirety */
1316 /* XXX RFC: quotes are "semantically invisible"
1317 * XXX But it was explicitly added (Changelog.Heirloom,
1318 * XXX [9.23] released 11/15/00, "Do not remove quotes
1319 * XXX when skinning names"? No more info.. */
1320 *cp2++ = c;
1321 while ((c = *cp) != '\0') { /* TODO improve */
1322 cp++;
1323 if (c == '"') {
1324 *cp2++ = c;
1325 break;
1327 if (c != '\\')
1328 *cp2++ = c;
1329 else if ((c = *cp) != '\0') {
1330 *cp2++ = c;
1331 cp++;
1334 lastsp = 0;
1335 break;
1336 case ' ':
1337 case '\t':
1338 if (gotaddr == 1) {
1339 gotaddr = 2;
1340 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1342 if (cp[0] == 'a' && cp[1] == 't' && blankchar(cp[2]))
1343 cp += 3, *cp2++ = '@';
1344 else if (cp[0] == '@' && blankchar(cp[1]))
1345 cp += 2, *cp2++ = '@';
1346 else
1347 lastsp = 1;
1348 break;
1349 case '<':
1350 agp->ag_iaddr_start = PTR2SIZE(cp - (name - 1));
1351 cp2 = bufend;
1352 gotlt = gotaddr = 1;
1353 lastsp = 0;
1354 break;
1355 case '>':
1356 if (gotlt) {
1357 /* (_addrspec_check() verifies these later!) */
1358 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1359 gotlt = 0;
1360 while ((c = *cp) != '\0' && c != ',') {
1361 cp++;
1362 if (c == '(')
1363 cp = skip_comment(cp);
1364 else if (c == '"')
1365 while ((c = *cp) != '\0') {
1366 cp++;
1367 if (c == '"')
1368 break;
1369 if (c == '\\' && *cp != '\0')
1370 ++cp;
1373 lastsp = 0;
1374 break;
1376 /* FALLTRHOUGH */
1377 default:
1378 if (lastsp) {
1379 lastsp = 0;
1380 if (gotaddr)
1381 *cp2++ = ' ';
1383 *cp2++ = c;
1384 if (c == ',') {
1385 if (!gotlt) {
1386 *cp2++ = ' ';
1387 for (; blankchar(*cp); ++cp)
1389 lastsp = 0;
1390 bufend = cp2;
1392 } else if (!gotaddr) {
1393 gotaddr = 1;
1394 agp->ag_iaddr_start = PTR2SIZE(cp - name);
1398 agp->ag_slen = PTR2SIZE(cp2 - nbuf);
1399 if (agp->ag_iaddr_aend == 0)
1400 agp->ag_iaddr_aend = agp->ag_ilen;
1402 agp->ag_skinned = savestrbuf(nbuf, agp->ag_slen);
1403 ac_free(nbuf);
1404 agp->ag_n_flags = NAME_NAME_SALLOC | NAME_SKINNED;
1405 jcheck:
1406 rv = _addrspec_check(doskin, agp);
1407 jleave:
1408 NYD_LEAVE;
1409 return rv;
1412 FL char *
1413 realname(char const *name)
1415 char const *cp, *cq, *cstart = NULL, *cend = NULL;
1416 char *rname, *rp;
1417 struct str in, out;
1418 int quoted, good, nogood;
1419 NYD_ENTER;
1421 if ((cp = UNCONST(name)) == NULL)
1422 goto jleave;
1423 for (; *cp != '\0'; ++cp) {
1424 switch (*cp) {
1425 case '(':
1426 if (cstart != NULL) {
1427 /* More than one comment in address, doesn't make sense to display
1428 * it without context. Return the entire field */
1429 cp = mime_fromaddr(name);
1430 goto jleave;
1432 cstart = cp++;
1433 cp = skip_comment(cp);
1434 cend = cp--;
1435 if (cend <= cstart)
1436 cend = cstart = NULL;
1437 break;
1438 case '"':
1439 while (*cp) {
1440 if (*++cp == '"')
1441 break;
1442 if (*cp == '\\' && cp[1])
1443 ++cp;
1445 break;
1446 case '<':
1447 if (cp > name) {
1448 cstart = name;
1449 cend = cp;
1451 break;
1452 case ',':
1453 /* More than one address. Just use the first one */
1454 goto jbrk;
1458 jbrk:
1459 if (cstart == NULL) {
1460 if (*name == '<') {
1461 /* If name contains only a route-addr, the surrounding angle brackets
1462 * don't serve any useful purpose when displaying, so remove */
1463 cp = prstr(skin(name));
1464 } else
1465 cp = mime_fromaddr(name);
1466 goto jleave;
1469 /* Strip quotes. Note that quotes that appear within a MIME encoded word are
1470 * not stripped. The idea is to strip only syntactical relevant things (but
1471 * this is not necessarily the most sensible way in practice) */
1472 rp = rname = ac_alloc(PTR2SIZE(cend - cstart +1));
1473 quoted = 0;
1474 for (cp = cstart; cp < cend; ++cp) {
1475 if (*cp == '(' && !quoted) {
1476 cq = skip_comment(++cp);
1477 if (PTRCMP(--cq, >, cend))
1478 cq = cend;
1479 while (cp < cq) {
1480 if (*cp == '\\' && PTRCMP(cp + 1, <, cq))
1481 ++cp;
1482 *rp++ = *cp++;
1484 } else if (*cp == '\\' && PTRCMP(cp + 1, <, cend))
1485 *rp++ = *++cp;
1486 else if (*cp == '"') {
1487 quoted = !quoted;
1488 continue;
1489 } else
1490 *rp++ = *cp;
1492 *rp = '\0';
1493 in.s = rname;
1494 in.l = rp - rname;
1495 mime_fromhdr(&in, &out, TD_ISPR | TD_ICONV);
1496 ac_free(rname);
1497 rname = savestr(out.s);
1498 free(out.s);
1500 while (blankchar(*rname))
1501 ++rname;
1502 for (rp = rname; *rp != '\0'; ++rp)
1504 while (PTRCMP(--rp, >=, rname) && blankchar(*rp))
1505 *rp = '\0';
1506 if (rp == rname) {
1507 cp = mime_fromaddr(name);
1508 goto jleave;
1511 /* mime_fromhdr() has converted all nonprintable characters to question
1512 * marks now. These and blanks are considered uninteresting; if the
1513 * displayed part of the real name contains more than 25% of them, it is
1514 * probably better to display the plain email address instead */
1515 good = 0;
1516 nogood = 0;
1517 for (rp = rname; *rp != '\0' && PTRCMP(rp, <, rname + 20); ++rp)
1518 if (*rp == '?' || blankchar(*rp))
1519 ++nogood;
1520 else
1521 ++good;
1522 cp = (good * 3 < nogood) ? prstr(skin(name)) : rname;
1523 jleave:
1524 NYD_LEAVE;
1525 return UNCONST(cp);
1528 FL char *
1529 name1(struct message *mp, int reptype)
1531 char *namebuf, *cp, *cp2, *linebuf = NULL /* TODO line pool */;
1532 size_t namesize, linesize = 0;
1533 FILE *ibuf;
1534 int f1st = 1;
1535 NYD_ENTER;
1537 if ((cp = hfield1("from", mp)) != NULL && *cp != '\0')
1538 goto jleave;
1539 if (reptype == 0 && (cp = hfield1("sender", mp)) != NULL && *cp != '\0')
1540 goto jleave;
1542 namebuf = smalloc(namesize = 1);
1543 namebuf[0] = 0;
1544 if (mp->m_flag & MNOFROM)
1545 goto jout;
1546 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
1547 goto jout;
1548 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1549 goto jout;
1551 jnewname:
1552 if (namesize <= linesize)
1553 namebuf = srealloc(namebuf, namesize = linesize +1);
1554 for (cp = linebuf; *cp != '\0' && *cp != ' '; ++cp)
1556 for (; blankchar(*cp); ++cp)
1558 for (cp2 = namebuf + strlen(namebuf);
1559 *cp && !blankchar(*cp) && PTRCMP(cp2, <, namebuf + namesize -1);)
1560 *cp2++ = *cp++;
1561 *cp2 = '\0';
1563 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1564 goto jout;
1565 if ((cp = strchr(linebuf, 'F')) == NULL)
1566 goto jout;
1567 if (strncmp(cp, "From", 4)) /* XXX is_head? */
1568 goto jout;
1569 if (namesize <= linesize)
1570 namebuf = srealloc(namebuf, namesize = linesize + 1);
1572 while ((cp = strchr(cp, 'r')) != NULL) {
1573 if (!strncmp(cp, "remote", 6)) {
1574 if ((cp = strchr(cp, 'f')) == NULL)
1575 break;
1576 if (strncmp(cp, "from", 4) != 0)
1577 break;
1578 if ((cp = strchr(cp, ' ')) == NULL)
1579 break;
1580 cp++;
1581 if (f1st) {
1582 strncpy(namebuf, cp, namesize);
1583 f1st = 0;
1584 } else {
1585 cp2 = strrchr(namebuf, '!') + 1;
1586 strncpy(cp2, cp, PTR2SIZE(namebuf + namesize - cp2));
1588 namebuf[namesize - 2] = '!';
1589 namebuf[namesize - 1] = '\0';
1590 goto jnewname;
1592 cp++;
1594 jout:
1595 if (*namebuf != '\0' || ((cp = hfield1("return-path", mp))) == NULL ||
1596 *cp == '\0')
1597 cp = savestr(namebuf);
1599 if (linebuf != NULL)
1600 free(linebuf);
1601 free(namebuf);
1602 jleave:
1603 NYD_LEAVE;
1604 return cp;
1607 FL char *
1608 subject_re_trim(char *s)
1610 struct {
1611 ui8_t len;
1612 char dat[7];
1613 } const *pp, ignored[] = { /* Update *reply-strings* manual upon change! */
1614 { 3, "re:" },
1615 { 3, "aw:" }, { 5, "antw:" }, /* de */
1616 { 0, "" }
1619 bool_t any = FAL0;
1620 char *orig_s = s, *re_st = NULL, *re_st_x;
1621 size_t re_l = 0 /* pacify CC */;
1622 NYD_ENTER;
1624 if ((re_st_x = ok_vlook(reply_strings)) != NULL &&
1625 (re_l = strlen(re_st_x)) > 0) {
1626 re_st = ac_alloc(++re_l * 2);
1627 memcpy(re_st, re_st_x, re_l);
1630 jouter:
1631 while (*s != '\0') {
1632 while (spacechar(*s))
1633 ++s;
1635 for (pp = ignored; pp->len > 0; ++pp)
1636 if (is_asccaseprefix(s, pp->dat)) {
1637 s += pp->len;
1638 any = TRU1;
1639 goto jouter;
1642 if (re_st != NULL) {
1643 char *cp;
1645 memcpy(re_st_x = re_st + re_l, re_st, re_l);
1646 while ((cp = n_strsep(&re_st_x, ',', TRU1)) != NULL)
1647 if (is_asccaseprefix(s, cp)) {
1648 s += strlen(cp);
1649 any = TRU1;
1650 goto jouter;
1653 break;
1656 if (re_st != NULL)
1657 ac_free(re_st);
1658 NYD_LEAVE;
1659 return any ? s : orig_s;
1662 FL int
1663 msgidcmp(char const *s1, char const *s2)
1665 int q1 = 0, q2 = 0, c1, c2;
1666 NYD_ENTER;
1668 do {
1669 c1 = msgidnextc(&s1, &q1);
1670 c2 = msgidnextc(&s2, &q2);
1671 if (c1 != c2)
1672 break;
1673 } while (c1 && c2);
1674 NYD_LEAVE;
1675 return c1 - c2;
1678 FL char const *
1679 fakefrom(struct message *mp)
1681 char const *name;
1682 NYD_ENTER;
1684 if (((name = skin(hfield1("return-path", mp))) == NULL || *name == '\0' ) &&
1685 ((name = skin(hfield1("from", mp))) == NULL || *name == '\0'))
1686 /* XXX MAILER-DAEMON is what an old MBOX manual page says.
1687 * RFC 4155 however requires a RFC 5322 (2822) conforming
1688 * "addr-spec", but we simply can't provide that */
1689 name = "MAILER-DAEMON";
1690 NYD_LEAVE;
1691 return name;
1694 FL char const *
1695 fakedate(time_t t)
1697 char *cp, *cq;
1698 NYD_ENTER;
1700 cp = ctime(&t);
1701 for (cq = cp; *cq != '\0' && *cq != '\n'; ++cq)
1703 *cq = '\0';
1704 cp = savestr(cp);
1705 NYD_LEAVE;
1706 return cp;
1709 #ifdef HAVE_IMAP_SEARCH
1710 FL time_t
1711 unixtime(char const *fromline)
1713 char const *fp;
1714 char *xp;
1715 time_t t;
1716 int i, year, month, day, hour, minute, second, tzdiff;
1717 struct tm *tmptr;
1718 NYD2_ENTER;
1720 for (fp = fromline; *fp != '\0' && *fp != '\n'; ++fp)
1722 fp -= 24;
1723 if (PTR2SIZE(fp - fromline) < 7)
1724 goto jinvalid;
1725 if (fp[3] != ' ')
1726 goto jinvalid;
1727 for (i = 0;;) {
1728 if (!strncmp(fp + 4, month_names[i], 3))
1729 break;
1730 if (month_names[++i][0] == '\0')
1731 goto jinvalid;
1733 month = i + 1;
1734 if (fp[7] != ' ')
1735 goto jinvalid;
1736 day = strtol(fp + 8, &xp, 10);
1737 if (*xp != ' ' || xp != fp + 10)
1738 goto jinvalid;
1739 hour = strtol(fp + 11, &xp, 10);
1740 if (*xp != ':' || xp != fp + 13)
1741 goto jinvalid;
1742 minute = strtol(fp + 14, &xp, 10);
1743 if (*xp != ':' || xp != fp + 16)
1744 goto jinvalid;
1745 second = strtol(fp + 17, &xp, 10);
1746 if (*xp != ' ' || xp != fp + 19)
1747 goto jinvalid;
1748 year = strtol(fp + 20, &xp, 10);
1749 if (xp != fp + 24)
1750 goto jinvalid;
1751 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
1752 goto jinvalid;
1753 tzdiff = t - mktime(gmtime(&t));
1754 tmptr = localtime(&t);
1755 if (tmptr->tm_isdst > 0)
1756 tzdiff += 3600;
1757 t -= tzdiff;
1758 jleave:
1759 NYD2_LEAVE;
1760 return t;
1761 jinvalid:
1762 t = n_time_epoch();
1763 goto jleave;
1765 #endif /* HAVE_IMAP_SEARCH */
1767 FL time_t
1768 rfctime(char const *date)
1770 char const *cp = date;
1771 char *x;
1772 time_t t;
1773 int i, year, month, day, hour, minute, second;
1774 NYD2_ENTER;
1776 if ((cp = nexttoken(cp)) == NULL)
1777 goto jinvalid;
1778 if (alphachar(cp[0]) && alphachar(cp[1]) && alphachar(cp[2]) &&
1779 cp[3] == ',') {
1780 if ((cp = nexttoken(&cp[4])) == NULL)
1781 goto jinvalid;
1783 day = strtol(cp, &x, 10); /* XXX strtol */
1784 if ((cp = nexttoken(x)) == NULL)
1785 goto jinvalid;
1786 for (i = 0;;) {
1787 if (!strncmp(cp, month_names[i], 3))
1788 break;
1789 if (month_names[++i][0] == '\0')
1790 goto jinvalid;
1792 month = i + 1;
1793 if ((cp = nexttoken(&cp[3])) == NULL)
1794 goto jinvalid;
1795 /* RFC 5322, 4.3:
1796 * Where a two or three digit year occurs in a date, the year is to be
1797 * interpreted as follows: If a two digit year is encountered whose
1798 * value is between 00 and 49, the year is interpreted by adding 2000,
1799 * ending up with a value between 2000 and 2049. If a two digit year
1800 * is encountered with a value between 50 and 99, or any three digit
1801 * year is encountered, the year is interpreted by adding 1900 */
1802 year = strtol(cp, &x, 10); /* XXX strtol */
1803 i = (int)PTR2SIZE(x - cp);
1804 if (i == 2 && year >= 0 && year <= 49)
1805 year += 2000;
1806 else if (i == 3 || (i == 2 && year >= 50 && year <= 99))
1807 year += 1900;
1808 if ((cp = nexttoken(x)) == NULL)
1809 goto jinvalid;
1810 hour = strtol(cp, &x, 10); /* XXX strtol */
1811 if (*x != ':')
1812 goto jinvalid;
1813 cp = &x[1];
1814 minute = strtol(cp, &x, 10);
1815 if (*x == ':') {
1816 cp = x + 1;
1817 second = strtol(cp, &x, 10);
1818 } else
1819 second = 0;
1821 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
1822 goto jinvalid;
1823 if ((cp = nexttoken(x)) != NULL) {
1824 char buf[3];
1825 int sign = 1;
1827 switch (*cp) {
1828 case '+':
1829 sign = -1;
1830 /* FALLTHRU */
1831 case '-':
1832 ++cp;
1833 break;
1835 if (digitchar(cp[0]) && digitchar(cp[1]) && digitchar(cp[2]) &&
1836 digitchar(cp[3])) {
1837 long tadj;
1838 buf[2] = '\0';
1839 buf[0] = cp[0];
1840 buf[1] = cp[1];
1841 tadj = strtol(buf, NULL, 10) * 3600;/*XXX strtrol*/
1842 buf[0] = cp[2];
1843 buf[1] = cp[3];
1844 tadj += strtol(buf, NULL, 10) * 60; /* XXX strtol*/
1845 if (sign < 0)
1846 tadj = -tadj;
1847 t += tadj;
1849 /* TODO WE DO NOT YET PARSE (OBSOLETE) ZONE NAMES
1850 * TODO once again, Christos Zoulas and NetBSD Mail have done
1851 * TODO a really good job already, but using strptime(3), which
1852 * TODO is not portable. Nonetheless, WE must improve, not
1853 * TODO at last because we simply ignore obsolete timezones!!
1854 * TODO See RFC 5322, 4.3! */
1856 jleave:
1857 NYD2_LEAVE;
1858 return t;
1859 jinvalid:
1860 t = 0;
1861 goto jleave;
1864 #define is_leapyear(Y) ((((Y) % 100 ? (Y) : (Y) / 100) & 3) == 0)
1866 FL time_t
1867 combinetime(int year, int month, int day, int hour, int minute, int second)
1869 time_t t;
1870 NYD2_ENTER;
1872 if (second < 0 || minute < 0 || hour < 0 || day < 1) {
1873 t = (time_t)-1;
1874 goto jleave;
1877 t = second + minute * 60 + hour * 3600 + (day - 1) * 86400;
1878 if (month > 1)
1879 t += 86400 * 31;
1880 if (month > 2)
1881 t += 86400 * (is_leapyear(year) ? 29 : 28);
1882 if (month > 3)
1883 t += 86400 * 31;
1884 if (month > 4)
1885 t += 86400 * 30;
1886 if (month > 5)
1887 t += 86400 * 31;
1888 if (month > 6)
1889 t += 86400 * 30;
1890 if (month > 7)
1891 t += 86400 * 31;
1892 if (month > 8)
1893 t += 86400 * 31;
1894 if (month > 9)
1895 t += 86400 * 30;
1896 if (month > 10)
1897 t += 86400 * 31;
1898 if (month > 11)
1899 t += 86400 * 30;
1900 year -= 1900;
1901 t += (year - 70) * 31536000 + ((year - 69) / 4) * 86400 -
1902 ((year - 1) / 100) * 86400 + ((year + 299) / 400) * 86400;
1903 jleave:
1904 NYD2_LEAVE;
1905 return t;
1908 FL void
1909 substdate(struct message *m)
1911 char const *cp;
1912 NYD_ENTER;
1914 /* Determine the date to print in faked 'From ' lines. This is traditionally
1915 * the date the message was written to the mail file. Try to determine this
1916 * using RFC message header fields, or fall back to current time */
1917 if ((cp = hfield1("received", m)) != NULL) {
1918 while ((cp = nexttoken(cp)) != NULL && *cp != ';') {
1920 ++cp;
1921 while (alnumchar(*cp));
1923 if (cp && *++cp)
1924 m->m_time = rfctime(cp);
1926 if (m->m_time == 0 || m->m_time > time_current.tc_time) {
1927 if ((cp = hfield1("date", m)) != NULL)
1928 m->m_time = rfctime(cp);
1930 if (m->m_time == 0 || m->m_time > time_current.tc_time)
1931 m->m_time = time_current.tc_time;
1932 NYD_LEAVE;
1935 FL void
1936 setup_from_and_sender(struct header *hp)
1938 char const *addr;
1939 struct name *np;
1940 NYD_ENTER;
1942 /* If -t parsed or composed From: then take it. With -t we otherwise
1943 * want -r to be honoured in favour of *from* in order to have
1944 * a behaviour that is compatible with what users would expect from e.g.
1945 * postfix(1) */
1946 if ((np = hp->h_from) != NULL ||
1947 ((pstate & PS_t_FLAG) && (np = option_r_arg) != NULL)) {
1949 } else if ((addr = myaddrs(hp)) != NULL)
1950 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
1951 hp->h_from = np;
1953 if ((np = hp->h_sender) != NULL) {
1955 } else if ((addr = ok_vlook(sender)) != NULL)
1956 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
1957 hp->h_sender = np;
1959 NYD_LEAVE;
1962 FL struct name const *
1963 check_from_and_sender(struct name const *fromfield,
1964 struct name const *senderfield)
1966 struct name const *rv = NULL;
1967 NYD_ENTER;
1969 if (senderfield != NULL) {
1970 if (senderfield->n_flink != NULL) {
1971 n_err(_("The Sender: field may contain only one address\n"));
1972 goto jleave;
1974 rv = senderfield;
1977 if (fromfield != NULL) {
1978 if (fromfield->n_flink != NULL && senderfield == NULL) {
1979 n_err(_("A Sender: is required when there are multiple "
1980 "addresses in From:\n"));
1981 goto jleave;
1983 if (rv == NULL)
1984 rv = fromfield;
1987 if (rv == NULL)
1988 rv = (struct name*)0x1;
1989 jleave:
1990 NYD_LEAVE;
1991 return rv;
1994 #ifdef HAVE_OPENSSL
1995 FL char *
1996 getsender(struct message *mp)
1998 char *cp;
1999 struct name *np;
2000 NYD_ENTER;
2002 if ((cp = hfield1("from", mp)) == NULL ||
2003 (np = lextract(cp, GEXTRA | GSKIN)) == NULL)
2004 cp = NULL;
2005 else
2006 cp = (np->n_flink != NULL) ? skin(hfield1("sender", mp)) : np->n_name;
2007 NYD_LEAVE;
2008 return cp;
2010 #endif
2012 FL int
2013 grab_headers(enum n_lexinput_flags lif, struct header *hp, enum gfield gflags,
2014 int subjfirst)
2016 /* TODO grab_headers: again, check counts etc. against RFC;
2017 * TODO (now assumes check_from_and_sender() is called afterwards ++ */
2018 int errs;
2019 int volatile comma;
2020 NYD_ENTER;
2022 errs = 0;
2023 comma = (ok_blook(bsdcompat) || ok_blook(bsdmsgs)) ? 0 : GCOMMA;
2025 if (gflags & GTO)
2026 hp->h_to = grab_names(lif, "To: ", hp->h_to, comma, GTO | GFULL);
2027 if (subjfirst && (gflags & GSUBJECT))
2028 hp->h_subject = n_lex_input_cp(lif, "Subject: ", hp->h_subject);
2029 if (gflags & GCC)
2030 hp->h_cc = grab_names(lif, "Cc: ", hp->h_cc, comma, GCC | GFULL);
2031 if (gflags & GBCC)
2032 hp->h_bcc = grab_names(lif, "Bcc: ", hp->h_bcc, comma, GBCC | GFULL);
2034 if (gflags & GEXTRA) {
2035 if (hp->h_from == NULL)
2036 hp->h_from = lextract(myaddrs(hp), GEXTRA | GFULL | GFULLEXTRA);
2037 hp->h_from = grab_names(lif, "From: ", hp->h_from, comma,
2038 GEXTRA | GFULL | GFULLEXTRA);
2039 if (hp->h_replyto == NULL)
2040 hp->h_replyto = lextract(ok_vlook(replyto), GEXTRA | GFULL);
2041 hp->h_replyto = grab_names(lif, "Reply-To: ", hp->h_replyto, comma,
2042 GEXTRA | GFULL);
2043 if (hp->h_sender == NULL)
2044 hp->h_sender = extract(ok_vlook(sender), GEXTRA | GFULL);
2045 hp->h_sender = grab_names(lif, "Sender: ", hp->h_sender, comma,
2046 GEXTRA | GFULL);
2049 if (!subjfirst && (gflags & GSUBJECT))
2050 hp->h_subject = n_lex_input_cp(lif, "Subject: ", hp->h_subject);
2052 NYD_LEAVE;
2053 return errs;
2056 FL bool_t
2057 header_match(struct message *mp, struct search_expr const *sep)
2059 struct str in, out;
2060 FILE *ibuf;
2061 int lc;
2062 size_t linesize = 0; /* TODO line pool */
2063 char *linebuf = NULL, *colon;
2064 bool_t rv = FAL0;
2065 NYD_ENTER;
2067 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2068 goto jleave;
2069 if ((lc = mp->m_lines - 1) < 0)
2070 goto jleave;
2072 if ((mp->m_flag & MNOFROM) == 0 &&
2073 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2074 goto jleave;
2075 while (lc > 0) {
2076 if (gethfield(ibuf, &linebuf, &linesize, lc, &colon) <= 0)
2077 break;
2078 if (blankchar(*++colon))
2079 ++colon;
2080 in.l = strlen(in.s = colon);
2081 mime_fromhdr(&in, &out, TD_ICONV);
2082 #ifdef HAVE_REGEX
2083 if (sep->ss_sexpr == NULL)
2084 rv = (regexec(&sep->ss_regex, out.s, 0,NULL, 0) != REG_NOMATCH);
2085 else
2086 #endif
2087 rv = substr(out.s, sep->ss_sexpr);
2088 free(out.s);
2089 if (rv)
2090 break;
2093 jleave:
2094 if (linebuf != NULL)
2095 free(linebuf);
2096 NYD_LEAVE;
2097 return rv;
2100 /* s-it-mode */