`mbox' can only be used in a system mailbox (for now)
[s-mailx.git] / head.c
blob3caedf1b466235a09ef61e3dff2f73341deae008
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 - 2015 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
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 wether 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 *rv;
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(smtp) != NULL || ok_vlook(hostname) != NULL) {
622 char *hn = nodename(1);
623 size_t sz = strlen(myname) + strlen(hn) + 1 +1;
624 rv = salloc(sz);
625 sstpcpy(sstpcpy(sstpcpy(rv, myname), "@"), hn);
627 jleave:
628 NYD_LEAVE;
629 return rv;
632 FL char const *
633 myorigin(struct header *hp)
635 char const *rv = NULL, *ccp;
636 struct name *np;
637 NYD_ENTER;
639 if ((ccp = myaddrs(hp)) != NULL &&
640 (np = lextract(ccp, GEXTRA | GFULL)) != NULL)
641 rv = (np->n_flink != NULL) ? ok_vlook(sender) : ccp;
642 NYD_LEAVE;
643 return rv;
646 FL int
647 is_head(char const *linebuf, size_t linelen, bool_t compat)
649 char date[FROM_DATEBUF];
650 int rv;
651 NYD2_ENTER;
653 if ((rv = (linelen >= 5 && !strncmp(linebuf, "From ", 5))) &&
654 (!compat || ok_blook(mbox_rfc4155)))
655 rv = (extract_date_from_from_(linebuf, linelen, date) && _is_date(date));
656 NYD2_LEAVE;
657 return rv;
660 FL int
661 extract_date_from_from_(char const *line, size_t linelen,
662 char datebuf[FROM_DATEBUF])
664 int rv = 0;
665 char const *cp = line;
666 NYD_ENTER;
668 /* "From " */
669 cp = _from__skipword(cp);
670 if (cp == NULL)
671 goto jerr;
672 /* "addr-spec " */
673 cp = _from__skipword(cp);
674 if (cp == NULL)
675 goto jerr;
676 if (cp[0] == 't' && cp[1] == 't' && cp[2] == 'y') {
677 cp = _from__skipword(cp);
678 if (cp == NULL)
679 goto jerr;
682 linelen -= PTR2SIZE(cp - line);
683 if (linelen < _DATE_MINLEN)
684 goto jerr;
685 if (cp[linelen - 1] == '\n') {
686 --linelen;
687 /* (Rather IMAP/POP3 only) */
688 if (cp[linelen - 1] == '\r')
689 --linelen;
690 if (linelen < _DATE_MINLEN)
691 goto jerr;
693 if (linelen >= FROM_DATEBUF)
694 goto jerr;
696 rv = 1;
697 jleave:
698 memcpy(datebuf, cp, linelen);
699 datebuf[linelen] = '\0';
700 NYD_LEAVE;
701 return rv;
702 jerr:
703 cp = _("<Unknown date>");
704 linelen = strlen(cp);
705 if (linelen >= FROM_DATEBUF)
706 linelen = FROM_DATEBUF;
707 goto jleave;
710 FL void
711 extract_header(FILE *fp, struct header *hp, si8_t *checkaddr_err)
713 struct header nh, *hq = &nh;
714 char *linebuf = NULL /* TODO line pool */, *colon;
715 size_t linesize = 0, seenfields = 0;
716 int lc, c;
717 char const *val, *cp;
718 NYD_ENTER;
720 memset(hq, 0, sizeof *hq);
721 if ((pstate & PS_t_FLAG) && (options & OPT_t_FLAG)) {
722 hq->h_to = hp->h_to;
723 hq->h_cc = hp->h_cc;
724 hq->h_bcc = hp->h_bcc;
727 for (lc = 0; readline_restart(fp, &linebuf, &linesize, 0) > 0; ++lc)
730 /* TODO yippieia, cat(check(lextract)) :-) */
731 rewind(fp);
732 while ((lc = gethfield(fp, &linebuf, &linesize, lc, &colon)) >= 0) {
733 struct name *np;
735 /* We explicitly allow EAF_NAME for some addressees since aliases are not
736 * yet expanded when we parse these! */
737 if ((val = thisfield(linebuf, "to")) != NULL) {
738 ++seenfields;
739 hq->h_to = cat(hq->h_to, checkaddrs(lextract(val, GTO | GFULL),
740 EACM_NORMAL | EAF_NAME, checkaddr_err));
741 } else if ((val = thisfield(linebuf, "cc")) != NULL) {
742 ++seenfields;
743 hq->h_cc = cat(hq->h_cc, checkaddrs(lextract(val, GCC | GFULL),
744 EACM_NORMAL | EAF_NAME, checkaddr_err));
745 } else if ((val = thisfield(linebuf, "bcc")) != NULL) {
746 ++seenfields;
747 hq->h_bcc = cat(hq->h_bcc, checkaddrs(lextract(val, GBCC | GFULL),
748 EACM_NORMAL | EAF_NAME, checkaddr_err));
749 } else if ((val = thisfield(linebuf, "from")) != NULL) {
750 if (!(pstate & PS_t_FLAG) || (options & OPT_t_FLAG)) {
751 ++seenfields;
752 hq->h_from = cat(hq->h_from,
753 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
754 EACM_STRICT, NULL));
756 } else if ((val = thisfield(linebuf, "reply-to")) != NULL) {
757 ++seenfields;
758 hq->h_replyto = cat(hq->h_replyto,
759 checkaddrs(lextract(val, GEXTRA | GFULL), EACM_STRICT, NULL));
760 } else if ((val = thisfield(linebuf, "sender")) != NULL) {
761 if (!(pstate & PS_t_FLAG) || (options & OPT_t_FLAG)) {
762 ++seenfields;
763 hq->h_sender = cat(hq->h_sender, /* TODO cat? check! */
764 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
765 EACM_STRICT, NULL));
767 } else if ((val = thisfield(linebuf, "organization")) != NULL) {
768 ++seenfields;
769 for (cp = val; blankchar(*cp); ++cp)
771 hq->h_organization = (hq->h_organization != NULL)
772 ? save2str(hq->h_organization, cp) : savestr(cp);
773 } else if ((val = thisfield(linebuf, "subject")) != NULL ||
774 (val = thisfield(linebuf, "subj")) != NULL) {
775 ++seenfields;
776 for (cp = val; blankchar(*cp); ++cp)
778 hq->h_subject = (hq->h_subject != NULL)
779 ? save2str(hq->h_subject, cp) : savestr(cp);
781 /* The remaining are mostly hacked in and thus TODO -- at least in
782 * TODO respect to their content checking */
783 else if ((pstate & PS_t_FLAG) &&
784 (val = thisfield(linebuf, "message-id")) != NULL) {
785 np = checkaddrs(lextract(val, GREF),
786 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
787 NULL);
788 if (np == NULL || np->n_flink != NULL)
789 goto jebadhead;
790 ++seenfields;
791 hq->h_message_id = np;
792 } else if ((pstate & PS_t_FLAG) &&
793 (val = thisfield(linebuf, "in-reply-to")) != NULL) {
794 np = checkaddrs(lextract(val, GREF),
795 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
796 NULL);
797 if (np == NULL || np->n_flink != NULL)
798 goto jebadhead;
799 ++seenfields;
800 hq->h_in_reply_to = np;
801 } else if ((pstate & PS_t_FLAG) &&
802 (val = thisfield(linebuf, "references")) != NULL) {
803 ++seenfields;
804 /* TODO Limit number of references TODO better on parser side */
805 hq->h_ref = cat(hq->h_ref, checkaddrs(extract(val, GREF),
806 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
807 NULL));
808 /* and that is very hairy */
809 } else if ((pstate & PS_t_FLAG) &&
810 (val = thisfield(linebuf, "mail-followup-to")) != NULL) {
811 ++seenfields;
812 hq->h_mft = cat(hq->h_mft, checkaddrs(lextract(val, GEXTRA | GFULL),
813 /*EACM_STRICT | TODO '/' valid!! | EACM_NOLOG | */ EACM_NONAME,
814 checkaddr_err));
815 } else
816 jebadhead:
817 n_err(_("Ignoring header field \"%s\"\n"), linebuf);
820 /* In case the blank line after the header has been edited out. Otherwise,
821 * fetch the header separator */
822 if (linebuf != NULL) {
823 if (linebuf[0] != '\0') {
824 for (cp = linebuf; *(++cp) != '\0';)
826 fseek(fp, (long)-PTR2SIZE(1 + cp - linebuf), SEEK_CUR);
827 } else {
828 if ((c = getc(fp)) != '\n' && c != EOF)
829 ungetc(c, fp);
833 if (seenfields > 0) {
834 hp->h_to = hq->h_to;
835 hp->h_cc = hq->h_cc;
836 hp->h_bcc = hq->h_bcc;
837 hp->h_from = hq->h_from;
838 hp->h_replyto = hq->h_replyto;
839 hp->h_sender = hq->h_sender;
840 hp->h_organization = hq->h_organization;
841 if (hq->h_subject != NULL || !(pstate & PS_t_FLAG) ||
842 !(options & OPT_t_FLAG))
843 hp->h_subject = hq->h_subject;
845 if (pstate & PS_t_FLAG) {
846 hp->h_ref = hq->h_ref;
847 hp->h_message_id = hq->h_message_id;
848 hp->h_in_reply_to = hq->h_in_reply_to;
849 hp->h_mft = hq->h_mft;
851 /* And perform additional validity checks so that we don't bail later
852 * on TODO this is good and the place where this should occur,
853 * TODO unfortunately a lot of other places do again and blabla */
854 if (pstate & PS_t_FLAG) {
855 if (hp->h_from == NULL)
856 hp->h_from = option_r_arg;
857 else if (hp->h_from->n_flink != NULL && hp->h_sender == NULL)
858 hp->h_sender = lextract(ok_vlook(sender),
859 GEXTRA | GFULL | GFULLEXTRA);
862 } else
863 n_err(_("Restoring deleted header lines\n"));
865 if (linebuf != NULL)
866 free(linebuf);
867 NYD_LEAVE;
870 FL char *
871 hfield_mult(char const *field, struct message *mp, int mult)
873 FILE *ibuf;
874 int lc;
875 struct str hfs;
876 size_t linesize = 0; /* TODO line pool */
877 char *linebuf = NULL, *colon;
878 char const *hfield;
879 NYD_ENTER;
881 /* There are (spam) messages which have header bytes which are many KB when
882 * joined, so resize a single heap storage until we are done if we shall
883 * collect a field that may have multiple bodies; only otherwise use the
884 * string dope directly */
885 memset(&hfs, 0, sizeof hfs);
887 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
888 goto jleave;
889 if ((lc = mp->m_lines - 1) < 0)
890 goto jleave;
892 if ((mp->m_flag & MNOFROM) == 0 &&
893 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
894 goto jleave;
895 while (lc > 0) {
896 if ((lc = gethfield(ibuf, &linebuf, &linesize, lc, &colon)) < 0)
897 break;
898 if ((hfield = thisfield(linebuf, field)) != NULL && *hfield != '\0') {
899 if (mult)
900 n_str_add_buf(&hfs, hfield, strlen(hfield));
901 else {
902 hfs.s = savestr(hfield);
903 break;
908 jleave:
909 if (linebuf != NULL)
910 free(linebuf);
911 if (mult && hfs.s != NULL) {
912 colon = savestrbuf(hfs.s, hfs.l);
913 free(hfs.s);
914 hfs.s = colon;
916 NYD_LEAVE;
917 return hfs.s;
920 FL char const *
921 thisfield(char const *linebuf, char const *field)
923 char const *rv = NULL;
924 NYD2_ENTER;
926 while (lowerconv(*linebuf) == lowerconv(*field)) {
927 ++linebuf;
928 ++field;
930 if (*field != '\0')
931 goto jleave;
933 while (blankchar(*linebuf))
934 ++linebuf;
935 if (*linebuf++ != ':')
936 goto jleave;
938 while (blankchar(*linebuf)) /* TODO header parser.. strip trailing WS?!? */
939 ++linebuf;
940 rv = linebuf;
941 jleave:
942 NYD2_LEAVE;
943 return rv;
946 FL char *
947 nameof(struct message *mp, int reptype)
949 char *cp, *cp2;
950 NYD_ENTER;
952 cp = skin(name1(mp, reptype));
953 if (reptype != 0 || charcount(cp, '!') < 2)
954 goto jleave;
955 cp2 = strrchr(cp, '!');
956 --cp2;
957 while (cp2 > cp && *cp2 != '!')
958 --cp2;
959 if (*cp2 == '!')
960 cp = cp2 + 1;
961 jleave:
962 NYD_LEAVE;
963 return cp;
966 FL char const *
967 skip_comment(char const *cp)
969 size_t nesting;
970 NYD_ENTER;
972 for (nesting = 1; nesting > 0 && *cp; ++cp) {
973 switch (*cp) {
974 case '\\':
975 if (cp[1])
976 ++cp;
977 break;
978 case '(':
979 ++nesting;
980 break;
981 case ')':
982 --nesting;
983 break;
986 NYD_LEAVE;
987 return cp;
990 FL char const *
991 routeaddr(char const *name)
993 char const *np, *rp = NULL;
994 NYD_ENTER;
996 for (np = name; *np; np++) {
997 switch (*np) {
998 case '(':
999 np = skip_comment(np + 1) - 1;
1000 break;
1001 case '"':
1002 while (*np) {
1003 if (*++np == '"')
1004 break;
1005 if (*np == '\\' && np[1])
1006 np++;
1008 break;
1009 case '<':
1010 rp = np;
1011 break;
1012 case '>':
1013 goto jleave;
1016 rp = NULL;
1017 jleave:
1018 NYD_LEAVE;
1019 return rp;
1022 FL enum expand_addr_flags
1023 expandaddr_to_eaf(void)
1025 struct eafdesc {
1026 char const *eafd_name;
1027 bool_t eafd_is_target;
1028 ui8_t eafd_andoff;
1029 ui8_t eafd_or;
1030 } const eafa[] = {
1031 {"restrict", FAL0, EAF_TARGET_MASK, EAF_RESTRICT | EAF_RESTRICT_TARGETS},
1032 {"fail", FAL0, EAF_NONE, EAF_FAIL},
1033 {"all", TRU1, EAF_NONE, EAF_TARGET_MASK},
1034 {"file", TRU1, EAF_NONE, EAF_FILE},
1035 {"pipe", TRU1, EAF_NONE, EAF_PIPE},
1036 {"name", TRU1, EAF_NONE, EAF_NAME},
1037 {"addr", TRU1, EAF_NONE, EAF_ADDR}
1038 }, *eafp;
1040 char *buf;
1041 enum expand_addr_flags rv;
1042 char const *cp;
1043 NYD2_ENTER;
1045 if ((cp = ok_vlook(expandaddr)) == NULL)
1046 rv = EAF_RESTRICT_TARGETS;
1047 else if (*cp == '\0')
1048 rv = EAF_TARGET_MASK;
1049 else {
1050 rv = EAF_TARGET_MASK;
1052 for (buf = savestr(cp); (cp = n_strsep(&buf, ',', TRU1)) != NULL;) {
1053 bool_t minus;
1055 if ((minus = (*cp == '-')) || *cp == '+')
1056 ++cp;
1057 for (eafp = eafa;; ++eafp) {
1058 if (eafp == eafa + NELEM(eafa)) {
1059 if (options & OPT_D_V)
1060 n_err(_("Unknown *expandaddr* value: \"%s\"\n"), cp);
1061 break;
1062 } else if (!asccasecmp(cp, eafp->eafd_name)) {
1063 if (!minus) {
1064 rv &= ~eafp->eafd_andoff;
1065 rv |= eafp->eafd_or;
1066 } else {
1067 if (eafp->eafd_is_target)
1068 rv &= ~eafp->eafd_or;
1069 else if (options & OPT_D_V)
1070 n_err(_("\"-\" prefix invalid for *expandaddr* value: "
1071 "\"%s\"\n"), --cp);
1073 break;
1074 } else if (!asccasecmp(cp, "noalias")) { /* TODO v15 OBSOLETE */
1075 OBSOLETE(_("*expandaddr*: \"noalias\" is henceforth \"-name\""));
1076 rv &= ~EAF_NAME;
1077 break;
1082 if ((rv & EAF_RESTRICT) && (options & (OPT_INTERACTIVE | OPT_TILDE_FLAG)))
1083 rv |= EAF_TARGET_MASK;
1084 else if (options & OPT_D_V) {
1085 if (!(rv & EAF_TARGET_MASK))
1086 n_err(_("*expandaddr* doesn't allow any addresses\n"));
1087 else if ((rv & EAF_FAIL) && (rv & EAF_TARGET_MASK) == EAF_TARGET_MASK)
1088 n_err(_("*expandaddr* with \"fail\" but no restrictions\n"));
1091 NYD2_LEAVE;
1092 return rv;
1095 FL si8_t
1096 is_addr_invalid(struct name *np, enum expand_addr_check_mode eacm)
1098 char cbuf[sizeof "'\\U12340'"];
1099 enum expand_addr_flags eaf;
1100 char const *cs;
1101 int f;
1102 si8_t rv;
1103 NYD_ENTER;
1105 f = np->n_flags;
1107 if ((rv = ((f & NAME_ADDRSPEC_INVALID) != 0))) {
1108 if ((eacm & EACM_NOLOG) || (f & NAME_ADDRSPEC_ERR_EMPTY)) {
1110 } else {
1111 ui32_t c;
1112 char const *fmt = "'\\x%02X'";
1113 bool_t ok8bit = TRU1;
1115 if (f & NAME_ADDRSPEC_ERR_IDNA) {
1116 cs = _("Invalid domain name: \"%s\", character %s\n");
1117 fmt = "'\\U%04X'";
1118 ok8bit = FAL0;
1119 } else if (f & NAME_ADDRSPEC_ERR_ATSEQ)
1120 cs = _("\"%s\" contains invalid %s sequence\n");
1121 else
1122 cs = _("\"%s\" contains invalid character %s\n");
1124 c = NAME_ADDRSPEC_ERR_GETWC(f);
1125 snprintf(cbuf, sizeof cbuf,
1126 (ok8bit && c >= 040 && c <= 0177 ? "'%c'" : fmt), c);
1127 goto jprint;
1129 goto jleave;
1132 /* *expandaddr* stuff */
1133 if (!(rv = ((eacm & EACM_MODE_MASK) != EACM_NONE)))
1134 goto jleave;
1136 eaf = expandaddr_to_eaf();
1138 if ((eacm & EACM_STRICT) && (f & NAME_ADDRSPEC_ISFILEORPIPE)) {
1139 if (eaf & EAF_FAIL)
1140 rv = -rv;
1141 cs = _("\"%s\"%s: file or pipe addressees not allowed here\n");
1142 if (eacm & EACM_NOLOG)
1143 goto jleave;
1144 else
1145 goto j0print;
1148 eaf |= (eacm & EAF_TARGET_MASK);
1149 if (eacm & EACM_NONAME)
1150 eaf &= ~EAF_NAME;
1152 if (eaf == EAF_NONE) {
1153 rv = FAL0;
1154 goto jleave;
1156 if (eaf & EAF_FAIL)
1157 rv = -rv;
1159 if (!(eaf & EAF_FILE) && (f & NAME_ADDRSPEC_ISFILE)) {
1160 cs = _("\"%s\"%s: *expandaddr* doesn't allow file target\n");
1161 if (eacm & EACM_NOLOG)
1162 goto jleave;
1163 } else if (!(eaf & EAF_PIPE) && (f & NAME_ADDRSPEC_ISPIPE)) {
1164 cs = _("\"%s\"%s: *expandaddr* doesn't allow command pipe target\n");
1165 if (eacm & EACM_NOLOG)
1166 goto jleave;
1167 } else if (!(eaf & EAF_NAME) && (f & NAME_ADDRSPEC_ISNAME)) {
1168 cs = _("\"%s\"%s: *expandaddr* doesn't allow user name target\n");
1169 if (eacm & EACM_NOLOG)
1170 goto jleave;
1171 } else if (!(eaf & EAF_ADDR) && (f & NAME_ADDRSPEC_ISADDR)) {
1172 cs = _("\"%s\"%s: *expandaddr* doesn't allow mail address target\n");
1173 if (eacm & EACM_NOLOG)
1174 goto jleave;
1175 } else {
1176 rv = FAL0;
1177 goto jleave;
1180 j0print:
1181 cbuf[0] = '\0';
1182 jprint:
1183 n_err(cs, np->n_name, cbuf);
1184 jleave:
1185 NYD_LEAVE;
1186 return rv;
1189 FL char *
1190 skin(char const *name)
1192 struct addrguts ag;
1193 char *ret = NULL;
1194 NYD_ENTER;
1196 if (name != NULL) {
1197 addrspec_with_guts(1, name, &ag);
1198 ret = ag.ag_skinned;
1199 if (!(ag.ag_n_flags & NAME_NAME_SALLOC))
1200 ret = savestrbuf(ret, ag.ag_slen);
1202 NYD_LEAVE;
1203 return ret;
1206 /* TODO addrspec_with_guts: RFC 5322
1207 * TODO addrspec_with_guts: trim whitespace ETC. ETC. ETC.!!! */
1208 FL int
1209 addrspec_with_guts(int doskin, char const *name, struct addrguts *agp)
1211 char const *cp;
1212 char *cp2, *bufend, *nbuf, c, gotlt, gotaddr, lastsp;
1213 int rv = 1;
1214 NYD_ENTER;
1216 memset(agp, 0, sizeof *agp);
1218 if ((agp->ag_input = name) == NULL || (agp->ag_ilen = strlen(name)) == 0) {
1219 agp->ag_skinned = UNCONST(""); /* ok: NAME_SALLOC is not set */
1220 agp->ag_slen = 0;
1221 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
1222 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
1223 goto jleave;
1226 if (!doskin || !anyof(name, "(< ")) {
1227 /*agp->ag_iaddr_start = 0;*/
1228 agp->ag_iaddr_aend = agp->ag_ilen;
1229 agp->ag_skinned = UNCONST(name); /* (NAME_SALLOC not set) */
1230 agp->ag_slen = agp->ag_ilen;
1231 agp->ag_n_flags = NAME_SKINNED;
1232 goto jcheck;
1235 /* Something makes us think we have to perform the skin operation */
1236 nbuf = ac_alloc(agp->ag_ilen + 1);
1237 /*agp->ag_iaddr_start = 0;*/
1238 cp2 = bufend = nbuf;
1239 gotlt = gotaddr = lastsp = 0;
1241 for (cp = name++; (c = *cp++) != '\0'; ) {
1242 switch (c) {
1243 case '(':
1244 cp = skip_comment(cp);
1245 lastsp = 0;
1246 break;
1247 case '"':
1248 /* Start of a "quoted-string".
1249 * Copy it in its entirety */
1250 /* XXX RFC: quotes are "semantically invisible"
1251 * XXX But it was explicitly added (Changelog.Heirloom,
1252 * XXX [9.23] released 11/15/00, "Do not remove quotes
1253 * XXX when skinning names"? No more info.. */
1254 *cp2++ = c;
1255 while ((c = *cp) != '\0') { /* TODO improve */
1256 cp++;
1257 if (c == '"') {
1258 *cp2++ = c;
1259 break;
1261 if (c != '\\')
1262 *cp2++ = c;
1263 else if ((c = *cp) != '\0') {
1264 *cp2++ = c;
1265 cp++;
1268 lastsp = 0;
1269 break;
1270 case ' ':
1271 case '\t':
1272 if (gotaddr == 1) {
1273 gotaddr = 2;
1274 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1276 if (cp[0] == 'a' && cp[1] == 't' && blankchar(cp[2]))
1277 cp += 3, *cp2++ = '@';
1278 else if (cp[0] == '@' && blankchar(cp[1]))
1279 cp += 2, *cp2++ = '@';
1280 else
1281 lastsp = 1;
1282 break;
1283 case '<':
1284 agp->ag_iaddr_start = PTR2SIZE(cp - (name - 1));
1285 cp2 = bufend;
1286 gotlt = gotaddr = 1;
1287 lastsp = 0;
1288 break;
1289 case '>':
1290 if (gotlt) {
1291 /* (_addrspec_check() verifies these later!) */
1292 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1293 gotlt = 0;
1294 while ((c = *cp) != '\0' && c != ',') {
1295 cp++;
1296 if (c == '(')
1297 cp = skip_comment(cp);
1298 else if (c == '"')
1299 while ((c = *cp) != '\0') {
1300 cp++;
1301 if (c == '"')
1302 break;
1303 if (c == '\\' && *cp != '\0')
1304 ++cp;
1307 lastsp = 0;
1308 break;
1310 /* FALLTRHOUGH */
1311 default:
1312 if (lastsp) {
1313 lastsp = 0;
1314 if (gotaddr)
1315 *cp2++ = ' ';
1317 *cp2++ = c;
1318 if (c == ',') {
1319 if (!gotlt) {
1320 *cp2++ = ' ';
1321 for (; blankchar(*cp); ++cp)
1323 lastsp = 0;
1324 bufend = cp2;
1326 } else if (!gotaddr) {
1327 gotaddr = 1;
1328 agp->ag_iaddr_start = PTR2SIZE(cp - name);
1332 agp->ag_slen = PTR2SIZE(cp2 - nbuf);
1333 if (agp->ag_iaddr_aend == 0)
1334 agp->ag_iaddr_aend = agp->ag_ilen;
1336 agp->ag_skinned = savestrbuf(nbuf, agp->ag_slen);
1337 ac_free(nbuf);
1338 agp->ag_n_flags = NAME_NAME_SALLOC | NAME_SKINNED;
1339 jcheck:
1340 rv = _addrspec_check(doskin, agp);
1341 jleave:
1342 NYD_LEAVE;
1343 return rv;
1346 FL char *
1347 realname(char const *name)
1349 char const *cp, *cq, *cstart = NULL, *cend = NULL;
1350 char *rname, *rp;
1351 struct str in, out;
1352 int quoted, good, nogood;
1353 NYD_ENTER;
1355 if ((cp = UNCONST(name)) == NULL)
1356 goto jleave;
1357 for (; *cp != '\0'; ++cp) {
1358 switch (*cp) {
1359 case '(':
1360 if (cstart != NULL) {
1361 /* More than one comment in address, doesn't make sense to display
1362 * it without context. Return the entire field */
1363 cp = mime_fromaddr(name);
1364 goto jleave;
1366 cstart = cp++;
1367 cp = skip_comment(cp);
1368 cend = cp--;
1369 if (cend <= cstart)
1370 cend = cstart = NULL;
1371 break;
1372 case '"':
1373 while (*cp) {
1374 if (*++cp == '"')
1375 break;
1376 if (*cp == '\\' && cp[1])
1377 ++cp;
1379 break;
1380 case '<':
1381 if (cp > name) {
1382 cstart = name;
1383 cend = cp;
1385 break;
1386 case ',':
1387 /* More than one address. Just use the first one */
1388 goto jbrk;
1392 jbrk:
1393 if (cstart == NULL) {
1394 if (*name == '<') {
1395 /* If name contains only a route-addr, the surrounding angle brackets
1396 * don't serve any useful purpose when displaying, so remove */
1397 cp = prstr(skin(name));
1398 } else
1399 cp = mime_fromaddr(name);
1400 goto jleave;
1403 /* Strip quotes. Note that quotes that appear within a MIME encoded word are
1404 * not stripped. The idea is to strip only syntactical relevant things (but
1405 * this is not necessarily the most sensible way in practice) */
1406 rp = rname = ac_alloc(PTR2SIZE(cend - cstart +1));
1407 quoted = 0;
1408 for (cp = cstart; cp < cend; ++cp) {
1409 if (*cp == '(' && !quoted) {
1410 cq = skip_comment(++cp);
1411 if (PTRCMP(--cq, >, cend))
1412 cq = cend;
1413 while (cp < cq) {
1414 if (*cp == '\\' && PTRCMP(cp + 1, <, cq))
1415 ++cp;
1416 *rp++ = *cp++;
1418 } else if (*cp == '\\' && PTRCMP(cp + 1, <, cend))
1419 *rp++ = *++cp;
1420 else if (*cp == '"') {
1421 quoted = !quoted;
1422 continue;
1423 } else
1424 *rp++ = *cp;
1426 *rp = '\0';
1427 in.s = rname;
1428 in.l = rp - rname;
1429 mime_fromhdr(&in, &out, TD_ISPR | TD_ICONV);
1430 ac_free(rname);
1431 rname = savestr(out.s);
1432 free(out.s);
1434 while (blankchar(*rname))
1435 ++rname;
1436 for (rp = rname; *rp != '\0'; ++rp)
1438 while (PTRCMP(--rp, >=, rname) && blankchar(*rp))
1439 *rp = '\0';
1440 if (rp == rname) {
1441 cp = mime_fromaddr(name);
1442 goto jleave;
1445 /* mime_fromhdr() has converted all nonprintable characters to question
1446 * marks now. These and blanks are considered uninteresting; if the
1447 * displayed part of the real name contains more than 25% of them, it is
1448 * probably better to display the plain email address instead */
1449 good = 0;
1450 nogood = 0;
1451 for (rp = rname; *rp != '\0' && PTRCMP(rp, <, rname + 20); ++rp)
1452 if (*rp == '?' || blankchar(*rp))
1453 ++nogood;
1454 else
1455 ++good;
1456 cp = (good * 3 < nogood) ? prstr(skin(name)) : rname;
1457 jleave:
1458 NYD_LEAVE;
1459 return UNCONST(cp);
1462 FL char *
1463 name1(struct message *mp, int reptype)
1465 char *namebuf, *cp, *cp2, *linebuf = NULL /* TODO line pool */;
1466 size_t namesize, linesize = 0;
1467 FILE *ibuf;
1468 int f1st = 1;
1469 NYD_ENTER;
1471 if ((cp = hfield1("from", mp)) != NULL && *cp != '\0')
1472 goto jleave;
1473 if (reptype == 0 && (cp = hfield1("sender", mp)) != NULL && *cp != '\0')
1474 goto jleave;
1476 namebuf = smalloc(namesize = 1);
1477 namebuf[0] = 0;
1478 if (mp->m_flag & MNOFROM)
1479 goto jout;
1480 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
1481 goto jout;
1482 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1483 goto jout;
1485 jnewname:
1486 if (namesize <= linesize)
1487 namebuf = srealloc(namebuf, namesize = linesize +1);
1488 for (cp = linebuf; *cp != '\0' && *cp != ' '; ++cp)
1490 for (; blankchar(*cp); ++cp)
1492 for (cp2 = namebuf + strlen(namebuf);
1493 *cp && !blankchar(*cp) && PTRCMP(cp2, <, namebuf + namesize -1);)
1494 *cp2++ = *cp++;
1495 *cp2 = '\0';
1497 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1498 goto jout;
1499 if ((cp = strchr(linebuf, 'F')) == NULL)
1500 goto jout;
1501 if (strncmp(cp, "From", 4)) /* XXX is_head? */
1502 goto jout;
1503 if (namesize <= linesize)
1504 namebuf = srealloc(namebuf, namesize = linesize + 1);
1506 while ((cp = strchr(cp, 'r')) != NULL) {
1507 if (!strncmp(cp, "remote", 6)) {
1508 if ((cp = strchr(cp, 'f')) == NULL)
1509 break;
1510 if (strncmp(cp, "from", 4) != 0)
1511 break;
1512 if ((cp = strchr(cp, ' ')) == NULL)
1513 break;
1514 cp++;
1515 if (f1st) {
1516 strncpy(namebuf, cp, namesize);
1517 f1st = 0;
1518 } else {
1519 cp2 = strrchr(namebuf, '!') + 1;
1520 strncpy(cp2, cp, PTR2SIZE(namebuf + namesize - cp2));
1522 namebuf[namesize - 2] = '!';
1523 namebuf[namesize - 1] = '\0';
1524 goto jnewname;
1526 cp++;
1528 jout:
1529 if (*namebuf != '\0' || ((cp = hfield1("return-path", mp))) == NULL ||
1530 *cp == '\0')
1531 cp = savestr(namebuf);
1533 if (linebuf != NULL)
1534 free(linebuf);
1535 free(namebuf);
1536 jleave:
1537 NYD_LEAVE;
1538 return cp;
1541 FL char *
1542 subject_re_trim(char *s)
1544 struct {
1545 ui8_t len;
1546 char dat[7];
1547 } const *pp, ignored[] = { /* Update *reply-strings* manual upon change! */
1548 { 3, "re:" },
1549 { 3, "aw:" }, { 5, "antw:" }, /* de */
1550 { 0, "" }
1553 bool_t any = FAL0;
1554 char *orig_s = s, *re_st = NULL, *re_st_x;
1555 size_t re_l = 0 /* pacify CC */;
1556 NYD_ENTER;
1558 if ((re_st_x = ok_vlook(reply_strings)) != NULL &&
1559 (re_l = strlen(re_st_x)) > 0) {
1560 re_st = ac_alloc(++re_l * 2);
1561 memcpy(re_st, re_st_x, re_l);
1564 jouter:
1565 while (*s != '\0') {
1566 while (spacechar(*s))
1567 ++s;
1569 for (pp = ignored; pp->len > 0; ++pp)
1570 if (is_asccaseprefix(s, pp->dat)) {
1571 s += pp->len;
1572 any = TRU1;
1573 goto jouter;
1576 if (re_st != NULL) {
1577 char *cp;
1579 memcpy(re_st_x = re_st + re_l, re_st, re_l);
1580 while ((cp = n_strsep(&re_st_x, ',', TRU1)) != NULL)
1581 if (is_asccaseprefix(s, cp)) {
1582 s += strlen(cp);
1583 any = TRU1;
1584 goto jouter;
1587 break;
1590 if (re_st != NULL)
1591 ac_free(re_st);
1592 NYD_LEAVE;
1593 return any ? s : orig_s;
1596 FL int
1597 msgidcmp(char const *s1, char const *s2)
1599 int q1 = 0, q2 = 0, c1, c2;
1600 NYD_ENTER;
1602 do {
1603 c1 = msgidnextc(&s1, &q1);
1604 c2 = msgidnextc(&s2, &q2);
1605 if (c1 != c2)
1606 break;
1607 } while (c1 && c2);
1608 NYD_LEAVE;
1609 return c1 - c2;
1612 FL int
1613 is_ign(char const *field, size_t fieldlen, struct ignoretab igta[2])
1615 char *realfld;
1616 int rv;
1617 NYD_ENTER;
1619 rv = 0;
1620 if (igta == NULL)
1621 goto jleave;
1622 rv = 1;
1623 if (igta == allignore)
1624 goto jleave;
1626 /* Lowercase it so that "Status" and "status" will hash to the same place */
1627 realfld = ac_alloc(fieldlen +1);
1628 i_strcpy(realfld, field, fieldlen +1);
1629 if (igta[1].i_count > 0)
1630 rv = !member(realfld, igta + 1);
1631 else
1632 rv = member(realfld, igta);
1633 ac_free(realfld);
1634 jleave:
1635 NYD_LEAVE;
1636 return rv;
1639 FL int
1640 member(char const *realfield, struct ignoretab *table)
1642 struct ignored *igp;
1643 int rv = 0;
1644 NYD_ENTER;
1646 for (igp = table->i_head[hash(realfield)]; igp != 0; igp = igp->i_link)
1647 if (*igp->i_field == *realfield && !strcmp(igp->i_field, realfield)) {
1648 rv = 1;
1649 break;
1651 NYD_LEAVE;
1652 return rv;
1655 FL char const *
1656 fakefrom(struct message *mp)
1658 char const *name;
1659 NYD_ENTER;
1661 if (((name = skin(hfield1("return-path", mp))) == NULL || *name == '\0' ) &&
1662 ((name = skin(hfield1("from", mp))) == NULL || *name == '\0'))
1663 /* XXX MAILER-DAEMON is what an old MBOX manual page says.
1664 * RFC 4155 however requires a RFC 5322 (2822) conforming
1665 * "addr-spec", but we simply can't provide that */
1666 name = "MAILER-DAEMON";
1667 NYD_LEAVE;
1668 return name;
1671 FL char const *
1672 fakedate(time_t t)
1674 char *cp, *cq;
1675 NYD_ENTER;
1677 cp = ctime(&t);
1678 for (cq = cp; *cq != '\0' && *cq != '\n'; ++cq)
1680 *cq = '\0';
1681 cp = savestr(cp);
1682 NYD_LEAVE;
1683 return cp;
1686 #if defined HAVE_IMAP_SEARCH || defined HAVE_IMAP
1687 FL time_t
1688 unixtime(char const *fromline)
1690 char const *fp;
1691 char *xp;
1692 time_t t;
1693 int i, year, month, day, hour, minute, second, tzdiff;
1694 struct tm *tmptr;
1695 NYD2_ENTER;
1697 for (fp = fromline; *fp != '\0' && *fp != '\n'; ++fp)
1699 fp -= 24;
1700 if (PTR2SIZE(fp - fromline) < 7)
1701 goto jinvalid;
1702 if (fp[3] != ' ')
1703 goto jinvalid;
1704 for (i = 0;;) {
1705 if (!strncmp(fp + 4, month_names[i], 3))
1706 break;
1707 if (month_names[++i][0] == '\0')
1708 goto jinvalid;
1710 month = i + 1;
1711 if (fp[7] != ' ')
1712 goto jinvalid;
1713 day = strtol(fp + 8, &xp, 10);
1714 if (*xp != ' ' || xp != fp + 10)
1715 goto jinvalid;
1716 hour = strtol(fp + 11, &xp, 10);
1717 if (*xp != ':' || xp != fp + 13)
1718 goto jinvalid;
1719 minute = strtol(fp + 14, &xp, 10);
1720 if (*xp != ':' || xp != fp + 16)
1721 goto jinvalid;
1722 second = strtol(fp + 17, &xp, 10);
1723 if (*xp != ' ' || xp != fp + 19)
1724 goto jinvalid;
1725 year = strtol(fp + 20, &xp, 10);
1726 if (xp != fp + 24)
1727 goto jinvalid;
1728 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
1729 goto jinvalid;
1730 tzdiff = t - mktime(gmtime(&t));
1731 tmptr = localtime(&t);
1732 if (tmptr->tm_isdst > 0)
1733 tzdiff += 3600;
1734 t -= tzdiff;
1735 jleave:
1736 NYD2_LEAVE;
1737 return t;
1738 jinvalid:
1739 time(&t);
1740 goto jleave;
1742 #endif /* HAVE_IMAP_SEARCH || defined HAVE_IMAP */
1744 FL time_t
1745 rfctime(char const *date)
1747 char const *cp = date;
1748 char *x;
1749 time_t t;
1750 int i, year, month, day, hour, minute, second;
1751 NYD2_ENTER;
1753 if ((cp = nexttoken(cp)) == NULL)
1754 goto jinvalid;
1755 if (alphachar(cp[0]) && alphachar(cp[1]) && alphachar(cp[2]) &&
1756 cp[3] == ',') {
1757 if ((cp = nexttoken(&cp[4])) == NULL)
1758 goto jinvalid;
1760 day = strtol(cp, &x, 10); /* XXX strtol */
1761 if ((cp = nexttoken(x)) == NULL)
1762 goto jinvalid;
1763 for (i = 0;;) {
1764 if (!strncmp(cp, month_names[i], 3))
1765 break;
1766 if (month_names[++i][0] == '\0')
1767 goto jinvalid;
1769 month = i + 1;
1770 if ((cp = nexttoken(&cp[3])) == NULL)
1771 goto jinvalid;
1772 /* RFC 5322, 4.3:
1773 * Where a two or three digit year occurs in a date, the year is to be
1774 * interpreted as follows: If a two digit year is encountered whose
1775 * value is between 00 and 49, the year is interpreted by adding 2000,
1776 * ending up with a value between 2000 and 2049. If a two digit year
1777 * is encountered with a value between 50 and 99, or any three digit
1778 * year is encountered, the year is interpreted by adding 1900 */
1779 year = strtol(cp, &x, 10); /* XXX strtol */
1780 i = (int)PTR2SIZE(x - cp);
1781 if (i == 2 && year >= 0 && year <= 49)
1782 year += 2000;
1783 else if (i == 3 || (i == 2 && year >= 50 && year <= 99))
1784 year += 1900;
1785 if ((cp = nexttoken(x)) == NULL)
1786 goto jinvalid;
1787 hour = strtol(cp, &x, 10); /* XXX strtol */
1788 if (*x != ':')
1789 goto jinvalid;
1790 cp = &x[1];
1791 minute = strtol(cp, &x, 10);
1792 if (*x == ':') {
1793 cp = x + 1;
1794 second = strtol(cp, &x, 10);
1795 } else
1796 second = 0;
1798 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
1799 goto jinvalid;
1800 if ((cp = nexttoken(x)) != NULL) {
1801 char buf[3];
1802 int sign = 1;
1804 switch (*cp) {
1805 case '+':
1806 sign = -1;
1807 /* FALLTHRU */
1808 case '-':
1809 ++cp;
1810 break;
1812 if (digitchar(cp[0]) && digitchar(cp[1]) && digitchar(cp[2]) &&
1813 digitchar(cp[3])) {
1814 long tadj;
1815 buf[2] = '\0';
1816 buf[0] = cp[0];
1817 buf[1] = cp[1];
1818 tadj = strtol(buf, NULL, 10) * 3600;/*XXX strtrol*/
1819 buf[0] = cp[2];
1820 buf[1] = cp[3];
1821 tadj += strtol(buf, NULL, 10) * 60; /* XXX strtol*/
1822 if (sign < 0)
1823 tadj = -tadj;
1824 t += tadj;
1826 /* TODO WE DO NOT YET PARSE (OBSOLETE) ZONE NAMES
1827 * TODO once again, Christos Zoulas and NetBSD Mail have done
1828 * TODO a really good job already, but using strptime(3), which
1829 * TODO is not portable. Nonetheless, WE must improve, not
1830 * TODO at last because we simply ignore obsolete timezones!!
1831 * TODO See RFC 5322, 4.3! */
1833 jleave:
1834 NYD2_LEAVE;
1835 return t;
1836 jinvalid:
1837 t = 0;
1838 goto jleave;
1841 #define is_leapyear(Y) ((((Y) % 100 ? (Y) : (Y) / 100) & 3) == 0)
1843 FL time_t
1844 combinetime(int year, int month, int day, int hour, int minute, int second)
1846 time_t t;
1847 NYD2_ENTER;
1849 if (second < 0 || minute < 0 || hour < 0 || day < 1) {
1850 t = (time_t)-1;
1851 goto jleave;
1854 t = second + minute * 60 + hour * 3600 + (day - 1) * 86400;
1855 if (month > 1)
1856 t += 86400 * 31;
1857 if (month > 2)
1858 t += 86400 * (is_leapyear(year) ? 29 : 28);
1859 if (month > 3)
1860 t += 86400 * 31;
1861 if (month > 4)
1862 t += 86400 * 30;
1863 if (month > 5)
1864 t += 86400 * 31;
1865 if (month > 6)
1866 t += 86400 * 30;
1867 if (month > 7)
1868 t += 86400 * 31;
1869 if (month > 8)
1870 t += 86400 * 31;
1871 if (month > 9)
1872 t += 86400 * 30;
1873 if (month > 10)
1874 t += 86400 * 31;
1875 if (month > 11)
1876 t += 86400 * 30;
1877 year -= 1900;
1878 t += (year - 70) * 31536000 + ((year - 69) / 4) * 86400 -
1879 ((year - 1) / 100) * 86400 + ((year + 299) / 400) * 86400;
1880 jleave:
1881 NYD2_LEAVE;
1882 return t;
1885 FL void
1886 substdate(struct message *m)
1888 char const *cp;
1889 NYD_ENTER;
1891 /* Determine the date to print in faked 'From ' lines. This is traditionally
1892 * the date the message was written to the mail file. Try to determine this
1893 * using RFC message header fields, or fall back to current time */
1894 if ((cp = hfield1("received", m)) != NULL) {
1895 while ((cp = nexttoken(cp)) != NULL && *cp != ';') {
1897 ++cp;
1898 while (alnumchar(*cp));
1900 if (cp && *++cp)
1901 m->m_time = rfctime(cp);
1903 if (m->m_time == 0 || m->m_time > time_current.tc_time) {
1904 if ((cp = hfield1("date", m)) != NULL)
1905 m->m_time = rfctime(cp);
1907 if (m->m_time == 0 || m->m_time > time_current.tc_time)
1908 m->m_time = time_current.tc_time;
1909 NYD_LEAVE;
1912 FL struct name const *
1913 check_from_and_sender(struct name const *fromfield,
1914 struct name const *senderfield)
1916 struct name const *rv = NULL;
1917 NYD_ENTER;
1919 if (senderfield != NULL) {
1920 if (senderfield->n_flink != NULL) {
1921 n_err(_("The \"Sender:\" field may contain only one address\n"));
1922 goto jleave;
1924 rv = senderfield;
1927 if (fromfield != NULL) {
1928 if (fromfield->n_flink != NULL && senderfield == NULL) {
1929 n_err(_("A \"Sender:\" field is required with multiple "
1930 "addresses in \"From:\" field\n"));
1931 goto jleave;
1933 if (rv == NULL)
1934 rv = fromfield;
1937 if (rv == NULL)
1938 rv = (struct name*)0x1;
1939 jleave:
1940 NYD_LEAVE;
1941 return rv;
1944 #ifdef HAVE_OPENSSL
1945 FL char *
1946 getsender(struct message *mp)
1948 char *cp;
1949 struct name *np;
1950 NYD_ENTER;
1952 if ((cp = hfield1("from", mp)) == NULL ||
1953 (np = lextract(cp, GEXTRA | GSKIN)) == NULL)
1954 cp = NULL;
1955 else
1956 cp = (np->n_flink != NULL) ? skin(hfield1("sender", mp)) : np->n_name;
1957 NYD_LEAVE;
1958 return cp;
1960 #endif
1962 FL int
1963 grab_headers(struct header *hp, enum gfield gflags, int subjfirst)
1965 /* TODO grab_headers: again, check counts etc. against RFC;
1966 * TODO (now assumes check_from_and_sender() is called afterwards ++ */
1967 int errs;
1968 int volatile comma;
1969 NYD_ENTER;
1971 errs = 0;
1972 comma = (ok_blook(bsdcompat) || ok_blook(bsdmsgs)) ? 0 : GCOMMA;
1974 if (gflags & GTO)
1975 hp->h_to = grab_names("To: ", hp->h_to, comma, GTO | GFULL);
1976 if (subjfirst && (gflags & GSUBJECT))
1977 hp->h_subject = n_input_cp_addhist("Subject: ", hp->h_subject, TRU1);
1978 if (gflags & GCC)
1979 hp->h_cc = grab_names("Cc: ", hp->h_cc, comma, GCC | GFULL);
1980 if (gflags & GBCC)
1981 hp->h_bcc = grab_names("Bcc: ", hp->h_bcc, comma, GBCC | GFULL);
1983 if (gflags & GEXTRA) {
1984 if (hp->h_from == NULL)
1985 hp->h_from = lextract(myaddrs(hp), GEXTRA | GFULL | GFULLEXTRA);
1986 hp->h_from = grab_names("From: ", hp->h_from, comma,
1987 GEXTRA | GFULL | GFULLEXTRA);
1988 if (hp->h_replyto == NULL)
1989 hp->h_replyto = lextract(ok_vlook(replyto), GEXTRA | GFULL);
1990 hp->h_replyto = grab_names("Reply-To: ", hp->h_replyto, comma,
1991 GEXTRA | GFULL);
1992 if (hp->h_sender == NULL)
1993 hp->h_sender = extract(ok_vlook(sender), GEXTRA | GFULL);
1994 hp->h_sender = grab_names("Sender: ", hp->h_sender, comma,
1995 GEXTRA | GFULL);
1996 if (hp->h_organization == NULL)
1997 hp->h_organization = ok_vlook(ORGANIZATION);
1998 hp->h_organization = n_input_cp_addhist("Organization: ",
1999 hp->h_organization, TRU1);
2002 if (!subjfirst && (gflags & GSUBJECT))
2003 hp->h_subject = n_input_cp_addhist("Subject: ", hp->h_subject, TRU1);
2005 NYD_LEAVE;
2006 return errs;
2009 FL bool_t
2010 header_match(struct message *mp, struct search_expr const *sep)
2012 struct str in, out;
2013 FILE *ibuf;
2014 int lc;
2015 size_t linesize = 0; /* TODO line pool */
2016 char *linebuf = NULL, *colon;
2017 bool_t rv = FAL0;
2018 NYD_ENTER;
2020 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2021 goto jleave;
2022 if ((lc = mp->m_lines - 1) < 0)
2023 goto jleave;
2025 if ((mp->m_flag & MNOFROM) == 0 &&
2026 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2027 goto jleave;
2028 while (lc > 0) {
2029 if (gethfield(ibuf, &linebuf, &linesize, lc, &colon) <= 0)
2030 break;
2031 if (blankchar(*++colon))
2032 ++colon;
2033 in.l = strlen(in.s = colon);
2034 mime_fromhdr(&in, &out, TD_ICONV);
2035 #ifdef HAVE_REGEX
2036 if (sep->ss_sexpr == NULL)
2037 rv = (regexec(&sep->ss_regex, out.s, 0,NULL, 0) != REG_NOMATCH);
2038 else
2039 #endif
2040 rv = substr(out.s, sep->ss_sexpr);
2041 free(out.s);
2042 if (rv)
2043 break;
2046 jleave:
2047 if (linebuf != NULL)
2048 free(linebuf);
2049 NYD_LEAVE;
2050 return rv;
2053 /* s-it-mode */