Fix _CLOEXEC_SET() fallback implementation
[s-mailx.git] / head.c
blob2e9ee644c2e7dcc916084829556223998e1c36de
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Routines for processing and detecting headlines.
3 *@ TODO Mostly a hackery, we need RFC compliant parsers instead.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
7 */
8 /*
9 * Copyright (c) 1980, 1993
10 * The Regents of the University of California. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 #undef n_FILE
37 #define n_FILE head
39 #ifndef HAVE_AMALGAMATION
40 # include "nail.h"
41 #endif
43 #ifdef HAVE_IDNA
44 # if HAVE_IDNA == HAVE_IDNA_LIBIDNA
45 # include <idna.h>
46 # include <idn-free.h>
47 # include <stringprep.h>
48 # elif HAVE_IDNA == HAVE_IDNA_IDNKIT
49 # include <idn/api.h>
50 # endif
51 #endif
53 struct cmatch_data {
54 size_t tlen; /* Length of .tdata */
55 char const *tdata; /* Template date - see _cmatch_data[] */
58 /* Template characters for cmatch_data.tdata:
59 * 'A' An upper case char
60 * 'a' A lower case char
61 * ' ' A space
62 * '0' A digit
63 * 'O' An optional digit or space
64 * ':' A colon
65 * '+' Either a plus or a minus sign */
66 static struct cmatch_data const _cmatch_data[] = {
67 { 24, "Aaa Aaa O0 00:00:00 0000" }, /* BSD/ISO C90 ctime */
68 { 28, "Aaa Aaa O0 00:00:00 AAA 0000" }, /* BSD tmz */
69 { 21, "Aaa Aaa O0 00:00 0000" }, /* SysV ctime */
70 { 25, "Aaa Aaa O0 00:00 AAA 0000" }, /* SysV tmz */
71 /* RFC 822-alike From_ lines do not conform to RFC 4155, but seem to be used
72 * in the wild (by UW-imap) */
73 { 30, "Aaa Aaa O0 00:00:00 0000 +0000" },
74 /* RFC 822 with zone spec; 1. military, 2. UT, 3. north america time
75 * zone strings; note that 1. is strictly speaking not correct as some
76 * letters are not used, and 2. is not because only "UT" is defined */
77 #define __reuse "Aaa Aaa O0 00:00:00 0000 AAA"
78 { 28 - 2, __reuse }, { 28 - 1, __reuse }, { 28 - 0, __reuse },
79 { 0, NULL }
81 #define a_HEAD_DATE_MINLEN 21
83 /* Skip over "word" as found in From_ line */
84 static char const * _from__skipword(char const *wp);
86 /* Match the date string against the date template (tp), return if match.
87 * See _cmatch_data[] for template character description */
88 static int _cmatch(size_t len, char const *date,
89 char const *tp);
91 /* Check whether date is a valid 'From_' date.
92 * (Rather ctime(3) generated dates, according to RFC 4155) */
93 static int _is_date(char const *date);
95 /* JulianDayNumber converter(s) */
96 static size_t a_head_gregorian_to_jdn(ui32_t y, ui32_t m, ui32_t d);
97 #if 0
98 static void a_head_jdn_to_gregorian(size_t jdn,
99 ui32_t *yp, ui32_t *mp, ui32_t *dp);
100 #endif
102 /* Convert the domain part of a skinned address to IDNA.
103 * If an error occurs before Unicode information is available, revert the IDNA
104 * error to a normal CHAR one so that the error message doesn't talk Unicode */
105 #ifdef HAVE_IDNA
106 static struct n_addrguts *a_head_idna_apply(struct n_addrguts *agp);
107 #endif
109 /* Classify and check a (possibly skinned) header body according to RFC
110 * *addr-spec* rules; if it (is assumed to has been) skinned it may however be
111 * also a file or a pipe command, so check that first, then.
112 * Otherwise perform content checking and isolate the domain part (for IDNA) */
113 static bool_t a_head_addrspec_check(struct n_addrguts *agp, bool_t skinned);
115 /* Return the next header field found in the given message.
116 * Return >= 0 if something found, < 0 elsewise.
117 * "colon" is set to point to the colon in the header.
118 * Must deal with \ continuations & other such fraud */
119 static int gethfield(FILE *f, char **linebuf, size_t *linesize,
120 int rem, char **colon);
122 static int msgidnextc(char const **cp, int *status);
124 /* Count the occurances of c in str */
125 static int charcount(char *str, int c);
127 static char const * nexttoken(char const *cp);
129 /* TODO v15: change *customhdr* syntax and use shell tokens?! */
130 static char *a_head_customhdr__sep(char **iolist);
132 static char const *
133 _from__skipword(char const *wp)
135 char c = 0;
136 NYD2_ENTER;
138 if (wp != NULL) {
139 while ((c = *wp++) != '\0' && !blankchar(c)) {
140 if (c == '"') {
141 while ((c = *wp++) != '\0' && c != '"')
143 if (c != '"')
144 --wp;
147 for (; blankchar(c); c = *wp++)
150 NYD2_LEAVE;
151 return (c == 0 ? NULL : wp - 1);
154 static int
155 _cmatch(size_t len, char const *date, char const *tp)
157 int ret = 0;
158 NYD2_ENTER;
160 while (len--) {
161 char c = date[len];
162 switch (tp[len]) {
163 case 'a':
164 if (!lowerchar(c))
165 goto jleave;
166 break;
167 case 'A':
168 if (!upperchar(c))
169 goto jleave;
170 break;
171 case ' ':
172 if (c != ' ')
173 goto jleave;
174 break;
175 case '0':
176 if (!digitchar(c))
177 goto jleave;
178 break;
179 case 'O':
180 if (c != ' ' && !digitchar(c))
181 goto jleave;
182 break;
183 case ':':
184 if (c != ':')
185 goto jleave;
186 break;
187 case '+':
188 if (c != '+' && c != '-')
189 goto jleave;
190 break;
193 ret = 1;
194 jleave:
195 NYD2_LEAVE;
196 return ret;
199 static int
200 _is_date(char const *date)
202 struct cmatch_data const *cmdp;
203 size_t dl;
204 int rv = 0;
205 NYD2_ENTER;
207 if ((dl = strlen(date)) >= a_HEAD_DATE_MINLEN)
208 for (cmdp = _cmatch_data; cmdp->tdata != NULL; ++cmdp)
209 if (dl == cmdp->tlen && (rv = _cmatch(dl, date, cmdp->tdata)))
210 break;
211 NYD2_LEAVE;
212 return rv;
215 static size_t
216 a_head_gregorian_to_jdn(ui32_t y, ui32_t m, ui32_t d){
217 /* Algorithm is taken from Communications of the ACM, Vol 6, No 8.
218 * (via third hand, plus adjustments).
219 * This algorithm is supposed to work for all dates in between 1582-10-15
220 * (0001-01-01 but that not Gregorian) and 65535-12-31 */
221 size_t jdn;
222 NYD2_ENTER;
224 #if 0
225 if(y == 0)
226 y = 1;
227 if(m == 0)
228 m = 1;
229 if(d == 0)
230 d = 1;
231 #endif
233 if(m > 2)
234 m -= 3;
235 else{
236 m += 9;
237 --y;
239 jdn = y;
240 jdn /= 100;
241 y -= 100 * jdn;
242 y *= 1461;
243 y >>= 2;
244 jdn *= 146097;
245 jdn >>= 2;
246 jdn += y;
247 jdn += d;
248 jdn += 1721119;
249 m *= 153;
250 m += 2;
251 m /= 5;
252 jdn += m;
253 NYD2_LEAVE;
254 return jdn;
257 #if 0
258 static void
259 a_head_jdn_to_gregorian(size_t jdn, ui32_t *yp, ui32_t *mp, ui32_t *dp){
260 /* Algorithm is taken from Communications of the ACM, Vol 6, No 8.
261 * (via third hand, plus adjustments) */
262 size_t y, x;
263 NYD2_ENTER;
265 jdn -= 1721119;
266 jdn <<= 2;
267 --jdn;
268 y = jdn / 146097;
269 jdn %= 146097;
270 jdn |= 3;
271 y *= 100;
272 y += jdn / 1461;
273 jdn %= 1461;
274 jdn += 4;
275 jdn >>= 2;
276 x = jdn;
277 jdn <<= 2;
278 jdn += x;
279 jdn -= 3;
280 x = jdn / 153; /* x -> month */
281 jdn %= 153;
282 jdn += 5;
283 jdn /= 5; /* jdn -> day */
284 if(x < 10)
285 x += 3;
286 else{
287 x -= 9;
288 ++y;
291 *yp = (ui32_t)(y & 0xFFFF);
292 *mp = (ui32_t)(x & 0xFF);
293 *dp = (ui32_t)(jdn & 0xFF);
294 NYD2_LEAVE;
296 #endif /* 0 */
298 #ifdef HAVE_IDNA
299 # if HAVE_IDNA == HAVE_IDNA_LIBIDNA
300 static struct n_addrguts *
301 a_head_idna_apply(struct n_addrguts *agp)
303 char *idna_utf8, *idna_ascii, *cs;
304 size_t sz, i;
305 NYD_ENTER;
307 sz = agp->ag_slen - agp->ag_sdom_start;
308 assert(sz > 0);
309 idna_utf8 = ac_alloc(sz +1);
310 memcpy(idna_utf8, agp->ag_skinned + agp->ag_sdom_start, sz);
311 idna_utf8[sz] = '\0';
313 /* GNU Libidn settles on top of iconv(3) without any fallback, so let's just
314 * let it perform the charset conversion, if any should be necessary */
315 if (!(n_psonce & n_PSO_UNICODE)) {
316 char const *tcs = ok_vlook(ttycharset);
317 idna_ascii = idna_utf8;
318 idna_utf8 = stringprep_convert(idna_ascii, "utf-8", tcs);
319 i = (idna_utf8 == NULL && n_err_no == n_ERR_INVAL);
320 ac_free(idna_ascii);
322 if (idna_utf8 == NULL) {
323 if (i)
324 n_err(_("Cannot convert from %s to %s\n"), tcs, "utf-8");
325 agp->ag_n_flags ^= NAME_ADDRSPEC_ERR_IDNA | NAME_ADDRSPEC_ERR_CHAR;
326 goto jleave;
330 if (idna_to_ascii_8z(idna_utf8, &idna_ascii, 0) != IDNA_SUCCESS) {
331 agp->ag_n_flags ^= NAME_ADDRSPEC_ERR_IDNA | NAME_ADDRSPEC_ERR_CHAR;
332 goto jleave1;
335 /* Replace the domain part of .ag_skinned with IDNA version */
336 sz = strlen(idna_ascii);
337 i = agp->ag_sdom_start;
338 cs = salloc(i + sz +1);
339 memcpy(cs, agp->ag_skinned, i);
340 memcpy(&cs[i], idna_ascii, sz);
341 i += sz;
342 cs[i] = '\0';
344 agp->ag_skinned = cs;
345 agp->ag_slen = i;
346 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags,
347 NAME_NAME_SALLOC | NAME_SKINNED | NAME_IDNA, 0);
349 idn_free(idna_ascii);
350 jleave1:
351 if (n_psonce & n_PSO_UNICODE)
352 ac_free(idna_utf8);
353 else
354 idn_free(idna_utf8);
355 jleave:
356 NYD_LEAVE;
357 return agp;
360 # elif HAVE_IDNA == HAVE_IDNA_IDNKIT /* IDNA==LIBIDNA */
361 static struct n_addrguts *
362 a_head_idna_apply(struct n_addrguts *agp)
364 char *idna_in, *idna_out, *cs;
365 size_t sz, i;
366 idn_result_t r;
367 NYD_ENTER;
369 sz = agp->ag_slen - agp->ag_sdom_start;
370 assert(sz > 0);
371 idna_in = ac_alloc(sz +1);
372 memcpy(idna_in, agp->ag_skinned + agp->ag_sdom_start, sz);
373 idna_in[sz] = '\0';
375 for (idna_out = NULL, sz = HOST_NAME_MAX +1;; sz += HOST_NAME_MAX) {
376 idna_out = ac_alloc(sz);
378 r = idn_encodename(IDN_ENCODE_APP, idna_in, idna_out, sz);
379 switch (r) {
380 case idn_success:
381 case idn_buffer_overflow:
382 break;
383 case idn_invalid_encoding:
384 n_err(_("Cannot convert from %s to %s\n"),
385 ok_vlook(ttycharset), "utf-8");
386 /* FALLTHRU */
387 default:
388 agp->ag_n_flags ^= NAME_ADDRSPEC_ERR_IDNA | NAME_ADDRSPEC_ERR_CHAR;
389 goto jleave;
392 if (r == idn_success)
393 break;
394 ac_free(idna_out);
397 /* Replace the domain part of .ag_skinned with IDNA version */
398 sz = strlen(idna_out);
399 i = agp->ag_sdom_start;
400 cs = salloc(i + sz +1);
401 memcpy(cs, agp->ag_skinned, i);
402 memcpy(&cs[i], idna_out, sz);
403 i += sz;
404 cs[i] = '\0';
406 agp->ag_skinned = cs;
407 agp->ag_slen = i;
408 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags,
409 NAME_NAME_SALLOC | NAME_SKINNED | NAME_IDNA, 0);
411 jleave:
412 ac_free(idna_out);
413 ac_free(idna_in);
414 NYD_LEAVE;
415 return agp;
417 # endif /* IDNA==IDNKIT */
418 #endif /* HAVE_IDNA */
420 static bool_t
421 a_head_addrspec_check(struct n_addrguts *agp, bool_t skinned)
423 char *addr, *p;
424 bool_t in_quote;
425 ui8_t in_domain, hadat;
426 union {bool_t b; char c; unsigned char u; ui32_t ui32; si32_t si32;} c;
427 #ifdef HAVE_IDNA
428 ui8_t use_idna;
429 #endif
430 NYD_ENTER;
432 #ifdef HAVE_IDNA
433 use_idna = ok_blook(idna_disable) ? 0 : 1;
434 #endif
435 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
436 addr = agp->ag_skinned;
438 if (agp->ag_iaddr_aend - agp->ag_iaddr_start == 0) {
439 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
440 goto jleave;
443 /* If the field is not a recipient, it cannot be a file or a pipe */
444 if (!skinned)
445 goto jaddr_check;
447 /* When changing any of the following adjust any RECIPIENTADDRSPEC;
448 * grep the latter for the complete picture */
449 if (*addr == '|') {
450 agp->ag_n_flags |= NAME_ADDRSPEC_ISPIPE;
451 goto jleave;
453 if (addr[0] == '/' || (addr[0] == '.' && addr[1] == '/') ||
454 (addr[0] == '-' && addr[1] == '\0'))
455 goto jisfile;
456 if (memchr(addr, '@', agp->ag_slen) == NULL) {
457 if (*addr == '+')
458 goto jisfile;
459 for (p = addr; (c.c = *p); ++p) {
460 if (c.c == '!' || c.c == '%')
461 break;
462 if (c.c == '/') {
463 jisfile:
464 agp->ag_n_flags |= NAME_ADDRSPEC_ISFILE;
465 goto jleave;
470 jaddr_check:
471 in_quote = FAL0;
472 in_domain = hadat = 0;
474 /* TODO addrspec_check: we need a real RFC 5322 (un)?structured parser! */
475 for (p = addr; (c.c = *p++) != '\0';) {
476 if (c.c == '"') {
477 in_quote = !in_quote;
478 } else if (c.u < 040 || c.u >= 0177) { /* TODO no magics: !bodychar()? */
479 #ifdef HAVE_IDNA
480 if (in_domain && use_idna > 0) {
481 if (use_idna == 1)
482 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_IDNA,
483 c.u);
484 use_idna = 2;
485 } else
486 #endif
487 break;
488 } else if (in_domain == 2) {
489 if ((c.c == ']' && *p != '\0') || c.c == '\\' || whitechar(c.c))
490 break;
491 } else if (in_quote && in_domain == 0) {
492 /*EMPTY*/;
493 } else if (c.c == '\\' && *p != '\0') {
494 ++p;
495 } else if (c.c == '@') {
496 if (hadat++ > 0) {
497 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_ATSEQ,
498 c.u);
499 goto jleave;
501 agp->ag_sdom_start = PTR2SIZE(p - addr);
502 agp->ag_n_flags |= NAME_ADDRSPEC_ISADDR; /* TODO .. really? */
503 in_domain = (*p == '[') ? 2 : 1;
504 continue;
505 } else if (c.c == '(' || c.c == ')' || c.c == '<' || c.c == '>' ||
506 c.c == '[' || c.c == ']' || c.c == ':' || c.c == ';' ||
507 c.c == '\\' || c.c == ',')
508 break;
509 hadat = 0;
511 if (c.c != '\0') {
512 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_CHAR, c.u);
513 goto jleave;
516 if(!(agp->ag_n_flags & NAME_ADDRSPEC_ISADDR)){
517 agp->ag_n_flags |= NAME_ADDRSPEC_ISNAME;
518 if(!n_alias_is_valid_name(agp->ag_input))
519 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_NAME, '.');
520 }else{
521 /* If we seem to know that this is an address. Ensure this is correct
522 * according to RFC 5322 TODO the entire address parser should be like
523 * TODO that for one, and then we should know whether structured or
524 * TODO unstructured, and just parse correctly overall!
525 * TODO In addition, this can be optimised a lot.
526 * TODO And it is far from perfect: it should not forget whether no
527 * TODO whitespace followed some snippet, and it was written hastily */
528 struct a_token{
529 struct a_token *t_last;
530 struct a_token *t_next;
531 enum{
532 a_T_TATOM = 1<<0,
533 a_T_TCOMM = 1<<1,
534 a_T_TQUOTE = 1<<2,
535 a_T_TADDR = 1<<3,
536 a_T_TMASK = (1<<4) - 1,
538 a_T_SPECIAL = 1<<8 /* An atom actually needs to go TQUOTE */
539 } t_f;
540 ui8_t t__pad[4];
541 size_t t_start;
542 size_t t_end;
543 } *thead, *tcurr, *tp;
545 struct n_string ost, *ostp;
546 char const *cp, *cp1st, *cpmax, *xp;
547 void *lofi_snap;
549 /* Name and domain must be non-empty */
550 if(*addr == '@' || &addr[2] >= p || p[-2] == '@'){
551 c.c = '@';
552 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_ATSEQ, c.u);
553 goto jleave;
556 #ifdef HAVE_IDNA
557 if(use_idna == 2)
558 agp = a_head_idna_apply(agp);
559 #endif
561 cp = agp->ag_input;
563 /* Nothing to do if there is only an address (in angle brackets) */
564 if(agp->ag_iaddr_start == 0){
565 if(agp->ag_iaddr_aend == agp->ag_ilen)
566 goto jleave;
567 }else if(agp->ag_iaddr_start == 1 && *cp == '<' &&
568 agp->ag_iaddr_aend == agp->ag_ilen - 1 &&
569 cp[agp->ag_iaddr_aend] == '>')
570 goto jleave;
572 /* It is not, so parse off all tokens, then resort and rejoin */
573 lofi_snap = n_lofi_snap_create();
575 cp1st = cp;
576 if((c.ui32 = agp->ag_iaddr_start) > 0)
577 --c.ui32;
578 cpmax = &cp[c.ui32];
580 thead = tcurr = NULL;
581 hadat = FAL0;
582 jnode_redo:
583 for(tp = NULL; cp < cpmax;){
584 switch((c.c = *cp)){
585 case '(':
586 if(tp != NULL)
587 tp->t_end = PTR2SIZE(cp - cp1st);
588 tp = n_lofi_alloc(sizeof *tp);
589 tp->t_next = NULL;
590 if((tp->t_last = tcurr) != NULL)
591 tcurr->t_next = tp;
592 else
593 thead = tp;
594 tcurr = tp;
595 tp->t_f = a_T_TCOMM;
596 tp->t_start = PTR2SIZE(++cp - cp1st);
597 xp = skip_comment(cp);
598 tp->t_end = PTR2SIZE(xp - cp1st);
599 cp = xp;
600 if(tp->t_end > tp->t_start){
601 if(xp[-1] == ')')
602 --tp->t_end;
603 else{
604 /* No closing comment - strip trailing whitespace */
605 while(blankchar(*--xp))
606 if(--tp->t_end == tp->t_start)
607 break;
610 tp = NULL;
611 break;
613 case '"':
614 if(tp != NULL)
615 tp->t_end = PTR2SIZE(cp - cp1st);
616 tp = n_lofi_alloc(sizeof *tp);
617 tp->t_next = NULL;
618 if((tp->t_last = tcurr) != NULL)
619 tcurr->t_next = tp;
620 else
621 thead = tp;
622 tcurr = tp;
623 tp->t_f = a_T_TQUOTE;
624 tp->t_start = PTR2SIZE(++cp - cp1st);
625 for(xp = cp; xp < cpmax; ++xp){
626 if((c.c = *xp) == '"')
627 break;
628 if(c.c == '\\' && xp[1] != '\0')
629 ++xp;
631 tp->t_end = PTR2SIZE(xp - cp1st);
632 cp = &xp[1];
633 if(tp->t_end > tp->t_start){
634 /* No closing quote - strip trailing whitespace */
635 if(*xp != '"'){
636 while(blankchar(*xp--))
637 if(--tp->t_end == tp->t_start)
638 break;
641 tp = NULL;
642 break;
644 default:
645 if(blankchar(c.c)){
646 if(tp != NULL)
647 tp->t_end = PTR2SIZE(cp - cp1st);
648 tp = NULL;
649 ++cp;
650 break;
653 if(tp == NULL){
654 tp = n_lofi_alloc(sizeof *tp);
655 tp->t_next = NULL;
656 if((tp->t_last = tcurr) != NULL)
657 tcurr->t_next = tp;
658 else
659 thead = tp;
660 tcurr = tp;
661 tp->t_f = a_T_TATOM;
662 tp->t_start = PTR2SIZE(cp - cp1st);
664 ++cp;
666 /* Reverse solidus transforms the following into a quoted-pair, and
667 * therefore (must occur in comment or quoted-string only) the
668 * entire atom into a quoted string */
669 if(c.c == '\\'){
670 tp->t_f |= a_T_SPECIAL;
671 if(cp < cpmax)
672 ++cp;
674 /* Is this plain RFC 5322 "atext", or "specials"? Because we don't
675 * TODO know structured/unstructured, nor anything else, we need to
676 * TODO treat "dot-atom" as being identical to "specials" */
677 else if(!alnumchar(c.c) &&
678 c.c != '!' && c.c != '#' && c.c != '$' && c.c != '%' &&
679 c.c != '&' && c.c != '\'' && c.c != '*' && c.c != '+' &&
680 c.c != '-' && c.c != '/' && c.c != '=' && c.c != '?' &&
681 c.c != '^' && c.c != '_' && c.c != '`' && c.c != '{' &&
682 c.c != '}' && c.c != '|' && c.c != '}' && c.c != '~')
683 tp->t_f |= a_T_SPECIAL;
684 break;
687 if(tp != NULL)
688 tp->t_end = PTR2SIZE(cp - cp1st);
690 if(hadat == FAL0){
691 hadat = TRU1;
692 tp = n_lofi_alloc(sizeof *tp);
693 tp->t_next = NULL;
694 if((tp->t_last = tcurr) != NULL)
695 tcurr->t_next = tp;
696 else
697 thead = tp;
698 tcurr = tp;
699 tp->t_f = a_T_TADDR;
700 tp->t_start = agp->ag_iaddr_start;
701 tp->t_end = agp->ag_iaddr_aend;
702 tp = NULL;
704 cp = &agp->ag_input[agp->ag_iaddr_aend + 1];
705 cpmax = &agp->ag_input[agp->ag_ilen];
706 if(cp < cpmax)
707 goto jnode_redo;
710 /* Nothing may follow the address, move it to the end */
711 if(!(tcurr->t_f & a_T_TADDR)){
712 for(tp = thead; tp != NULL; tp = tp->t_next){
713 if(tp->t_f & a_T_TADDR){
714 if(tp->t_last != NULL)
715 tp->t_last->t_next = tp->t_next;
716 else
717 thead = tp->t_next;
718 if(tp->t_next != NULL)
719 tp->t_next->t_last = tp->t_last;
721 tcurr = tp;
722 while(tp->t_next != NULL)
723 tp = tp->t_next;
724 tp->t_next = tcurr;
725 tcurr->t_last = tp;
726 tcurr->t_next = NULL;
727 break;
732 /* Make ranges contiguous: ensure a continuous range of atoms is converted
733 * to a SPECIAL one if at least one of them requires it */
734 for(tp = thead; tp != NULL; tp = tp->t_next){
735 if(tp->t_f & a_T_SPECIAL){
736 tcurr = tp;
737 while((tp = tp->t_last) != NULL && (tp->t_f & a_T_TATOM))
738 tp->t_f |= a_T_SPECIAL;
739 tp = tcurr;
740 while((tp = tp->t_next) != NULL && (tp->t_f & a_T_TATOM))
741 tp->t_f |= a_T_SPECIAL;
745 /* And yes, we want quotes to extend as much as possible */
746 for(tp = thead; tp != NULL; tp = tp->t_next){
747 if(tp->t_f & a_T_TQUOTE){
748 tcurr = tp;
749 while((tp = tp->t_last) != NULL && (tp->t_f & a_T_TATOM))
750 tp->t_f |= a_T_SPECIAL;
751 tp = tcurr;
752 while((tp = tp->t_next) != NULL && (tp->t_f & a_T_TATOM))
753 tp->t_f |= a_T_SPECIAL;
757 /* Then rejoin */
758 ostp = n_string_creat_auto(&ost);
759 if((c.ui32 = agp->ag_ilen) <= UI32_MAX >> 1)
760 ostp = n_string_reserve(ostp, c.ui32 <<= 1);
762 for(tcurr = thead; tcurr != NULL;){
763 if(tcurr != thead)
764 ostp = n_string_push_c(ostp, ' ');
765 if(tcurr->t_f & a_T_TADDR){
766 ostp = n_string_push_c(ostp, '<');
767 agp->ag_iaddr_start = ostp->s_len;
768 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
769 (tcurr->t_end - tcurr->t_start));
770 agp->ag_iaddr_aend = ostp->s_len;
771 ostp = n_string_push_c(ostp, '>');
772 tcurr = tcurr->t_next;
773 }else if(tcurr->t_f & a_T_TCOMM){
774 ostp = n_string_push_c(ostp, '(');
775 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
776 (tcurr->t_end - tcurr->t_start));
777 while((tp = tcurr->t_next) != NULL && (tp->t_f & a_T_TCOMM)){
778 tcurr = tp;
779 ostp = n_string_push_c(ostp, ' '); /* XXX may be artificial */
780 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
781 (tcurr->t_end - tcurr->t_start));
783 ostp = n_string_push_c(ostp, ')');
784 tcurr = tcurr->t_next;
785 }else if(tcurr->t_f & a_T_TQUOTE){
786 jput_quote:
787 ostp = n_string_push_c(ostp, '"');
788 tp = tcurr;
789 do/* while tcurr && TATOM||TQUOTE */{
790 cp = &cp1st[tcurr->t_start];
791 cpmax = &cp1st[tcurr->t_end];
792 if(cp == cpmax)
793 continue;
795 if(tcurr != tp)
796 ostp = n_string_push_c(ostp, ' ');
798 if((tcurr->t_f & (a_T_TATOM | a_T_SPECIAL)) == a_T_TATOM)
799 ostp = n_string_push_buf(ostp, cp, PTR2SIZE(cpmax - cp));
800 else{
801 bool_t esc;
803 for(esc = FAL0; cp < cpmax;){
804 if((c.c = *cp++) == '\\' && !esc){
805 if(cp < cpmax && (*cp == '"' || *cp == '\\'))
806 esc = TRU1;
807 }else{
808 if(esc || c.c == '"'){
809 jput_quote_esc:
810 ostp = n_string_push_c(ostp, '\\');
812 ostp = n_string_push_c(ostp, c.c);
813 esc = FAL0;
816 if(esc){
817 c.c = '\\';
818 goto jput_quote_esc;
821 }while((tcurr = tcurr->t_next) != NULL &&
822 (tcurr->t_f & (a_T_TATOM | a_T_TQUOTE)));
823 ostp = n_string_push_c(ostp, '"');
824 }else if(tcurr->t_f & a_T_SPECIAL)
825 goto jput_quote;
826 else{
827 /* Can we use a fast join mode? */
828 for(tp = tcurr; tcurr != NULL; tcurr = tcurr->t_next){
829 if(!(tcurr->t_f & a_T_TATOM))
830 break;
831 if(tcurr != tp)
832 ostp = n_string_push_c(ostp, ' ');
833 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
834 (tcurr->t_end - tcurr->t_start));
839 n_lofi_snap_unroll(lofi_snap);
841 agp->ag_input = n_string_cp(ostp);
842 agp->ag_ilen = ostp->s_len;
843 ostp = n_string_drop_ownership(ostp);
845 jleave:
846 NYD_LEAVE;
847 return ((agp->ag_n_flags & NAME_ADDRSPEC_INVALID) == 0);
850 static int
851 gethfield(FILE *f, char **linebuf, size_t *linesize, int rem, char **colon)
853 char *line2 = NULL, *cp, *cp2;
854 size_t line2size = 0;
855 int c, isenc;
856 NYD2_ENTER;
858 if (*linebuf == NULL)
859 *linebuf = srealloc(*linebuf, *linesize = 1);
860 **linebuf = '\0';
861 for (;;) {
862 if (--rem < 0) {
863 rem = -1;
864 break;
866 if ((c = readline_restart(f, linebuf, linesize, 0)) <= 0) {
867 rem = -1;
868 break;
870 for (cp = *linebuf; fieldnamechar(*cp); ++cp)
872 if (cp > *linebuf)
873 while (blankchar(*cp))
874 ++cp;
875 if (*cp != ':' || cp == *linebuf)
876 continue;
878 /* I guess we got a headline. Handle wraparound */
879 *colon = cp;
880 cp = *linebuf + c;
881 for (;;) {
882 isenc = 0;
883 while (PTRCMP(--cp, >=, *linebuf) && blankchar(*cp))
885 cp++;
886 if (rem <= 0)
887 break;
888 if (PTRCMP(cp - 8, >=, *linebuf) && cp[-1] == '=' && cp[-2] == '?')
889 isenc |= 1;
890 ungetc(c = getc(f), f);
891 if (!blankchar(c))
892 break;
893 c = readline_restart(f, &line2, &line2size, 0);
894 if (c < 0)
895 break;
896 --rem;
897 for (cp2 = line2; blankchar(*cp2); ++cp2)
899 c -= (int)PTR2SIZE(cp2 - line2);
900 if (cp2[0] == '=' && cp2[1] == '?' && c > 8)
901 isenc |= 2;
902 if (PTRCMP(cp + c, >=, *linebuf + *linesize - 2)) {
903 size_t diff = PTR2SIZE(cp - *linebuf),
904 colondiff = PTR2SIZE(*colon - *linebuf);
905 *linebuf = srealloc(*linebuf, *linesize += c + 2);
906 cp = &(*linebuf)[diff];
907 *colon = &(*linebuf)[colondiff];
909 if (isenc != 3)
910 *cp++ = ' ';
911 memcpy(cp, cp2, c);
912 cp += c;
914 *cp = '\0';
916 if (line2 != NULL)
917 free(line2);
918 break;
920 NYD2_LEAVE;
921 return rem;
924 static int
925 msgidnextc(char const **cp, int *status)
927 int c;
928 NYD2_ENTER;
930 assert(cp != NULL);
931 assert(*cp != NULL);
932 assert(status != NULL);
934 for (;;) {
935 if (*status & 01) {
936 if (**cp == '"') {
937 *status &= ~01;
938 (*cp)++;
939 continue;
941 if (**cp == '\\') {
942 (*cp)++;
943 if (**cp == '\0')
944 goto jeof;
946 goto jdfl;
948 switch (**cp) {
949 case '(':
950 *cp = skip_comment(&(*cp)[1]);
951 continue;
952 case '>':
953 case '\0':
954 jeof:
955 c = '\0';
956 goto jleave;
957 case '"':
958 (*cp)++;
959 *status |= 01;
960 continue;
961 case '@':
962 *status |= 02;
963 /*FALLTHRU*/
964 default:
965 jdfl:
966 c = *(*cp)++ & 0377;
967 c = (*status & 02) ? lowerconv(c) : c;
968 goto jleave;
971 jleave:
972 NYD2_LEAVE;
973 return c;
976 static int
977 charcount(char *str, int c)
979 char *cp;
980 int i;
981 NYD2_ENTER;
983 for (i = 0, cp = str; *cp; ++cp)
984 if (*cp == c)
985 ++i;
986 NYD2_LEAVE;
987 return i;
990 static char const *
991 nexttoken(char const *cp)
993 NYD2_ENTER;
994 for (;;) {
995 if (*cp == '\0') {
996 cp = NULL;
997 break;
1000 if (*cp == '(') {
1001 size_t nesting = 1;
1003 do switch (*++cp) {
1004 case '(':
1005 ++nesting;
1006 break;
1007 case ')':
1008 --nesting;
1009 break;
1010 } while (nesting > 0 && *cp != '\0'); /* XXX error? */
1011 } else if (blankchar(*cp) || *cp == ',')
1012 ++cp;
1013 else
1014 break;
1016 NYD2_LEAVE;
1017 return cp;
1020 static char *
1021 a_head_customhdr__sep(char **iolist){
1022 char *cp, c, *base;
1023 bool_t isesc, anyesc;
1024 NYD2_ENTER;
1026 for(base = *iolist; base != NULL; base = *iolist){
1027 while((c = *base) != '\0' && blankspacechar(c))
1028 ++base;
1030 for(isesc = anyesc = FAL0, cp = base;; ++cp){
1031 if(n_UNLIKELY((c = *cp) == '\0')){
1032 *iolist = NULL;
1033 break;
1034 }else if(!isesc){
1035 if(c == ','){
1036 *iolist = cp + 1;
1037 break;
1039 isesc = (c == '\\');
1040 }else{
1041 isesc = FAL0;
1042 anyesc |= (c == ',');
1046 while(cp > base && blankspacechar(cp[-1]))
1047 --cp;
1048 *cp = '\0';
1050 if(*base != '\0'){
1051 if(anyesc){
1052 char *ins;
1054 for(ins = cp = base;; ++ins)
1055 if((c = *cp) == '\\' && cp[1] == ','){
1056 *ins = ',';
1057 cp += 2;
1058 }else if((*ins = (++cp, c)) == '\0')
1059 break;
1061 break;
1064 NYD2_LEAVE;
1065 return base;
1068 FL char const *
1069 myaddrs(struct header *hp) /* TODO */
1071 struct name *np;
1072 char const *rv, *mta;
1073 NYD_ENTER;
1075 if (hp != NULL && (np = hp->h_from) != NULL) {
1076 if ((rv = np->n_fullname) != NULL)
1077 goto jleave;
1078 if ((rv = np->n_name) != NULL)
1079 goto jleave;
1082 if((rv = ok_vlook(from)) != NULL){
1083 if((np = lextract(rv, GEXTRA | GFULL)) == NULL)
1084 jefrom:
1085 n_err(_("An address given in *from* is invalid: %s\n"), rv);
1086 else for(; np != NULL; np = np->n_flink)
1087 if(is_addr_invalid(np, EACM_STRICT | EACM_NOLOG | EACM_NONAME))
1088 goto jefrom;
1089 goto jleave;
1092 /* When invoking *sendmail* directly, it's its task to generate an otherwise
1093 * undeterminable From: address. However, if the user sets *hostname*,
1094 * accept his desire */
1095 if (ok_vlook(hostname) != NULL)
1096 goto jnodename;
1097 if (ok_vlook(smtp) != NULL || /* TODO obsolete -> mta */
1098 /* TODO pretty hacky for now (this entire fun), later: url_creat()! */
1099 ((mta = ok_vlook(mta)) != NULL &&
1100 (mta = n_servbyname(mta, NULL)) != NULL && *mta != '\0'))
1101 goto jnodename;
1102 jleave:
1103 NYD_LEAVE;
1104 return rv;
1106 jnodename:{
1107 char *cp;
1108 char const *hn, *ln;
1109 size_t i;
1111 hn = n_nodename(TRU1);
1112 ln = ok_vlook(LOGNAME);
1113 i = strlen(ln) + strlen(hn) + 1 +1;
1114 rv = cp = salloc(i);
1115 sstpcpy(sstpcpy(sstpcpy(cp, ln), n_at), hn);
1117 goto jleave;
1120 FL char const *
1121 myorigin(struct header *hp) /* TODO */
1123 char const *rv = NULL, *ccp;
1124 struct name *np;
1125 NYD_ENTER;
1127 if((ccp = myaddrs(hp)) != NULL &&
1128 (np = lextract(ccp, GEXTRA | GFULL)) != NULL){
1129 if(np->n_flink == NULL)
1130 rv = ccp;
1131 else if((ccp = ok_vlook(sender)) != NULL) {
1132 if((np = lextract(ccp, GEXTRA | GFULL)) == NULL ||
1133 np->n_flink != NULL ||
1134 is_addr_invalid(np, EACM_STRICT | EACM_NOLOG | EACM_NONAME))
1135 n_err(_("The address given in *sender* is invalid: %s\n"), ccp);
1136 else
1137 rv = ccp;
1140 NYD_LEAVE;
1141 return rv;
1144 FL bool_t
1145 is_head(char const *linebuf, size_t linelen, bool_t check_rfc4155)
1147 char date[n_FROM_DATEBUF];
1148 bool_t rv;
1149 NYD2_ENTER;
1151 if ((rv = (linelen >= 5 && !memcmp(linebuf, "From ", 5))) && check_rfc4155 &&
1152 (extract_date_from_from_(linebuf, linelen, date) <= 0 ||
1153 !_is_date(date)))
1154 rv = TRUM1;
1155 NYD2_LEAVE;
1156 return rv;
1159 FL int
1160 extract_date_from_from_(char const *line, size_t linelen,
1161 char datebuf[n_FROM_DATEBUF])
1163 int rv;
1164 char const *cp = line;
1165 NYD_ENTER;
1167 rv = 1;
1169 /* "From " */
1170 cp = _from__skipword(cp);
1171 if (cp == NULL)
1172 goto jerr;
1173 /* "addr-spec " */
1174 cp = _from__skipword(cp);
1175 if (cp == NULL)
1176 goto jerr;
1177 if (cp[0] == 't' && cp[1] == 't' && cp[2] == 'y') {
1178 cp = _from__skipword(cp);
1179 if (cp == NULL)
1180 goto jerr;
1182 /* It seems there are invalid MBOX archives in the wild, compare
1183 * . http://bugs.debian.org/624111
1184 * . [Mutt] #3868: mutt should error if the imported mailbox is invalid
1185 * What they do is that they obfuscate the address to "name at host",
1186 * and even "name at host dot dom dot dom. I think we should handle that */
1187 else if(cp[0] == 'a' && cp[1] == 't' && cp[2] == ' '){
1188 rv = -1;
1189 cp += 3;
1190 jat_dot:
1191 cp = _from__skipword(cp);
1192 if (cp == NULL)
1193 goto jerr;
1194 if(cp[0] == 'd' && cp[1] == 'o' && cp[2] == 't' && cp[3] == ' '){
1195 cp += 4;
1196 goto jat_dot;
1200 linelen -= PTR2SIZE(cp - line);
1201 if (linelen < a_HEAD_DATE_MINLEN)
1202 goto jerr;
1203 if (cp[linelen - 1] == '\n') {
1204 --linelen;
1205 /* (Rather IMAP/POP3 only) */
1206 if (cp[linelen - 1] == '\r')
1207 --linelen;
1208 if (linelen < a_HEAD_DATE_MINLEN)
1209 goto jerr;
1211 if (linelen >= n_FROM_DATEBUF)
1212 goto jerr;
1214 jleave:
1215 memcpy(datebuf, cp, linelen);
1216 datebuf[linelen] = '\0';
1217 NYD_LEAVE;
1218 return rv;
1219 jerr:
1220 cp = _("<Unknown date>");
1221 linelen = strlen(cp);
1222 if (linelen >= n_FROM_DATEBUF)
1223 linelen = n_FROM_DATEBUF;
1224 rv = 0;
1225 goto jleave;
1228 FL void
1229 extract_header(FILE *fp, struct header *hp, si8_t *checkaddr_err)
1231 /* See the prototype declaration for the hairy relationship of
1232 * n_poption&n_PO_t_FLAG and/or n_psonce&n_PSO_t_FLAG in here */
1233 struct n_header_field **hftail;
1234 struct header nh, *hq = &nh;
1235 char *linebuf = NULL /* TODO line pool */, *colon;
1236 size_t linesize = 0, seenfields = 0;
1237 int lc, c;
1238 char const *val, *cp;
1239 NYD_ENTER;
1241 memset(hq, 0, sizeof *hq);
1242 if ((n_psonce & n_PSO_t_FLAG) && (n_poption & n_PO_t_FLAG)) {
1243 hq->h_to = hp->h_to;
1244 hq->h_cc = hp->h_cc;
1245 hq->h_bcc = hp->h_bcc;
1247 hftail = &hq->h_user_headers;
1249 for (lc = 0; readline_restart(fp, &linebuf, &linesize, 0) > 0; ++lc)
1252 /* TODO yippieia, cat(check(lextract)) :-) */
1253 rewind(fp);
1254 while ((lc = gethfield(fp, &linebuf, &linesize, lc, &colon)) >= 0) {
1255 struct name *np;
1257 /* We explicitly allow EAF_NAME for some addressees since aliases are not
1258 * yet expanded when we parse these! */
1259 if ((val = thisfield(linebuf, "to")) != NULL) {
1260 ++seenfields;
1261 hq->h_to = cat(hq->h_to, checkaddrs(lextract(val, GTO | GFULL),
1262 EACM_NORMAL | EAF_NAME | EAF_MAYKEEP, checkaddr_err));
1263 } else if ((val = thisfield(linebuf, "cc")) != NULL) {
1264 ++seenfields;
1265 hq->h_cc = cat(hq->h_cc, checkaddrs(lextract(val, GCC | GFULL),
1266 EACM_NORMAL | EAF_NAME | EAF_MAYKEEP, checkaddr_err));
1267 } else if ((val = thisfield(linebuf, "bcc")) != NULL) {
1268 ++seenfields;
1269 hq->h_bcc = cat(hq->h_bcc, checkaddrs(lextract(val, GBCC | GFULL),
1270 EACM_NORMAL | EAF_NAME | EAF_MAYKEEP, checkaddr_err));
1271 } else if ((val = thisfield(linebuf, "from")) != NULL) {
1272 if (!(n_psonce & n_PSO_t_FLAG) || (n_poption & n_PO_t_FLAG)) {
1273 ++seenfields;
1274 hq->h_from = cat(hq->h_from,
1275 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
1276 EACM_STRICT, NULL));
1278 } else if ((val = thisfield(linebuf, "reply-to")) != NULL) {
1279 ++seenfields;
1280 hq->h_replyto = cat(hq->h_replyto,
1281 checkaddrs(lextract(val, GEXTRA | GFULL), EACM_STRICT, NULL));
1282 } else if ((val = thisfield(linebuf, "sender")) != NULL) {
1283 if (!(n_psonce & n_PSO_t_FLAG) || (n_poption & n_PO_t_FLAG)) {
1284 ++seenfields;
1285 hq->h_sender = cat(hq->h_sender, /* TODO cat? check! */
1286 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
1287 EACM_STRICT, NULL));
1288 } else
1289 goto jebadhead;
1290 } else if ((val = thisfield(linebuf, "subject")) != NULL ||
1291 (val = thisfield(linebuf, "subj")) != NULL) {
1292 ++seenfields;
1293 for (cp = val; blankchar(*cp); ++cp)
1295 hq->h_subject = (hq->h_subject != NULL)
1296 ? save2str(hq->h_subject, cp) : savestr(cp);
1298 /* The remaining are mostly hacked in and thus TODO -- at least in
1299 * TODO respect to their content checking */
1300 else if((val = thisfield(linebuf, "message-id")) != NULL){
1301 if(n_psonce & n_PSO_t_FLAG){
1302 np = checkaddrs(lextract(val, GREF),
1303 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1304 NULL);
1305 if (np == NULL || np->n_flink != NULL)
1306 goto jebadhead;
1307 ++seenfields;
1308 hq->h_message_id = np;
1309 }else
1310 goto jebadhead;
1311 }else if((val = thisfield(linebuf, "in-reply-to")) != NULL){
1312 if(n_psonce & n_PSO_t_FLAG){
1313 np = checkaddrs(lextract(val, GREF),
1314 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1315 NULL);
1316 ++seenfields;
1317 hq->h_in_reply_to = np;
1318 }else
1319 goto jebadhead;
1320 }else if((val = thisfield(linebuf, "references")) != NULL){
1321 if(n_psonce & n_PSO_t_FLAG){
1322 ++seenfields;
1323 /* TODO Limit number of references TODO better on parser side */
1324 hq->h_ref = cat(hq->h_ref, checkaddrs(extract(val, GREF),
1325 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1326 NULL));
1327 }else
1328 goto jebadhead;
1330 /* and that is very hairy */
1331 else if((val = thisfield(linebuf, "mail-followup-to")) != NULL){
1332 if(n_psonce & n_PSO_t_FLAG){
1333 ++seenfields;
1334 hq->h_mft = cat(hq->h_mft, checkaddrs(lextract(val, GEXTRA | GFULL),
1335 /*EACM_STRICT | TODO '/' valid!! | EACM_NOLOG | */EACM_NONAME,
1336 checkaddr_err));
1337 }else
1338 goto jebadhead;
1340 /* A free-form user header; gethfield() did some verification already.. */
1341 else{
1342 struct n_header_field *hfp;
1343 ui32_t nl, bl;
1344 char const *nstart;
1346 for(nstart = cp = linebuf;; ++cp)
1347 if(!fieldnamechar(*cp))
1348 break;
1349 nl = (ui32_t)PTR2SIZE(cp - nstart);
1351 while(blankchar(*cp))
1352 ++cp;
1353 if(*cp++ != ':'){
1354 jebadhead:
1355 n_err(_("Ignoring header field: %s\n"), linebuf);
1356 continue;
1358 while(blankchar(*cp))
1359 ++cp;
1360 bl = (ui32_t)strlen(cp) +1;
1362 ++seenfields;
1363 *hftail = hfp = salloc(n_VSTRUCT_SIZEOF(struct n_header_field, hf_dat
1364 ) + nl +1 + bl);
1365 hftail = &hfp->hf_next;
1366 hfp->hf_next = NULL;
1367 hfp->hf_nl = nl;
1368 hfp->hf_bl = bl - 1;
1369 memcpy(hfp->hf_dat, nstart, nl);
1370 hfp->hf_dat[nl++] = '\0';
1371 memcpy(hfp->hf_dat + nl, cp, bl);
1375 /* In case the blank line after the header has been edited out. Otherwise,
1376 * fetch the header separator */
1377 if (linebuf != NULL) {
1378 if (linebuf[0] != '\0') {
1379 for (cp = linebuf; *(++cp) != '\0';)
1381 fseek(fp, (long)-PTR2SIZE(1 + cp - linebuf), SEEK_CUR);
1382 } else {
1383 if ((c = getc(fp)) != '\n' && c != EOF)
1384 ungetc(c, fp);
1388 if (seenfields > 0 && (checkaddr_err == NULL || *checkaddr_err == 0)) {
1389 hp->h_to = hq->h_to;
1390 hp->h_cc = hq->h_cc;
1391 hp->h_bcc = hq->h_bcc;
1392 hp->h_from = hq->h_from;
1393 hp->h_replyto = hq->h_replyto;
1394 hp->h_sender = hq->h_sender;
1395 if (hq->h_subject != NULL || !(n_psonce & n_PSO_t_FLAG) ||
1396 !(n_poption & n_PO_t_FLAG))
1397 hp->h_subject = hq->h_subject;
1398 hp->h_user_headers = hq->h_user_headers;
1400 if (n_psonce & n_PSO_t_FLAG) {
1401 hp->h_ref = hq->h_ref;
1402 hp->h_message_id = hq->h_message_id;
1403 hp->h_in_reply_to = hq->h_in_reply_to;
1404 hp->h_mft = hq->h_mft;
1406 /* And perform additional validity checks so that we don't bail later
1407 * on TODO this is good and the place where this should occur,
1408 * TODO unfortunately a lot of other places do again and blabla */
1409 if (hp->h_from == NULL)
1410 hp->h_from = n_poption_arg_r;
1411 else if (hp->h_from->n_flink != NULL && hp->h_sender == NULL)
1412 hp->h_sender = lextract(ok_vlook(sender),
1413 GEXTRA | GFULL | GFULLEXTRA);
1415 } else
1416 n_err(_("Restoring deleted header lines\n"));
1418 if (linebuf != NULL)
1419 free(linebuf);
1420 NYD_LEAVE;
1423 FL char *
1424 hfield_mult(char const *field, struct message *mp, int mult)
1426 FILE *ibuf;
1427 int lc;
1428 struct str hfs;
1429 size_t linesize = 0; /* TODO line pool */
1430 char *linebuf = NULL, *colon;
1431 char const *hfield;
1432 NYD_ENTER;
1434 /* There are (spam) messages which have header bytes which are many KB when
1435 * joined, so resize a single heap storage until we are done if we shall
1436 * collect a field that may have multiple bodies; only otherwise use the
1437 * string dope directly */
1438 memset(&hfs, 0, sizeof hfs);
1440 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
1441 goto jleave;
1442 if ((lc = mp->m_lines - 1) < 0)
1443 goto jleave;
1445 if ((mp->m_flag & MNOFROM) == 0 &&
1446 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1447 goto jleave;
1448 while (lc > 0) {
1449 if ((lc = gethfield(ibuf, &linebuf, &linesize, lc, &colon)) < 0)
1450 break;
1451 if ((hfield = thisfield(linebuf, field)) != NULL && *hfield != '\0') {
1452 if (mult)
1453 n_str_add_buf(&hfs, hfield, strlen(hfield));
1454 else {
1455 hfs.s = savestr(hfield);
1456 break;
1461 jleave:
1462 if (linebuf != NULL)
1463 free(linebuf);
1464 if (mult && hfs.s != NULL) {
1465 colon = savestrbuf(hfs.s, hfs.l);
1466 free(hfs.s);
1467 hfs.s = colon;
1469 NYD_LEAVE;
1470 return hfs.s;
1473 FL char const *
1474 thisfield(char const *linebuf, char const *field)
1476 char const *rv = NULL;
1477 NYD2_ENTER;
1479 while (lowerconv(*linebuf) == lowerconv(*field)) {
1480 ++linebuf;
1481 ++field;
1483 if (*field != '\0')
1484 goto jleave;
1486 while (blankchar(*linebuf))
1487 ++linebuf;
1488 if (*linebuf++ != ':')
1489 goto jleave;
1491 while (blankchar(*linebuf)) /* TODO header parser.. strip trailing WS?!? */
1492 ++linebuf;
1493 rv = linebuf;
1494 jleave:
1495 NYD2_LEAVE;
1496 return rv;
1499 FL char *
1500 nameof(struct message *mp, int reptype)
1502 char *cp, *cp2;
1503 NYD_ENTER;
1505 cp = skin(name1(mp, reptype));
1506 if (reptype != 0 || charcount(cp, '!') < 2)
1507 goto jleave;
1508 cp2 = strrchr(cp, '!');
1509 --cp2;
1510 while (cp2 > cp && *cp2 != '!')
1511 --cp2;
1512 if (*cp2 == '!')
1513 cp = cp2 + 1;
1514 jleave:
1515 NYD_LEAVE;
1516 return cp;
1519 FL char const *
1520 skip_comment(char const *cp)
1522 size_t nesting;
1523 NYD_ENTER;
1525 for (nesting = 1; nesting > 0 && *cp; ++cp) {
1526 switch (*cp) {
1527 case '\\':
1528 if (cp[1])
1529 ++cp;
1530 break;
1531 case '(':
1532 ++nesting;
1533 break;
1534 case ')':
1535 --nesting;
1536 break;
1539 NYD_LEAVE;
1540 return cp;
1543 FL char const *
1544 routeaddr(char const *name)
1546 char const *np, *rp = NULL;
1547 NYD_ENTER;
1549 for (np = name; *np; np++) {
1550 switch (*np) {
1551 case '(':
1552 np = skip_comment(np + 1) - 1;
1553 break;
1554 case '"':
1555 while (*np) {
1556 if (*++np == '"')
1557 break;
1558 if (*np == '\\' && np[1])
1559 np++;
1561 break;
1562 case '<':
1563 rp = np;
1564 break;
1565 case '>':
1566 goto jleave;
1569 rp = NULL;
1570 jleave:
1571 NYD_LEAVE;
1572 return rp;
1575 FL enum expand_addr_flags
1576 expandaddr_to_eaf(void)
1578 struct eafdesc {
1579 char const *eafd_name;
1580 bool_t eafd_is_target;
1581 ui8_t eafd_andoff;
1582 ui8_t eafd_or;
1583 } const eafa[] = {
1584 {"restrict", FAL0, EAF_TARGET_MASK, EAF_RESTRICT | EAF_RESTRICT_TARGETS},
1585 {"fail", FAL0, EAF_NONE, EAF_FAIL},
1586 {"failinvaddr", FAL0, EAF_NONE, EAF_FAILINVADDR | EAF_ADDR},
1587 {"all", TRU1, EAF_NONE, EAF_TARGET_MASK},
1588 {"file", TRU1, EAF_NONE, EAF_FILE},
1589 {"pipe", TRU1, EAF_NONE, EAF_PIPE},
1590 {"name", TRU1, EAF_NONE, EAF_NAME},
1591 {"addr", TRU1, EAF_NONE, EAF_ADDR}
1592 }, *eafp;
1594 char *buf;
1595 enum expand_addr_flags rv;
1596 char const *cp;
1597 NYD2_ENTER;
1599 if ((cp = ok_vlook(expandaddr)) == NULL)
1600 rv = EAF_RESTRICT_TARGETS;
1601 else if (*cp == '\0')
1602 rv = EAF_TARGET_MASK;
1603 else {
1604 rv = EAF_TARGET_MASK;
1606 for (buf = savestr(cp); (cp = n_strsep(&buf, ',', TRU1)) != NULL;) {
1607 bool_t minus;
1609 if ((minus = (*cp == '-')) || *cp == '+')
1610 ++cp;
1611 for (eafp = eafa;; ++eafp) {
1612 if (eafp == eafa + n_NELEM(eafa)) {
1613 if (n_poption & n_PO_D_V)
1614 n_err(_("Unknown *expandaddr* value: %s\n"), cp);
1615 break;
1616 } else if (!asccasecmp(cp, eafp->eafd_name)) {
1617 if (!minus) {
1618 rv &= ~eafp->eafd_andoff;
1619 rv |= eafp->eafd_or;
1620 } else {
1621 if (eafp->eafd_is_target)
1622 rv &= ~eafp->eafd_or;
1623 else if (n_poption & n_PO_D_V)
1624 n_err(_("minus - prefix invalid for *expandaddr* value: "
1625 "%s\n"), --cp);
1627 break;
1628 } else if (!asccasecmp(cp, "noalias")) { /* TODO v15 OBSOLETE */
1629 n_OBSOLETE(_("*expandaddr*: noalias is henceforth -name"));
1630 rv &= ~EAF_NAME;
1631 break;
1636 if((rv & EAF_RESTRICT) && ((n_psonce & n_PSO_INTERACTIVE) ||
1637 (n_poption & n_PO_TILDE_FLAG)))
1638 rv |= EAF_TARGET_MASK;
1639 else if(n_poption & n_PO_D_V){
1640 if(!(rv & EAF_TARGET_MASK))
1641 n_err(_("*expandaddr* doesn't allow any addressees\n"));
1642 else if((rv & EAF_FAIL) && (rv & EAF_TARGET_MASK) == EAF_TARGET_MASK)
1643 n_err(_("*expandaddr* with fail, but no restrictions to apply\n"));
1646 NYD2_LEAVE;
1647 return rv;
1650 FL si8_t
1651 is_addr_invalid(struct name *np, enum expand_addr_check_mode eacm)
1653 char cbuf[sizeof "'\\U12340'"];
1654 char const *cs;
1655 int f;
1656 si8_t rv;
1657 enum expand_addr_flags eaf;
1658 NYD_ENTER;
1660 eaf = expandaddr_to_eaf();
1661 f = np->n_flags;
1663 if ((rv = ((f & NAME_ADDRSPEC_INVALID) != 0))) {
1664 if (eaf & EAF_FAILINVADDR)
1665 rv = -rv;
1667 if ((eacm & EACM_NOLOG) || (f & NAME_ADDRSPEC_ERR_EMPTY)) {
1669 } else {
1670 ui32_t c;
1671 char const *fmt = "'\\x%02X'";
1672 bool_t ok8bit = TRU1;
1674 if (f & NAME_ADDRSPEC_ERR_IDNA) {
1675 cs = _("Invalid domain name: %s, character %s\n");
1676 fmt = "'\\U%04X'";
1677 ok8bit = FAL0;
1678 } else if (f & NAME_ADDRSPEC_ERR_ATSEQ)
1679 cs = _("%s contains invalid %s sequence\n");
1680 else if (f & NAME_ADDRSPEC_ERR_NAME) {
1681 cs = _("%s is an invalid alias name\n");
1682 } else
1683 cs = _("%s contains invalid byte %s\n");
1685 c = NAME_ADDRSPEC_ERR_GETWC(f);
1686 snprintf(cbuf, sizeof cbuf,
1687 (ok8bit && c >= 040 && c <= 0177 ? "'%c'" : fmt), c);
1688 goto jprint;
1690 goto jleave;
1693 /* *expandaddr* stuff */
1694 if (!(rv = ((eacm & EACM_MODE_MASK) != EACM_NONE)))
1695 goto jleave;
1697 if ((eacm & EACM_STRICT) && (f & NAME_ADDRSPEC_ISFILEORPIPE)) {
1698 if (eaf & EAF_FAIL)
1699 rv = -rv;
1700 cs = _("%s%s: file or pipe addressees not allowed here\n");
1701 if (eacm & EACM_NOLOG)
1702 goto jleave;
1703 else
1704 goto j0print;
1707 eaf |= (eacm & EAF_TARGET_MASK);
1708 if (eacm & EACM_NONAME)
1709 eaf &= ~EAF_NAME;
1711 if (eaf == EAF_NONE) {
1712 rv = FAL0;
1713 goto jleave;
1715 if (eaf & EAF_FAIL)
1716 rv = -rv;
1718 if (!(eaf & EAF_FILE) && (f & NAME_ADDRSPEC_ISFILE)) {
1719 cs = _("%s%s: *expandaddr* doesn't allow file target\n");
1720 if (eacm & EACM_NOLOG)
1721 goto jleave;
1722 } else if (!(eaf & EAF_PIPE) && (f & NAME_ADDRSPEC_ISPIPE)) {
1723 cs = _("%s%s: *expandaddr* doesn't allow command pipe target\n");
1724 if (eacm & EACM_NOLOG)
1725 goto jleave;
1726 } else if (!(eaf & EAF_NAME) && (f & NAME_ADDRSPEC_ISNAME)) {
1727 cs = _("%s%s: *expandaddr* doesn't allow user name target\n");
1728 if (eacm & EACM_NOLOG)
1729 goto jleave;
1730 } else if (!(eaf & EAF_ADDR) && (f & NAME_ADDRSPEC_ISADDR)) {
1731 cs = _("%s%s: *expandaddr* doesn't allow mail address target\n");
1732 if (eacm & EACM_NOLOG)
1733 goto jleave;
1734 } else {
1735 rv = FAL0;
1736 goto jleave;
1739 j0print:
1740 cbuf[0] = '\0';
1741 jprint:
1742 n_err(cs, n_shexp_quote_cp(np->n_name, TRU1), cbuf);
1743 jleave:
1744 NYD_LEAVE;
1745 return rv;
1748 FL char *
1749 skin(char const *name)
1751 struct n_addrguts ag;
1752 char *rv;
1753 NYD_ENTER;
1755 if(name != NULL){
1756 name = n_addrspec_with_guts(&ag,name, TRU1, FAL0);
1757 rv = ag.ag_skinned;
1758 if(!(ag.ag_n_flags & NAME_NAME_SALLOC))
1759 rv = savestrbuf(rv, ag.ag_slen);
1760 }else
1761 rv = NULL;
1762 NYD_LEAVE;
1763 return rv;
1766 /* TODO addrspec_with_guts: RFC 5322
1767 * TODO addrspec_with_guts: trim whitespace ETC. ETC. ETC.!!! */
1768 FL char const *
1769 n_addrspec_with_guts(struct n_addrguts *agp, char const *name, bool_t doskin,
1770 bool_t issingle_hack){
1771 char const *cp;
1772 char *cp2, *bufend, *nbuf, c;
1773 enum{
1774 a_NONE,
1775 a_GOTLT = 1<<0,
1776 a_GOTADDR = 1<<1,
1777 a_GOTSPACE = 1<<2,
1778 a_LASTSP = 1<<3
1779 } flags;
1780 NYD_ENTER;
1782 memset(agp, 0, sizeof *agp);
1784 if((agp->ag_input = name) == NULL || (agp->ag_ilen = strlen(name)) == 0){
1785 agp->ag_skinned = n_UNCONST(n_empty); /* ok: NAME_SALLOC is not set */
1786 agp->ag_slen = 0;
1787 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
1788 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
1789 goto jleave;
1790 }else if(!doskin){
1791 /*agp->ag_iaddr_start = 0;*/
1792 agp->ag_iaddr_aend = agp->ag_ilen;
1793 agp->ag_skinned = n_UNCONST(name); /* (NAME_SALLOC not set) */
1794 agp->ag_slen = agp->ag_ilen;
1795 agp->ag_n_flags = NAME_SKINNED;
1796 goto jcheck;
1799 flags = a_NONE;
1800 nbuf = n_lofi_alloc(agp->ag_ilen +1);
1801 /*agp->ag_iaddr_start = 0;*/
1802 cp2 = bufend = nbuf;
1804 /* TODO This is complete crap and should use a token parser */
1805 for(cp = name++; (c = *cp++) != '\0';){
1806 switch (c) {
1807 case '(':
1808 cp = skip_comment(cp);
1809 flags &= ~a_LASTSP;
1810 break;
1811 case '"':
1812 /* Start of a "quoted-string". Copy it in its entirety */
1813 /* XXX RFC: quotes are "semantically invisible"
1814 * XXX But it was explicitly added (Changelog.Heirloom,
1815 * XXX [9.23] released 11/15/00, "Do not remove quotes
1816 * XXX when skinning names"? No more info.. */
1817 *cp2++ = c;
1818 while ((c = *cp) != '\0') { /* TODO improve */
1819 ++cp;
1820 if (c == '"') {
1821 *cp2++ = c;
1822 break;
1824 if (c != '\\')
1825 *cp2++ = c;
1826 else if ((c = *cp) != '\0') {
1827 *cp2++ = c;
1828 ++cp;
1831 flags &= ~a_LASTSP;
1832 break;
1833 case ' ':
1834 case '\t':
1835 if((flags & (a_GOTADDR | a_GOTSPACE)) == a_GOTADDR){
1836 flags |= a_GOTSPACE;
1837 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1839 if (cp[0] == 'a' && cp[1] == 't' && blankchar(cp[2]))
1840 cp += 3, *cp2++ = '@';
1841 else if (cp[0] == '@' && blankchar(cp[1]))
1842 cp += 2, *cp2++ = '@';
1843 else
1844 flags |= a_LASTSP;
1845 break;
1846 case '<':
1847 agp->ag_iaddr_start = PTR2SIZE(cp - (name - 1));
1848 cp2 = bufend;
1849 flags &= ~(a_GOTSPACE | a_LASTSP);
1850 flags |= a_GOTLT | a_GOTADDR;
1851 break;
1852 case '>':
1853 if(flags & a_GOTLT){
1854 /* (_addrspec_check() verifies these later!) */
1855 flags &= ~(a_GOTLT | a_LASTSP);
1856 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1858 /* Skip over the entire remaining field */
1859 while((c = *cp) != '\0' && c != ','){
1860 ++cp;
1861 if (c == '(')
1862 cp = skip_comment(cp);
1863 else if (c == '"')
1864 while ((c = *cp) != '\0') {
1865 ++cp;
1866 if (c == '"')
1867 break;
1868 if (c == '\\' && *cp != '\0')
1869 ++cp;
1872 break;
1874 /* FALLTHRU */
1875 default:
1876 if(flags & a_LASTSP){
1877 flags &= ~a_LASTSP;
1878 if(flags & a_GOTADDR)
1879 *cp2++ = ' ';
1881 *cp2++ = c;
1882 /* This character is forbidden here, but it may nonetheless be
1883 * present: ensure we turn this into something valid! (E.g., if the
1884 * next character would be a "..) */
1885 if(c == '\\' && *cp != '\0')
1886 *cp2++ = *cp++;
1887 if(c == ',' && !issingle_hack){
1888 if(!(flags & a_GOTLT)){
1889 *cp2++ = ' ';
1890 for(; blankchar(*cp); ++cp)
1892 flags &= ~a_LASTSP;
1893 bufend = cp2;
1895 }else if(!(flags & a_GOTADDR)){
1896 flags |= a_GOTADDR;
1897 agp->ag_iaddr_start = PTR2SIZE(cp - name);
1901 --name;
1902 agp->ag_slen = PTR2SIZE(cp2 - nbuf);
1903 if (agp->ag_iaddr_aend == 0)
1904 agp->ag_iaddr_aend = agp->ag_ilen;
1905 /* Misses > */
1906 else if (agp->ag_iaddr_aend < agp->ag_iaddr_start) {
1907 cp2 = n_autorec_alloc(agp->ag_ilen + 1 +1);
1908 memcpy(cp2, agp->ag_input, agp->ag_ilen);
1909 agp->ag_iaddr_aend = agp->ag_ilen;
1910 cp2[agp->ag_ilen++] = '>';
1911 cp2[agp->ag_ilen] = '\0';
1913 agp->ag_skinned = savestrbuf(nbuf, agp->ag_slen);
1914 n_lofi_free(nbuf);
1915 agp->ag_n_flags = NAME_NAME_SALLOC | NAME_SKINNED;
1916 jcheck:
1917 if(a_head_addrspec_check(agp, doskin) <= FAL0)
1918 name = NULL;
1919 else
1920 name = agp->ag_input;
1921 jleave:
1922 NYD_LEAVE;
1923 return name;
1926 FL char *
1927 realname(char const *name)
1929 char const *cp, *cq, *cstart = NULL, *cend = NULL;
1930 char *rname, *rp;
1931 struct str in, out;
1932 int quoted, good, nogood;
1933 NYD_ENTER;
1935 if ((cp = n_UNCONST(name)) == NULL)
1936 goto jleave;
1937 for (; *cp != '\0'; ++cp) {
1938 switch (*cp) {
1939 case '(':
1940 if (cstart != NULL) {
1941 /* More than one comment in address, doesn't make sense to display
1942 * it without context. Return the entire field */
1943 cp = mime_fromaddr(name);
1944 goto jleave;
1946 cstart = cp++;
1947 cp = skip_comment(cp);
1948 cend = cp--;
1949 if (cend <= cstart)
1950 cend = cstart = NULL;
1951 break;
1952 case '"':
1953 while (*cp) {
1954 if (*++cp == '"')
1955 break;
1956 if (*cp == '\\' && cp[1])
1957 ++cp;
1959 break;
1960 case '<':
1961 if (cp > name) {
1962 cstart = name;
1963 cend = cp;
1965 break;
1966 case ',':
1967 /* More than one address. Just use the first one */
1968 goto jbrk;
1972 jbrk:
1973 if (cstart == NULL) {
1974 if (*name == '<') {
1975 /* If name contains only a route-addr, the surrounding angle brackets
1976 * don't serve any useful purpose when displaying, so remove */
1977 cp = prstr(skin(name));
1978 } else
1979 cp = mime_fromaddr(name);
1980 goto jleave;
1983 /* Strip quotes. Note that quotes that appear within a MIME encoded word are
1984 * not stripped. The idea is to strip only syntactical relevant things (but
1985 * this is not necessarily the most sensible way in practice) */
1986 rp = rname = ac_alloc(PTR2SIZE(cend - cstart +1));
1987 quoted = 0;
1988 for (cp = cstart; cp < cend; ++cp) {
1989 if (*cp == '(' && !quoted) {
1990 cq = skip_comment(++cp);
1991 if (PTRCMP(--cq, >, cend))
1992 cq = cend;
1993 while (cp < cq) {
1994 if (*cp == '\\' && PTRCMP(cp + 1, <, cq))
1995 ++cp;
1996 *rp++ = *cp++;
1998 } else if (*cp == '\\' && PTRCMP(cp + 1, <, cend))
1999 *rp++ = *++cp;
2000 else if (*cp == '"') {
2001 quoted = !quoted;
2002 continue;
2003 } else
2004 *rp++ = *cp;
2006 *rp = '\0';
2007 in.s = rname;
2008 in.l = rp - rname;
2009 mime_fromhdr(&in, &out, TD_ISPR | TD_ICONV);
2010 ac_free(rname);
2011 rname = savestr(out.s);
2012 free(out.s);
2014 while (blankchar(*rname))
2015 ++rname;
2016 for (rp = rname; *rp != '\0'; ++rp)
2018 while (PTRCMP(--rp, >=, rname) && blankchar(*rp))
2019 *rp = '\0';
2020 if (rp == rname) {
2021 cp = mime_fromaddr(name);
2022 goto jleave;
2025 /* mime_fromhdr() has converted all nonprintable characters to question
2026 * marks now. These and blanks are considered uninteresting; if the
2027 * displayed part of the real name contains more than 25% of them, it is
2028 * probably better to display the plain email address instead */
2029 good = 0;
2030 nogood = 0;
2031 for (rp = rname; *rp != '\0' && PTRCMP(rp, <, rname + 20); ++rp)
2032 if (*rp == '?' || blankchar(*rp))
2033 ++nogood;
2034 else
2035 ++good;
2036 cp = (good * 3 < nogood) ? prstr(skin(name)) : rname;
2037 jleave:
2038 NYD_LEAVE;
2039 return n_UNCONST(cp);
2042 FL char *
2043 name1(struct message *mp, int reptype)
2045 char *namebuf, *cp, *cp2, *linebuf = NULL /* TODO line pool */;
2046 size_t namesize, linesize = 0;
2047 FILE *ibuf;
2048 int f1st = 1;
2049 NYD_ENTER;
2051 if ((cp = hfield1("from", mp)) != NULL && *cp != '\0')
2052 goto jleave;
2053 if (reptype == 0 && (cp = hfield1("sender", mp)) != NULL && *cp != '\0')
2054 goto jleave;
2056 namebuf = smalloc(namesize = 1);
2057 namebuf[0] = 0;
2058 if (mp->m_flag & MNOFROM)
2059 goto jout;
2060 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2061 goto jout;
2062 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2063 goto jout;
2065 jnewname:
2066 if (namesize <= linesize)
2067 namebuf = srealloc(namebuf, namesize = linesize +1);
2068 for (cp = linebuf; *cp != '\0' && *cp != ' '; ++cp)
2070 for (; blankchar(*cp); ++cp)
2072 for (cp2 = namebuf + strlen(namebuf);
2073 *cp && !blankchar(*cp) && PTRCMP(cp2, <, namebuf + namesize -1);)
2074 *cp2++ = *cp++;
2075 *cp2 = '\0';
2077 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2078 goto jout;
2079 if ((cp = strchr(linebuf, 'F')) == NULL)
2080 goto jout;
2081 if (strncmp(cp, "From", 4))
2082 goto jout;
2083 if (namesize <= linesize)
2084 namebuf = srealloc(namebuf, namesize = linesize + 1);
2086 while ((cp = strchr(cp, 'r')) != NULL) {
2087 if (!strncmp(cp, "remote", 6)) {
2088 if ((cp = strchr(cp, 'f')) == NULL)
2089 break;
2090 if (strncmp(cp, "from", 4) != 0)
2091 break;
2092 if ((cp = strchr(cp, ' ')) == NULL)
2093 break;
2094 cp++;
2095 if (f1st) {
2096 strncpy(namebuf, cp, namesize);
2097 f1st = 0;
2098 } else {
2099 cp2 = strrchr(namebuf, '!') + 1;
2100 strncpy(cp2, cp, PTR2SIZE(namebuf + namesize - cp2));
2102 namebuf[namesize - 2] = '!';
2103 namebuf[namesize - 1] = '\0';
2104 goto jnewname;
2106 cp++;
2108 jout:
2109 if (*namebuf != '\0' || ((cp = hfield1("return-path", mp))) == NULL ||
2110 *cp == '\0')
2111 cp = savestr(namebuf);
2113 if (linebuf != NULL)
2114 free(linebuf);
2115 free(namebuf);
2116 jleave:
2117 NYD_LEAVE;
2118 return cp;
2121 FL char const *
2122 subject_re_trim(char const *s){
2123 struct{
2124 ui8_t len;
2125 char dat[7];
2126 }const *pp, ignored[] = { /* Update *reply-strings* manual upon change! */
2127 {3, "re:"},
2128 {3, "aw:"}, {5, "antw:"}, /* de */
2129 {3, "wg:"}, /* Seen too often in the wild */
2130 {0, ""}
2133 bool_t any;
2134 char *re_st, *re_st_x;
2135 char const *orig_s;
2136 size_t re_l;
2137 NYD_ENTER;
2139 any = FAL0;
2140 orig_s = s;
2141 re_st = NULL;
2142 n_UNINIT(re_l, 0);
2144 if((re_st_x = ok_vlook(reply_strings)) != NULL &&
2145 (re_l = strlen(re_st_x)) > 0){
2146 re_st = n_lofi_alloc(++re_l * 2);
2147 memcpy(re_st, re_st_x, re_l);
2150 jouter:
2151 while(*s != '\0'){
2152 while(spacechar(*s))
2153 ++s;
2155 for(pp = ignored; pp->len > 0; ++pp)
2156 if(is_asccaseprefix(pp->dat, s)){
2157 s += pp->len;
2158 any = TRU1;
2159 goto jouter;
2162 if(re_st != NULL){
2163 char *cp;
2165 memcpy(re_st_x = &re_st[re_l], re_st, re_l);
2166 while((cp = n_strsep(&re_st_x, ',', TRU1)) != NULL)
2167 if(is_asccaseprefix(cp, s)){
2168 s += strlen(cp);
2169 any = TRU1;
2170 goto jouter;
2173 break;
2176 if(re_st != NULL)
2177 n_lofi_free(re_st);
2178 NYD_LEAVE;
2179 return any ? s : orig_s;
2182 FL int
2183 msgidcmp(char const *s1, char const *s2)
2185 int q1 = 0, q2 = 0, c1, c2;
2186 NYD_ENTER;
2188 while(*s1 == '<')
2189 ++s1;
2190 while(*s2 == '<')
2191 ++s2;
2193 do {
2194 c1 = msgidnextc(&s1, &q1);
2195 c2 = msgidnextc(&s2, &q2);
2196 if (c1 != c2)
2197 break;
2198 } while (c1 && c2);
2199 NYD_LEAVE;
2200 return c1 - c2;
2203 FL char const *
2204 fakefrom(struct message *mp)
2206 char const *name;
2207 NYD_ENTER;
2209 if (((name = skin(hfield1("return-path", mp))) == NULL || *name == '\0' ) &&
2210 ((name = skin(hfield1("from", mp))) == NULL || *name == '\0'))
2211 /* XXX MAILER-DAEMON is what an old MBOX manual page says.
2212 * RFC 4155 however requires a RFC 5322 (2822) conforming
2213 * "addr-spec", but we simply can't provide that */
2214 name = "MAILER-DAEMON";
2215 NYD_LEAVE;
2216 return name;
2219 FL char const *
2220 fakedate(time_t t)
2222 char *cp, *cq;
2223 NYD_ENTER;
2225 cp = ctime(&t);
2226 for (cq = cp; *cq != '\0' && *cq != '\n'; ++cq)
2228 *cq = '\0';
2229 cp = savestr(cp);
2230 NYD_LEAVE;
2231 return cp;
2234 #ifdef HAVE_IMAP_SEARCH
2235 FL time_t
2236 unixtime(char const *fromline)
2238 char const *fp, *xp;
2239 time_t t;
2240 si32_t i, year, month, day, hour, minute, second, tzdiff;
2241 struct tm *tmptr;
2242 NYD2_ENTER;
2244 for (fp = fromline; *fp != '\0' && *fp != '\n'; ++fp)
2246 fp -= 24;
2247 if (PTR2SIZE(fp - fromline) < 7)
2248 goto jinvalid;
2249 if (fp[3] != ' ')
2250 goto jinvalid;
2251 for (i = 0;;) {
2252 if (!strncmp(fp + 4, n_month_names[i], 3))
2253 break;
2254 if (n_month_names[++i][0] == '\0')
2255 goto jinvalid;
2257 month = i + 1;
2258 if (fp[7] != ' ')
2259 goto jinvalid;
2260 n_idec_si32_cp(&day, &fp[8], 10, &xp);
2261 if (*xp != ' ' || xp != fp + 10)
2262 goto jinvalid;
2263 n_idec_si32_cp(&hour, &fp[11], 10, &xp);
2264 if (*xp != ':' || xp != fp + 13)
2265 goto jinvalid;
2266 n_idec_si32_cp(&minute, &fp[14], 10, &xp);
2267 if (*xp != ':' || xp != fp + 16)
2268 goto jinvalid;
2269 n_idec_si32_cp(&second, &fp[17], 10, &xp);
2270 if (*xp != ' ' || xp != fp + 19)
2271 goto jinvalid;
2272 n_idec_si32_cp(&year, &fp[20], 10, &xp);
2273 if (xp != fp + 24)
2274 goto jinvalid;
2275 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
2276 goto jinvalid;
2277 tzdiff = t - mktime(gmtime(&t));
2278 tmptr = localtime(&t);
2279 if (tmptr->tm_isdst > 0)
2280 tzdiff += 3600;
2281 t -= tzdiff;
2282 jleave:
2283 NYD2_LEAVE;
2284 return t;
2285 jinvalid:
2286 t = n_time_epoch();
2287 goto jleave;
2289 #endif /* HAVE_IMAP_SEARCH */
2291 FL time_t
2292 rfctime(char const *date) /* TODO n_idec_ return tests */
2294 char const *cp, *x;
2295 time_t t;
2296 si32_t i, year, month, day, hour, minute, second;
2297 NYD2_ENTER;
2299 cp = date;
2301 if ((cp = nexttoken(cp)) == NULL)
2302 goto jinvalid;
2303 if (alphachar(cp[0]) && alphachar(cp[1]) && alphachar(cp[2]) &&
2304 cp[3] == ',') {
2305 if ((cp = nexttoken(&cp[4])) == NULL)
2306 goto jinvalid;
2308 n_idec_si32_cp(&day, cp, 10, &x);
2309 if ((cp = nexttoken(x)) == NULL)
2310 goto jinvalid;
2311 for (i = 0;;) {
2312 if (!strncmp(cp, n_month_names[i], 3))
2313 break;
2314 if (n_month_names[++i][0] == '\0')
2315 goto jinvalid;
2317 month = i + 1;
2318 if ((cp = nexttoken(&cp[3])) == NULL)
2319 goto jinvalid;
2320 /* RFC 5322, 4.3:
2321 * Where a two or three digit year occurs in a date, the year is to be
2322 * interpreted as follows: If a two digit year is encountered whose
2323 * value is between 00 and 49, the year is interpreted by adding 2000,
2324 * ending up with a value between 2000 and 2049. If a two digit year
2325 * is encountered with a value between 50 and 99, or any three digit
2326 * year is encountered, the year is interpreted by adding 1900 */
2327 n_idec_si32_cp(&year, cp, 10, &x);
2328 i = (int)PTR2SIZE(x - cp);
2329 if (i == 2 && year >= 0 && year <= 49)
2330 year += 2000;
2331 else if (i == 3 || (i == 2 && year >= 50 && year <= 99))
2332 year += 1900;
2333 if ((cp = nexttoken(x)) == NULL)
2334 goto jinvalid;
2335 n_idec_si32_cp(&hour, cp, 10, &x);
2336 if (*x != ':')
2337 goto jinvalid;
2338 cp = &x[1];
2339 n_idec_si32_cp(&minute, cp, 10, &x);
2340 if (*x == ':') {
2341 cp = &x[1];
2342 n_idec_si32_cp(&second, cp, 10, &x);
2343 } else
2344 second = 0;
2346 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
2347 goto jinvalid;
2348 if ((cp = nexttoken(x)) != NULL) {
2349 char buf[3];
2350 int sign = 1;
2352 switch (*cp) {
2353 case '+':
2354 sign = -1;
2355 /* FALLTHRU */
2356 case '-':
2357 ++cp;
2358 break;
2360 if (digitchar(cp[0]) && digitchar(cp[1]) && digitchar(cp[2]) &&
2361 digitchar(cp[3])) {
2362 si64_t tadj;
2364 buf[2] = '\0';
2365 buf[0] = cp[0];
2366 buf[1] = cp[1];
2367 n_idec_si32_cp(&i, buf, 10, NULL);
2368 tadj = (si64_t)i * 3600; /* XXX */
2369 buf[0] = cp[2];
2370 buf[1] = cp[3];
2371 n_idec_si32_cp(&i, buf, 10, NULL);
2372 tadj += (si64_t)i * 60; /* XXX */
2373 if (sign < 0)
2374 tadj = -tadj;
2375 t += (time_t)tadj;
2377 /* TODO WE DO NOT YET PARSE (OBSOLETE) ZONE NAMES
2378 * TODO once again, Christos Zoulas and NetBSD Mail have done
2379 * TODO a really good job already, but using strptime(3), which
2380 * TODO is not portable. Nonetheless, WE must improve, not
2381 * TODO at last because we simply ignore obsolete timezones!!
2382 * TODO See RFC 5322, 4.3! */
2384 jleave:
2385 NYD2_LEAVE;
2386 return t;
2387 jinvalid:
2388 t = 0;
2389 goto jleave;
2392 FL time_t
2393 combinetime(int year, int month, int day, int hour, int minute, int second){
2394 size_t const jdn_epoch = 2440588;
2395 bool_t const y2038p = (sizeof(time_t) == 4);
2397 size_t jdn;
2398 time_t t;
2399 NYD2_ENTER;
2401 if(UICMP(32, second, >/*XXX leap=*/, n_DATE_SECSMIN) ||
2402 UICMP(32, minute, >=, n_DATE_MINSHOUR) ||
2403 UICMP(32, hour, >=, n_DATE_HOURSDAY) ||
2404 day < 1 || day > 31 ||
2405 month < 1 || month > 12 ||
2406 year < 1970)
2407 goto jerr;
2409 if(year >= 1970 + ((y2038p ? SI32_MAX : SI64_MAX) /
2410 (n_DATE_SECSDAY * n_DATE_DAYSYEAR))){
2411 /* Be a coward regarding Y2038, many people (mostly myself, that is) do
2412 * test by stepping second-wise around the flip. Don't care otherwise */
2413 if(!y2038p)
2414 goto jerr;
2415 if(year > 2038 || month > 1 || day > 19 ||
2416 hour > 3 || minute > 14 || second > 7)
2417 goto jerr;
2420 t = second;
2421 t += minute * n_DATE_SECSMIN;
2422 t += hour * n_DATE_SECSHOUR;
2424 jdn = a_head_gregorian_to_jdn(year, month, day);
2425 jdn -= jdn_epoch;
2426 t += (time_t)jdn * n_DATE_SECSDAY;
2427 jleave:
2428 NYD2_LEAVE;
2429 return t;
2430 jerr:
2431 t = (time_t)-1;
2432 goto jleave;
2435 FL void
2436 substdate(struct message *m)
2438 char const *cp;
2439 NYD_ENTER;
2441 /* Determine the date to print in faked 'From ' lines. This is traditionally
2442 * the date the message was written to the mail file. Try to determine this
2443 * using RFC message header fields, or fall back to current time */
2444 if ((cp = hfield1("received", m)) != NULL) {
2445 while ((cp = nexttoken(cp)) != NULL && *cp != ';') {
2447 ++cp;
2448 while (alnumchar(*cp));
2450 if (cp && *++cp)
2451 m->m_time = rfctime(cp);
2453 if (m->m_time == 0 || m->m_time > time_current.tc_time) {
2454 if ((cp = hfield1("date", m)) != NULL)
2455 m->m_time = rfctime(cp);
2457 if (m->m_time == 0 || m->m_time > time_current.tc_time)
2458 m->m_time = time_current.tc_time;
2459 NYD_LEAVE;
2462 FL void
2463 setup_from_and_sender(struct header *hp)
2465 char const *addr;
2466 struct name *np;
2467 NYD_ENTER;
2469 /* If -t parsed or composed From: then take it. With -t we otherwise
2470 * want -r to be honoured in favour of *from* in order to have
2471 * a behaviour that is compatible with what users would expect from e.g.
2472 * postfix(1) */
2473 if ((np = hp->h_from) != NULL ||
2474 ((n_psonce & n_PSO_t_FLAG) && (np = n_poption_arg_r) != NULL)) {
2476 } else if ((addr = myaddrs(hp)) != NULL)
2477 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
2478 hp->h_from = np;
2480 if ((np = hp->h_sender) != NULL) {
2482 } else if ((addr = ok_vlook(sender)) != NULL)
2483 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
2484 hp->h_sender = np;
2486 NYD_LEAVE;
2489 FL struct name const *
2490 check_from_and_sender(struct name const *fromfield,
2491 struct name const *senderfield)
2493 struct name const *rv = NULL;
2494 NYD_ENTER;
2496 if (senderfield != NULL) {
2497 if (senderfield->n_flink != NULL) {
2498 n_err(_("The Sender: field may contain only one address\n"));
2499 goto jleave;
2501 rv = senderfield;
2504 if (fromfield != NULL) {
2505 if (fromfield->n_flink != NULL && senderfield == NULL) {
2506 n_err(_("A Sender: is required when there are multiple "
2507 "addresses in From:\n"));
2508 goto jleave;
2510 if (rv == NULL)
2511 rv = fromfield;
2514 if (rv == NULL)
2515 rv = (struct name*)0x1;
2516 jleave:
2517 NYD_LEAVE;
2518 return rv;
2521 #ifdef HAVE_XSSL
2522 FL char *
2523 getsender(struct message *mp)
2525 char *cp;
2526 struct name *np;
2527 NYD_ENTER;
2529 if ((cp = hfield1("from", mp)) == NULL ||
2530 (np = lextract(cp, GEXTRA | GSKIN)) == NULL)
2531 cp = NULL;
2532 else
2533 cp = (np->n_flink != NULL) ? skin(hfield1("sender", mp)) : np->n_name;
2534 NYD_LEAVE;
2535 return cp;
2537 #endif
2539 FL int
2540 grab_headers(enum n_go_input_flags gif, struct header *hp, enum gfield gflags,
2541 int subjfirst)
2543 /* TODO grab_headers: again, check counts etc. against RFC;
2544 * TODO (now assumes check_from_and_sender() is called afterwards ++ */
2545 int errs;
2546 int volatile comma;
2547 NYD_ENTER;
2549 errs = 0;
2550 comma = (ok_blook(bsdcompat) || ok_blook(bsdmsgs)) ? 0 : GCOMMA;
2552 if (gflags & GTO)
2553 hp->h_to = grab_names(gif, "To: ", hp->h_to, comma, GTO | GFULL);
2554 if (subjfirst && (gflags & GSUBJECT))
2555 hp->h_subject = n_go_input_cp(gif, "Subject: ", hp->h_subject);
2556 if (gflags & GCC)
2557 hp->h_cc = grab_names(gif, "Cc: ", hp->h_cc, comma, GCC | GFULL);
2558 if (gflags & GBCC)
2559 hp->h_bcc = grab_names(gif, "Bcc: ", hp->h_bcc, comma, GBCC | GFULL);
2561 if (gflags & GEXTRA) {
2562 if (hp->h_from == NULL)
2563 hp->h_from = lextract(myaddrs(hp), GEXTRA | GFULL | GFULLEXTRA);
2564 hp->h_from = grab_names(gif, "From: ", hp->h_from, comma,
2565 GEXTRA | GFULL | GFULLEXTRA);
2566 if (hp->h_replyto == NULL)
2567 hp->h_replyto = lextract(ok_vlook(replyto), GEXTRA | GFULL);
2568 hp->h_replyto = grab_names(gif, "Reply-To: ", hp->h_replyto, comma,
2569 GEXTRA | GFULL);
2570 if (hp->h_sender == NULL)
2571 hp->h_sender = extract(ok_vlook(sender), GEXTRA | GFULL);
2572 hp->h_sender = grab_names(gif, "Sender: ", hp->h_sender, comma,
2573 GEXTRA | GFULL);
2576 if (!subjfirst && (gflags & GSUBJECT))
2577 hp->h_subject = n_go_input_cp(gif, "Subject: ", hp->h_subject);
2579 NYD_LEAVE;
2580 return errs;
2583 FL bool_t
2584 header_match(struct message *mp, struct search_expr const *sep)
2586 struct str in, out;
2587 FILE *ibuf;
2588 int lc;
2589 size_t linesize = 0; /* TODO line pool */
2590 char *linebuf = NULL, *colon;
2591 bool_t rv = FAL0;
2592 NYD_ENTER;
2594 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2595 goto jleave;
2596 if ((lc = mp->m_lines - 1) < 0)
2597 goto jleave;
2599 if ((mp->m_flag & MNOFROM) == 0 &&
2600 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2601 goto jleave;
2602 while (lc > 0) {
2603 if (gethfield(ibuf, &linebuf, &linesize, lc, &colon) <= 0)
2604 break;
2605 if (blankchar(*++colon))
2606 ++colon;
2607 in.l = strlen(in.s = colon);
2608 mime_fromhdr(&in, &out, TD_ICONV);
2609 #ifdef HAVE_REGEX
2610 if (sep->ss_sexpr == NULL)
2611 rv = (regexec(&sep->ss_regex, out.s, 0,NULL, 0) != REG_NOMATCH);
2612 else
2613 #endif
2614 rv = substr(out.s, sep->ss_sexpr);
2615 free(out.s);
2616 if (rv)
2617 break;
2620 jleave:
2621 if (linebuf != NULL)
2622 free(linebuf);
2623 NYD_LEAVE;
2624 return rv;
2627 FL struct n_header_field *
2628 n_customhdr_query(void){
2629 char const *vp;
2630 struct n_header_field *rv, **tail, *hfp;
2631 NYD_ENTER;
2633 rv = NULL;
2635 if((vp = ok_vlook(customhdr)) != NULL){
2636 char *buf;
2638 tail = &rv;
2639 buf = savestr(vp);
2640 jch_outer:
2641 while((vp = a_head_customhdr__sep(&buf)) != NULL){
2642 ui32_t nl, bl;
2643 char const *nstart, *cp;
2645 for(nstart = cp = vp;; ++cp){
2646 if(fieldnamechar(*cp))
2647 continue;
2648 if(*cp == '\0'){
2649 if(cp == nstart){
2650 n_err(_("Invalid nameless *customhdr* entry\n"));
2651 goto jch_outer;
2653 }else if(*cp != ':' && !blankchar(*cp)){
2654 jch_badent:
2655 n_err(_("Invalid *customhdr* entry: %s\n"), vp);
2656 goto jch_outer;
2658 break;
2660 nl = (ui32_t)PTR2SIZE(cp - nstart);
2662 while(blankchar(*cp))
2663 ++cp;
2664 if(*cp++ != ':')
2665 goto jch_badent;
2666 while(blankchar(*cp))
2667 ++cp;
2668 bl = (ui32_t)strlen(cp) +1;
2670 *tail =
2671 hfp = salloc(n_VSTRUCT_SIZEOF(struct n_header_field, hf_dat) +
2672 nl +1 + bl);
2673 tail = &hfp->hf_next;
2674 hfp->hf_next = NULL;
2675 hfp->hf_nl = nl;
2676 hfp->hf_bl = bl - 1;
2677 memcpy(hfp->hf_dat, nstart, nl);
2678 hfp->hf_dat[nl++] = '\0';
2679 memcpy(hfp->hf_dat + nl, cp, bl);
2682 NYD_LEAVE;
2683 return rv;
2686 /* s-it-mode */