main(), nail.1: unify synopsis arg-repitition indicator(s); nits
[s-mailx.git] / head.c
blob5355a746cc4c7bc6a8f21b80ef6fc69f60d06280
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 now whether structured or
524 * TODO unstructured, and just parse correctly overall!
525 * TODO In addition, this can be optimised a lot */
526 struct a_token{
527 struct a_token *t_last;
528 struct a_token *t_next;
529 enum{
530 a_T_TATOM = 1<<0,
531 a_T_TCOMM = 1<<1,
532 a_T_TQUOTE = 1<<2,
533 a_T_TADDR = 1<<3,
534 a_T_TMASK = (1<<4) - 1,
536 a_T_SPECIAL = 1<<8 /* An atom actually needs to go TQUOTE */
537 } t_f;
538 ui8_t t__pad[4];
539 size_t t_start;
540 size_t t_end;
541 } *thead, *tcurr, *tp;
543 struct n_string ost, *ostp;
544 char const *cp, *cp1st, *cpmax, *xp;
545 void *lofi_snap;
547 /* Name and domain must be non-empty */
548 if(*addr == '@' || &addr[2] >= p || p[-2] == '@'){
549 c.c = '@';
550 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_ATSEQ, c.u);
551 goto jleave;
554 #ifdef HAVE_IDNA
555 if(use_idna == 2)
556 agp = a_head_idna_apply(agp);
557 #endif
559 cp = agp->ag_input;
561 /* Nothing to do if there is only an address (in angle brackets) */
562 if(agp->ag_iaddr_start == 0){
563 if(agp->ag_iaddr_aend == agp->ag_ilen)
564 goto jleave;
565 }else if(agp->ag_iaddr_start == 1 && *cp == '<' &&
566 agp->ag_iaddr_aend == agp->ag_ilen - 1 &&
567 cp[agp->ag_iaddr_aend] == '>')
568 goto jleave;
570 /* It is not, so parse off all tokens, then resort and rejoin */
571 lofi_snap = n_lofi_snap_create();
573 cp1st = cp;
574 if((c.ui32 = agp->ag_iaddr_start) > 0)
575 --c.ui32;
576 cpmax = &cp[c.ui32];
578 thead = tcurr = NULL;
579 hadat = FAL0;
580 jnode_redo:
581 for(tp = NULL; cp < cpmax;){
582 switch((c.c = *cp)){
583 case '(':
584 if(tp != NULL)
585 tp->t_end = PTR2SIZE(cp - cp1st);
586 tp = n_lofi_alloc(sizeof *tp);
587 tp->t_next = NULL;
588 if((tp->t_last = tcurr) != NULL)
589 tcurr->t_next = tp;
590 else
591 thead = tp;
592 tcurr = tp;
593 tp->t_f = a_T_TCOMM;
594 tp->t_start = PTR2SIZE(++cp - cp1st);
595 xp = skip_comment(cp);
596 tp->t_end = PTR2SIZE(xp - cp1st);
597 cp = xp;
598 if(tp->t_end > tp->t_start){
599 if(xp[-1] == ')')
600 --tp->t_end;
601 else{
602 /* No closing comment - strip trailing whitespace */
603 while(blankchar(*--xp))
604 if(--tp->t_end == tp->t_start)
605 break;
608 tp = NULL;
609 break;
611 case '"':
612 if(tp != NULL)
613 tp->t_end = PTR2SIZE(cp - cp1st);
614 tp = n_lofi_alloc(sizeof *tp);
615 tp->t_next = NULL;
616 if((tp->t_last = tcurr) != NULL)
617 tcurr->t_next = tp;
618 else
619 thead = tp;
620 tcurr = tp;
621 tp->t_f = a_T_TQUOTE;
622 tp->t_start = PTR2SIZE(++cp - cp1st);
623 for(xp = cp; xp < cpmax; ++xp){
624 if((c.c = *xp) == '"')
625 break;
626 if(c.c == '\\' && xp[1] != '\0')
627 ++xp;
629 tp->t_end = PTR2SIZE(xp - cp1st);
630 cp = &xp[1];
631 if(tp->t_end > tp->t_start){
632 /* No closing quote - strip trailing whitespace */
633 if(*xp != '"'){
634 while(blankchar(*xp--))
635 if(--tp->t_end == tp->t_start)
636 break;
639 tp = NULL;
640 break;
642 default:
643 if(blankchar(c.c)){
644 if(tp != NULL)
645 tp->t_end = PTR2SIZE(cp - cp1st);
646 tp = NULL;
647 ++cp;
648 break;
651 if(tp == NULL){
652 tp = n_lofi_alloc(sizeof *tp);
653 tp->t_next = NULL;
654 if((tp->t_last = tcurr) != NULL)
655 tcurr->t_next = tp;
656 else
657 thead = tp;
658 tcurr = tp;
659 tp->t_f = a_T_TATOM;
660 tp->t_start = PTR2SIZE(cp - cp1st);
662 ++cp;
664 /* Reverse solidus transforms the following into a quoted-pair, and
665 * therefore (must occur in comment or quoted-string only) the
666 * entire atom into a quoted string */
667 if(c.c == '\\'){
668 tp->t_f |= a_T_SPECIAL;
669 if(cp < cpmax)
670 ++cp;
672 /* Is this plain RFC 5322 "atext", or "specials"? Because we don't
673 * TODO know structured/unstructured, nor anything else, we need to
674 * TODO treat "dot-atom" as being identical to "specials" */
675 else if(!alnumchar(c.c) &&
676 c.c != '!' && c.c != '#' && c.c != '$' && c.c != '%' &&
677 c.c != '&' && c.c != '\'' && c.c != '*' && 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 tp->t_f |= a_T_SPECIAL;
682 break;
685 if(tp != NULL)
686 tp->t_end = PTR2SIZE(cp - cp1st);
688 if(hadat == FAL0){
689 hadat = TRU1;
690 tp = n_lofi_alloc(sizeof *tp);
691 tp->t_next = NULL;
692 if((tp->t_last = tcurr) != NULL)
693 tcurr->t_next = tp;
694 else
695 thead = tp;
696 tcurr = tp;
697 tp->t_f = a_T_TADDR;
698 tp->t_start = agp->ag_iaddr_start;
699 tp->t_end = agp->ag_iaddr_aend;
700 tp = NULL;
702 cp = &agp->ag_input[agp->ag_iaddr_aend + 1];
703 cpmax = &agp->ag_input[agp->ag_ilen];
704 if(cp < cpmax)
705 goto jnode_redo;
708 /* Nothing may follow the address, move it to the end */
709 if(!(tcurr->t_f & a_T_TADDR)){
710 for(tp = thead; tp != NULL; tp = tp->t_next)
711 if(tp->t_f & a_T_TADDR){
712 if(tp->t_last != NULL)
713 tp->t_last->t_next = tp->t_next;
714 else
715 thead = tp->t_next;
716 if(tp->t_next != NULL)
717 tp->t_next->t_last = tp->t_last;
719 tcurr = tp;
720 while(tp->t_next != NULL)
721 tp = tp->t_next;
722 tp->t_next = tcurr;
723 tcurr->t_last = tp;
724 tcurr->t_next = NULL;
725 break;
729 /* Make ranges contiguous: ensure a continuous range of atoms is converted
730 * to a SPECIAL one if at least one of them requires it */
731 for(tp = thead; tp != NULL; tp = tp->t_next){
732 if(tp->t_f & a_T_SPECIAL){
733 tcurr = tp;
734 while((tp = tp->t_last) != NULL && (tp->t_f & a_T_TATOM))
735 tp->t_f |= a_T_SPECIAL;
736 tp = tcurr;
737 while((tp = tp->t_next) != NULL && (tp->t_f & a_T_TATOM))
738 tp->t_f |= a_T_SPECIAL;
741 /* And yes, we want quotes to extend as much as possible */
742 for(tp = thead; tp != NULL; tp = tp->t_next){
743 if(tp->t_f & a_T_TQUOTE){
744 tcurr = tp;
745 while((tp = tp->t_last) != NULL && (tp->t_f & a_T_TATOM))
746 tp->t_f |= a_T_SPECIAL;
747 tp = tcurr;
748 while((tp = tp->t_next) != NULL && (tp->t_f & a_T_TATOM))
749 tp->t_f |= a_T_SPECIAL;
753 /* Then rejoin */
754 ostp = n_string_creat_auto(&ost);
755 if((c.ui32 = agp->ag_ilen) <= UI32_MAX >> 1)
756 ostp = n_string_reserve(ostp, c.ui32 <<= 1);
758 for(tcurr = thead; tcurr != NULL;){
759 if(tcurr != thead)
760 ostp = n_string_push_c(ostp, ' ');
761 if(tcurr->t_f & a_T_TADDR){
762 ostp = n_string_push_c(ostp, '<');
763 agp->ag_iaddr_start = ostp->s_len;
764 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
765 (tcurr->t_end - tcurr->t_start));
766 agp->ag_iaddr_aend = ostp->s_len;
767 ostp = n_string_push_c(ostp, '>');
768 tcurr = tcurr->t_next;
769 }else if(tcurr->t_f & a_T_TCOMM){
770 ostp = n_string_push_c(ostp, '(');
771 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
772 (tcurr->t_end - tcurr->t_start));
773 while((tp = tcurr->t_next) != NULL && (tp->t_f & a_T_TCOMM)){
774 tcurr = tp;
775 ostp = n_string_push_c(ostp, ' ');
776 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
777 (tcurr->t_end - tcurr->t_start));
779 ostp = n_string_push_c(ostp, ')');
780 tcurr = tcurr->t_next;
781 }else if(tcurr->t_f & a_T_TQUOTE){
782 jput_quote:
783 ostp = n_string_push_c(ostp, '"');
784 tp = tcurr;
785 do/* while tcurr && TATOM||TQUOTE */{
786 cp = &cp1st[tcurr->t_start];
787 cpmax = &cp1st[tcurr->t_end];
788 if(cp == cpmax)
789 continue;
791 if(tcurr != tp)
792 ostp = n_string_push_c(ostp, ' ');
794 if((tcurr->t_f & (a_T_TATOM | a_T_SPECIAL)) == a_T_TATOM)
795 ostp = n_string_push_buf(ostp, cp, PTR2SIZE(cpmax - cp));
796 else{
797 bool_t esc;
799 for(esc = FAL0; cp < cpmax;){
800 if((c.c = *cp++) == '\\' && !esc)
801 esc = TRU1;
802 else{
803 if(esc || c.c == '"'){
804 jput_quote_esc:
805 ostp = n_string_push_c(ostp, '\\');
807 ostp = n_string_push_c(ostp, c.c);
808 esc = FAL0;
811 if(esc){
812 c.c = '\\';
813 goto jput_quote_esc;
816 }while((tcurr = tcurr->t_next) != NULL &&
817 (tcurr->t_f & (a_T_TATOM | a_T_TQUOTE)));
818 ostp = n_string_push_c(ostp, '"');
819 }else if(tcurr->t_f & a_T_SPECIAL)
820 goto jput_quote;
821 else{
822 /* Can we use a fast join mode? */
823 for(tp = tcurr; tcurr != NULL; tcurr = tcurr->t_next){
824 if(!(tcurr->t_f & a_T_TATOM))
825 break;
826 if(tcurr != tp)
827 ostp = n_string_push_c(ostp, ' ');
828 ostp = n_string_push_buf(ostp, &cp1st[tcurr->t_start],
829 (tcurr->t_end - tcurr->t_start));
834 n_lofi_snap_unroll(lofi_snap);
836 agp->ag_input = n_string_cp(ostp);
837 agp->ag_ilen = ostp->s_len;
838 ostp = n_string_drop_ownership(ostp);
840 jleave:
841 NYD_LEAVE;
842 return ((agp->ag_n_flags & NAME_ADDRSPEC_INVALID) == 0);
845 static int
846 gethfield(FILE *f, char **linebuf, size_t *linesize, int rem, char **colon)
848 char *line2 = NULL, *cp, *cp2;
849 size_t line2size = 0;
850 int c, isenc;
851 NYD2_ENTER;
853 if (*linebuf == NULL)
854 *linebuf = srealloc(*linebuf, *linesize = 1);
855 **linebuf = '\0';
856 for (;;) {
857 if (--rem < 0) {
858 rem = -1;
859 break;
861 if ((c = readline_restart(f, linebuf, linesize, 0)) <= 0) {
862 rem = -1;
863 break;
865 for (cp = *linebuf; fieldnamechar(*cp); ++cp)
867 if (cp > *linebuf)
868 while (blankchar(*cp))
869 ++cp;
870 if (*cp != ':' || cp == *linebuf)
871 continue;
873 /* I guess we got a headline. Handle wraparound */
874 *colon = cp;
875 cp = *linebuf + c;
876 for (;;) {
877 isenc = 0;
878 while (PTRCMP(--cp, >=, *linebuf) && blankchar(*cp))
880 cp++;
881 if (rem <= 0)
882 break;
883 if (PTRCMP(cp - 8, >=, *linebuf) && cp[-1] == '=' && cp[-2] == '?')
884 isenc |= 1;
885 ungetc(c = getc(f), f);
886 if (!blankchar(c))
887 break;
888 c = readline_restart(f, &line2, &line2size, 0);
889 if (c < 0)
890 break;
891 --rem;
892 for (cp2 = line2; blankchar(*cp2); ++cp2)
894 c -= (int)PTR2SIZE(cp2 - line2);
895 if (cp2[0] == '=' && cp2[1] == '?' && c > 8)
896 isenc |= 2;
897 if (PTRCMP(cp + c, >=, *linebuf + *linesize - 2)) {
898 size_t diff = PTR2SIZE(cp - *linebuf),
899 colondiff = PTR2SIZE(*colon - *linebuf);
900 *linebuf = srealloc(*linebuf, *linesize += c + 2);
901 cp = &(*linebuf)[diff];
902 *colon = &(*linebuf)[colondiff];
904 if (isenc != 3)
905 *cp++ = ' ';
906 memcpy(cp, cp2, c);
907 cp += c;
909 *cp = '\0';
911 if (line2 != NULL)
912 free(line2);
913 break;
915 NYD2_LEAVE;
916 return rem;
919 static int
920 msgidnextc(char const **cp, int *status)
922 int c;
923 NYD2_ENTER;
925 assert(cp != NULL);
926 assert(*cp != NULL);
927 assert(status != NULL);
929 for (;;) {
930 if (*status & 01) {
931 if (**cp == '"') {
932 *status &= ~01;
933 (*cp)++;
934 continue;
936 if (**cp == '\\') {
937 (*cp)++;
938 if (**cp == '\0')
939 goto jeof;
941 goto jdfl;
943 switch (**cp) {
944 case '(':
945 *cp = skip_comment(&(*cp)[1]);
946 continue;
947 case '>':
948 case '\0':
949 jeof:
950 c = '\0';
951 goto jleave;
952 case '"':
953 (*cp)++;
954 *status |= 01;
955 continue;
956 case '@':
957 *status |= 02;
958 /*FALLTHRU*/
959 default:
960 jdfl:
961 c = *(*cp)++ & 0377;
962 c = (*status & 02) ? lowerconv(c) : c;
963 goto jleave;
966 jleave:
967 NYD2_LEAVE;
968 return c;
971 static int
972 charcount(char *str, int c)
974 char *cp;
975 int i;
976 NYD2_ENTER;
978 for (i = 0, cp = str; *cp; ++cp)
979 if (*cp == c)
980 ++i;
981 NYD2_LEAVE;
982 return i;
985 static char const *
986 nexttoken(char const *cp)
988 NYD2_ENTER;
989 for (;;) {
990 if (*cp == '\0') {
991 cp = NULL;
992 break;
995 if (*cp == '(') {
996 size_t nesting = 1;
998 do switch (*++cp) {
999 case '(':
1000 ++nesting;
1001 break;
1002 case ')':
1003 --nesting;
1004 break;
1005 } while (nesting > 0 && *cp != '\0'); /* XXX error? */
1006 } else if (blankchar(*cp) || *cp == ',')
1007 ++cp;
1008 else
1009 break;
1011 NYD2_LEAVE;
1012 return cp;
1015 static char *
1016 a_head_customhdr__sep(char **iolist){
1017 char *cp, c, *base;
1018 bool_t isesc, anyesc;
1019 NYD2_ENTER;
1021 for(base = *iolist; base != NULL; base = *iolist){
1022 while((c = *base) != '\0' && blankspacechar(c))
1023 ++base;
1025 for(isesc = anyesc = FAL0, cp = base;; ++cp){
1026 if(n_UNLIKELY((c = *cp) == '\0')){
1027 *iolist = NULL;
1028 break;
1029 }else if(!isesc){
1030 if(c == ','){
1031 *iolist = cp + 1;
1032 break;
1034 isesc = (c == '\\');
1035 }else{
1036 isesc = FAL0;
1037 anyesc |= (c == ',');
1041 while(cp > base && blankspacechar(cp[-1]))
1042 --cp;
1043 *cp = '\0';
1045 if(*base != '\0'){
1046 if(anyesc){
1047 char *ins;
1049 for(ins = cp = base;; ++ins)
1050 if((c = *cp) == '\\' && cp[1] == ','){
1051 *ins = ',';
1052 cp += 2;
1053 }else if((*ins = (++cp, c)) == '\0')
1054 break;
1056 break;
1059 NYD2_LEAVE;
1060 return base;
1063 FL char const *
1064 myaddrs(struct header *hp) /* TODO */
1066 struct name *np;
1067 char const *rv, *mta;
1068 NYD_ENTER;
1070 if (hp != NULL && (np = hp->h_from) != NULL) {
1071 if ((rv = np->n_fullname) != NULL)
1072 goto jleave;
1073 if ((rv = np->n_name) != NULL)
1074 goto jleave;
1077 if((rv = ok_vlook(from)) != NULL){
1078 if((np = lextract(rv, GEXTRA | GFULL)) == NULL)
1079 jefrom:
1080 n_err(_("An address given in *from* is invalid: %s\n"), rv);
1081 else for(; np != NULL; np = np->n_flink)
1082 if(is_addr_invalid(np, EACM_STRICT | EACM_NOLOG | EACM_NONAME))
1083 goto jefrom;
1084 goto jleave;
1087 /* When invoking *sendmail* directly, it's its task to generate an otherwise
1088 * undeterminable From: address. However, if the user sets *hostname*,
1089 * accept his desire */
1090 if (ok_vlook(hostname) != NULL)
1091 goto jnodename;
1092 if (ok_vlook(smtp) != NULL || /* TODO obsolete -> mta */
1093 /* TODO pretty hacky for now (this entire fun), later: url_creat()! */
1094 ((mta = ok_vlook(mta)) != NULL &&
1095 (mta = n_servbyname(mta, NULL)) != NULL && *mta != '\0'))
1096 goto jnodename;
1097 jleave:
1098 NYD_LEAVE;
1099 return rv;
1101 jnodename:{
1102 char *cp;
1103 char const *hn, *ln;
1104 size_t i;
1106 hn = n_nodename(TRU1);
1107 ln = ok_vlook(LOGNAME);
1108 i = strlen(ln) + strlen(hn) + 1 +1;
1109 rv = cp = salloc(i);
1110 sstpcpy(sstpcpy(sstpcpy(cp, ln), n_at), hn);
1112 goto jleave;
1115 FL char const *
1116 myorigin(struct header *hp) /* TODO */
1118 char const *rv = NULL, *ccp;
1119 struct name *np;
1120 NYD_ENTER;
1122 if((ccp = myaddrs(hp)) != NULL &&
1123 (np = lextract(ccp, GEXTRA | GFULL)) != NULL){
1124 if(np->n_flink == NULL)
1125 rv = ccp;
1126 else if((ccp = ok_vlook(sender)) != NULL) {
1127 if((np = lextract(ccp, GEXTRA | GFULL)) == NULL ||
1128 np->n_flink != NULL ||
1129 is_addr_invalid(np, EACM_STRICT | EACM_NOLOG | EACM_NONAME))
1130 n_err(_("The address given in *sender* is invalid: %s\n"), ccp);
1131 else
1132 rv = ccp;
1135 NYD_LEAVE;
1136 return rv;
1139 FL bool_t
1140 is_head(char const *linebuf, size_t linelen, bool_t check_rfc4155)
1142 char date[n_FROM_DATEBUF];
1143 bool_t rv;
1144 NYD2_ENTER;
1146 if ((rv = (linelen >= 5 && !memcmp(linebuf, "From ", 5))) && check_rfc4155 &&
1147 (extract_date_from_from_(linebuf, linelen, date) <= 0 ||
1148 !_is_date(date)))
1149 rv = TRUM1;
1150 NYD2_LEAVE;
1151 return rv;
1154 FL int
1155 extract_date_from_from_(char const *line, size_t linelen,
1156 char datebuf[n_FROM_DATEBUF])
1158 int rv;
1159 char const *cp = line;
1160 NYD_ENTER;
1162 rv = 1;
1164 /* "From " */
1165 cp = _from__skipword(cp);
1166 if (cp == NULL)
1167 goto jerr;
1168 /* "addr-spec " */
1169 cp = _from__skipword(cp);
1170 if (cp == NULL)
1171 goto jerr;
1172 if (cp[0] == 't' && cp[1] == 't' && cp[2] == 'y') {
1173 cp = _from__skipword(cp);
1174 if (cp == NULL)
1175 goto jerr;
1177 /* It seems there are invalid MBOX archives in the wild, compare
1178 * . http://bugs.debian.org/624111
1179 * . [Mutt] #3868: mutt should error if the imported mailbox is invalid
1180 * What they do is that they obfuscate the address to "name at host",
1181 * and even "name at host dot dom dot dom. I think we should handle that */
1182 else if(cp[0] == 'a' && cp[1] == 't' && cp[2] == ' '){
1183 rv = -1;
1184 cp += 3;
1185 jat_dot:
1186 cp = _from__skipword(cp);
1187 if (cp == NULL)
1188 goto jerr;
1189 if(cp[0] == 'd' && cp[1] == 'o' && cp[2] == 't' && cp[3] == ' '){
1190 cp += 4;
1191 goto jat_dot;
1195 linelen -= PTR2SIZE(cp - line);
1196 if (linelen < a_HEAD_DATE_MINLEN)
1197 goto jerr;
1198 if (cp[linelen - 1] == '\n') {
1199 --linelen;
1200 /* (Rather IMAP/POP3 only) */
1201 if (cp[linelen - 1] == '\r')
1202 --linelen;
1203 if (linelen < a_HEAD_DATE_MINLEN)
1204 goto jerr;
1206 if (linelen >= n_FROM_DATEBUF)
1207 goto jerr;
1209 jleave:
1210 memcpy(datebuf, cp, linelen);
1211 datebuf[linelen] = '\0';
1212 NYD_LEAVE;
1213 return rv;
1214 jerr:
1215 cp = _("<Unknown date>");
1216 linelen = strlen(cp);
1217 if (linelen >= n_FROM_DATEBUF)
1218 linelen = n_FROM_DATEBUF;
1219 rv = 0;
1220 goto jleave;
1223 FL void
1224 extract_header(FILE *fp, struct header *hp, si8_t *checkaddr_err)
1226 /* See the prototype declaration for the hairy relationship of
1227 * n_poption&n_PO_t_FLAG and/or n_psonce&n_PSO_t_FLAG in here */
1228 struct n_header_field **hftail;
1229 struct header nh, *hq = &nh;
1230 char *linebuf = NULL /* TODO line pool */, *colon;
1231 size_t linesize = 0, seenfields = 0;
1232 int lc, c;
1233 char const *val, *cp;
1234 NYD_ENTER;
1236 memset(hq, 0, sizeof *hq);
1237 if ((n_psonce & n_PSO_t_FLAG) && (n_poption & n_PO_t_FLAG)) {
1238 hq->h_to = hp->h_to;
1239 hq->h_cc = hp->h_cc;
1240 hq->h_bcc = hp->h_bcc;
1242 hftail = &hq->h_user_headers;
1244 for (lc = 0; readline_restart(fp, &linebuf, &linesize, 0) > 0; ++lc)
1247 /* TODO yippieia, cat(check(lextract)) :-) */
1248 rewind(fp);
1249 while ((lc = gethfield(fp, &linebuf, &linesize, lc, &colon)) >= 0) {
1250 struct name *np;
1252 /* We explicitly allow EAF_NAME for some addressees since aliases are not
1253 * yet expanded when we parse these! */
1254 if ((val = thisfield(linebuf, "to")) != NULL) {
1255 ++seenfields;
1256 hq->h_to = cat(hq->h_to, checkaddrs(lextract(val, GTO | GFULL),
1257 EACM_NORMAL | EAF_NAME | EAF_MAYKEEP, checkaddr_err));
1258 } else if ((val = thisfield(linebuf, "cc")) != NULL) {
1259 ++seenfields;
1260 hq->h_cc = cat(hq->h_cc, checkaddrs(lextract(val, GCC | GFULL),
1261 EACM_NORMAL | EAF_NAME | EAF_MAYKEEP, checkaddr_err));
1262 } else if ((val = thisfield(linebuf, "bcc")) != NULL) {
1263 ++seenfields;
1264 hq->h_bcc = cat(hq->h_bcc, checkaddrs(lextract(val, GBCC | GFULL),
1265 EACM_NORMAL | EAF_NAME | EAF_MAYKEEP, checkaddr_err));
1266 } else if ((val = thisfield(linebuf, "from")) != NULL) {
1267 if (!(n_psonce & n_PSO_t_FLAG) || (n_poption & n_PO_t_FLAG)) {
1268 ++seenfields;
1269 hq->h_from = cat(hq->h_from,
1270 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
1271 EACM_STRICT, NULL));
1273 } else if ((val = thisfield(linebuf, "reply-to")) != NULL) {
1274 ++seenfields;
1275 hq->h_replyto = cat(hq->h_replyto,
1276 checkaddrs(lextract(val, GEXTRA | GFULL), EACM_STRICT, NULL));
1277 } else if ((val = thisfield(linebuf, "sender")) != NULL) {
1278 if (!(n_psonce & n_PSO_t_FLAG) || (n_poption & n_PO_t_FLAG)) {
1279 ++seenfields;
1280 hq->h_sender = cat(hq->h_sender, /* TODO cat? check! */
1281 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
1282 EACM_STRICT, NULL));
1283 } else
1284 goto jebadhead;
1285 } else if ((val = thisfield(linebuf, "subject")) != NULL ||
1286 (val = thisfield(linebuf, "subj")) != NULL) {
1287 ++seenfields;
1288 for (cp = val; blankchar(*cp); ++cp)
1290 hq->h_subject = (hq->h_subject != NULL)
1291 ? save2str(hq->h_subject, cp) : savestr(cp);
1293 /* The remaining are mostly hacked in and thus TODO -- at least in
1294 * TODO respect to their content checking */
1295 else if((val = thisfield(linebuf, "message-id")) != NULL){
1296 if(n_psonce & n_PSO_t_FLAG){
1297 np = checkaddrs(lextract(val, GREF),
1298 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1299 NULL);
1300 if (np == NULL || np->n_flink != NULL)
1301 goto jebadhead;
1302 ++seenfields;
1303 hq->h_message_id = np;
1304 }else
1305 goto jebadhead;
1306 }else if((val = thisfield(linebuf, "in-reply-to")) != NULL){
1307 if(n_psonce & n_PSO_t_FLAG){
1308 np = checkaddrs(lextract(val, GREF),
1309 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1310 NULL);
1311 ++seenfields;
1312 hq->h_in_reply_to = np;
1313 }else
1314 goto jebadhead;
1315 }else if((val = thisfield(linebuf, "references")) != NULL){
1316 if(n_psonce & n_PSO_t_FLAG){
1317 ++seenfields;
1318 /* TODO Limit number of references TODO better on parser side */
1319 hq->h_ref = cat(hq->h_ref, checkaddrs(extract(val, GREF),
1320 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1321 NULL));
1322 }else
1323 goto jebadhead;
1325 /* and that is very hairy */
1326 else if((val = thisfield(linebuf, "mail-followup-to")) != NULL){
1327 if(n_psonce & n_PSO_t_FLAG){
1328 ++seenfields;
1329 hq->h_mft = cat(hq->h_mft, checkaddrs(lextract(val, GEXTRA | GFULL),
1330 /*EACM_STRICT | TODO '/' valid!! | EACM_NOLOG | */EACM_NONAME,
1331 checkaddr_err));
1332 }else
1333 goto jebadhead;
1335 /* A free-form user header; gethfield() did some verification already.. */
1336 else{
1337 struct n_header_field *hfp;
1338 ui32_t nl, bl;
1339 char const *nstart;
1341 for(nstart = cp = linebuf;; ++cp)
1342 if(!fieldnamechar(*cp))
1343 break;
1344 nl = (ui32_t)PTR2SIZE(cp - nstart);
1346 while(blankchar(*cp))
1347 ++cp;
1348 if(*cp++ != ':'){
1349 jebadhead:
1350 n_err(_("Ignoring header field: %s\n"), linebuf);
1351 continue;
1353 while(blankchar(*cp))
1354 ++cp;
1355 bl = (ui32_t)strlen(cp) +1;
1357 ++seenfields;
1358 *hftail = hfp = salloc(n_VSTRUCT_SIZEOF(struct n_header_field, hf_dat
1359 ) + nl +1 + bl);
1360 hftail = &hfp->hf_next;
1361 hfp->hf_next = NULL;
1362 hfp->hf_nl = nl;
1363 hfp->hf_bl = bl - 1;
1364 memcpy(hfp->hf_dat, nstart, nl);
1365 hfp->hf_dat[nl++] = '\0';
1366 memcpy(hfp->hf_dat + nl, cp, bl);
1370 /* In case the blank line after the header has been edited out. Otherwise,
1371 * fetch the header separator */
1372 if (linebuf != NULL) {
1373 if (linebuf[0] != '\0') {
1374 for (cp = linebuf; *(++cp) != '\0';)
1376 fseek(fp, (long)-PTR2SIZE(1 + cp - linebuf), SEEK_CUR);
1377 } else {
1378 if ((c = getc(fp)) != '\n' && c != EOF)
1379 ungetc(c, fp);
1383 if (seenfields > 0 && (checkaddr_err == NULL || *checkaddr_err == 0)) {
1384 hp->h_to = hq->h_to;
1385 hp->h_cc = hq->h_cc;
1386 hp->h_bcc = hq->h_bcc;
1387 hp->h_from = hq->h_from;
1388 hp->h_replyto = hq->h_replyto;
1389 hp->h_sender = hq->h_sender;
1390 if (hq->h_subject != NULL || !(n_psonce & n_PSO_t_FLAG) ||
1391 !(n_poption & n_PO_t_FLAG))
1392 hp->h_subject = hq->h_subject;
1393 hp->h_user_headers = hq->h_user_headers;
1395 if (n_psonce & n_PSO_t_FLAG) {
1396 hp->h_ref = hq->h_ref;
1397 hp->h_message_id = hq->h_message_id;
1398 hp->h_in_reply_to = hq->h_in_reply_to;
1399 hp->h_mft = hq->h_mft;
1401 /* And perform additional validity checks so that we don't bail later
1402 * on TODO this is good and the place where this should occur,
1403 * TODO unfortunately a lot of other places do again and blabla */
1404 if (hp->h_from == NULL)
1405 hp->h_from = n_poption_arg_r;
1406 else if (hp->h_from->n_flink != NULL && hp->h_sender == NULL)
1407 hp->h_sender = lextract(ok_vlook(sender),
1408 GEXTRA | GFULL | GFULLEXTRA);
1410 } else
1411 n_err(_("Restoring deleted header lines\n"));
1413 if (linebuf != NULL)
1414 free(linebuf);
1415 NYD_LEAVE;
1418 FL char *
1419 hfield_mult(char const *field, struct message *mp, int mult)
1421 FILE *ibuf;
1422 int lc;
1423 struct str hfs;
1424 size_t linesize = 0; /* TODO line pool */
1425 char *linebuf = NULL, *colon;
1426 char const *hfield;
1427 NYD_ENTER;
1429 /* There are (spam) messages which have header bytes which are many KB when
1430 * joined, so resize a single heap storage until we are done if we shall
1431 * collect a field that may have multiple bodies; only otherwise use the
1432 * string dope directly */
1433 memset(&hfs, 0, sizeof hfs);
1435 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
1436 goto jleave;
1437 if ((lc = mp->m_lines - 1) < 0)
1438 goto jleave;
1440 if ((mp->m_flag & MNOFROM) == 0 &&
1441 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1442 goto jleave;
1443 while (lc > 0) {
1444 if ((lc = gethfield(ibuf, &linebuf, &linesize, lc, &colon)) < 0)
1445 break;
1446 if ((hfield = thisfield(linebuf, field)) != NULL && *hfield != '\0') {
1447 if (mult)
1448 n_str_add_buf(&hfs, hfield, strlen(hfield));
1449 else {
1450 hfs.s = savestr(hfield);
1451 break;
1456 jleave:
1457 if (linebuf != NULL)
1458 free(linebuf);
1459 if (mult && hfs.s != NULL) {
1460 colon = savestrbuf(hfs.s, hfs.l);
1461 free(hfs.s);
1462 hfs.s = colon;
1464 NYD_LEAVE;
1465 return hfs.s;
1468 FL char const *
1469 thisfield(char const *linebuf, char const *field)
1471 char const *rv = NULL;
1472 NYD2_ENTER;
1474 while (lowerconv(*linebuf) == lowerconv(*field)) {
1475 ++linebuf;
1476 ++field;
1478 if (*field != '\0')
1479 goto jleave;
1481 while (blankchar(*linebuf))
1482 ++linebuf;
1483 if (*linebuf++ != ':')
1484 goto jleave;
1486 while (blankchar(*linebuf)) /* TODO header parser.. strip trailing WS?!? */
1487 ++linebuf;
1488 rv = linebuf;
1489 jleave:
1490 NYD2_LEAVE;
1491 return rv;
1494 FL char *
1495 nameof(struct message *mp, int reptype)
1497 char *cp, *cp2;
1498 NYD_ENTER;
1500 cp = skin(name1(mp, reptype));
1501 if (reptype != 0 || charcount(cp, '!') < 2)
1502 goto jleave;
1503 cp2 = strrchr(cp, '!');
1504 --cp2;
1505 while (cp2 > cp && *cp2 != '!')
1506 --cp2;
1507 if (*cp2 == '!')
1508 cp = cp2 + 1;
1509 jleave:
1510 NYD_LEAVE;
1511 return cp;
1514 FL char const *
1515 skip_comment(char const *cp)
1517 size_t nesting;
1518 NYD_ENTER;
1520 for (nesting = 1; nesting > 0 && *cp; ++cp) {
1521 switch (*cp) {
1522 case '\\':
1523 if (cp[1])
1524 ++cp;
1525 break;
1526 case '(':
1527 ++nesting;
1528 break;
1529 case ')':
1530 --nesting;
1531 break;
1534 NYD_LEAVE;
1535 return cp;
1538 FL char const *
1539 routeaddr(char const *name)
1541 char const *np, *rp = NULL;
1542 NYD_ENTER;
1544 for (np = name; *np; np++) {
1545 switch (*np) {
1546 case '(':
1547 np = skip_comment(np + 1) - 1;
1548 break;
1549 case '"':
1550 while (*np) {
1551 if (*++np == '"')
1552 break;
1553 if (*np == '\\' && np[1])
1554 np++;
1556 break;
1557 case '<':
1558 rp = np;
1559 break;
1560 case '>':
1561 goto jleave;
1564 rp = NULL;
1565 jleave:
1566 NYD_LEAVE;
1567 return rp;
1570 FL enum expand_addr_flags
1571 expandaddr_to_eaf(void)
1573 struct eafdesc {
1574 char const *eafd_name;
1575 bool_t eafd_is_target;
1576 ui8_t eafd_andoff;
1577 ui8_t eafd_or;
1578 } const eafa[] = {
1579 {"restrict", FAL0, EAF_TARGET_MASK, EAF_RESTRICT | EAF_RESTRICT_TARGETS},
1580 {"fail", FAL0, EAF_NONE, EAF_FAIL},
1581 {"failinvaddr", FAL0, EAF_NONE, EAF_FAILINVADDR | EAF_ADDR},
1582 {"all", TRU1, EAF_NONE, EAF_TARGET_MASK},
1583 {"file", TRU1, EAF_NONE, EAF_FILE},
1584 {"pipe", TRU1, EAF_NONE, EAF_PIPE},
1585 {"name", TRU1, EAF_NONE, EAF_NAME},
1586 {"addr", TRU1, EAF_NONE, EAF_ADDR}
1587 }, *eafp;
1589 char *buf;
1590 enum expand_addr_flags rv;
1591 char const *cp;
1592 NYD2_ENTER;
1594 if ((cp = ok_vlook(expandaddr)) == NULL)
1595 rv = EAF_RESTRICT_TARGETS;
1596 else if (*cp == '\0')
1597 rv = EAF_TARGET_MASK;
1598 else {
1599 rv = EAF_TARGET_MASK;
1601 for (buf = savestr(cp); (cp = n_strsep(&buf, ',', TRU1)) != NULL;) {
1602 bool_t minus;
1604 if ((minus = (*cp == '-')) || *cp == '+')
1605 ++cp;
1606 for (eafp = eafa;; ++eafp) {
1607 if (eafp == eafa + n_NELEM(eafa)) {
1608 if (n_poption & n_PO_D_V)
1609 n_err(_("Unknown *expandaddr* value: %s\n"), cp);
1610 break;
1611 } else if (!asccasecmp(cp, eafp->eafd_name)) {
1612 if (!minus) {
1613 rv &= ~eafp->eafd_andoff;
1614 rv |= eafp->eafd_or;
1615 } else {
1616 if (eafp->eafd_is_target)
1617 rv &= ~eafp->eafd_or;
1618 else if (n_poption & n_PO_D_V)
1619 n_err(_("minus - prefix invalid for *expandaddr* value: "
1620 "%s\n"), --cp);
1622 break;
1623 } else if (!asccasecmp(cp, "noalias")) { /* TODO v15 OBSOLETE */
1624 n_OBSOLETE(_("*expandaddr*: noalias is henceforth -name"));
1625 rv &= ~EAF_NAME;
1626 break;
1631 if((rv & EAF_RESTRICT) && ((n_psonce & n_PSO_INTERACTIVE) ||
1632 (n_poption & n_PO_TILDE_FLAG)))
1633 rv |= EAF_TARGET_MASK;
1634 else if(n_poption & n_PO_D_V){
1635 if(!(rv & EAF_TARGET_MASK))
1636 n_err(_("*expandaddr* doesn't allow any addressees\n"));
1637 else if((rv & EAF_FAIL) && (rv & EAF_TARGET_MASK) == EAF_TARGET_MASK)
1638 n_err(_("*expandaddr* with fail, but no restrictions to apply\n"));
1641 NYD2_LEAVE;
1642 return rv;
1645 FL si8_t
1646 is_addr_invalid(struct name *np, enum expand_addr_check_mode eacm)
1648 char cbuf[sizeof "'\\U12340'"];
1649 char const *cs;
1650 int f;
1651 si8_t rv;
1652 enum expand_addr_flags eaf;
1653 NYD_ENTER;
1655 eaf = expandaddr_to_eaf();
1656 f = np->n_flags;
1658 if ((rv = ((f & NAME_ADDRSPEC_INVALID) != 0))) {
1659 if (eaf & EAF_FAILINVADDR)
1660 rv = -rv;
1662 if ((eacm & EACM_NOLOG) || (f & NAME_ADDRSPEC_ERR_EMPTY)) {
1664 } else {
1665 ui32_t c;
1666 char const *fmt = "'\\x%02X'";
1667 bool_t ok8bit = TRU1;
1669 if (f & NAME_ADDRSPEC_ERR_IDNA) {
1670 cs = _("Invalid domain name: %s, character %s\n");
1671 fmt = "'\\U%04X'";
1672 ok8bit = FAL0;
1673 } else if (f & NAME_ADDRSPEC_ERR_ATSEQ)
1674 cs = _("%s contains invalid %s sequence\n");
1675 else if (f & NAME_ADDRSPEC_ERR_NAME) {
1676 cs = _("%s is an invalid alias name\n");
1677 } else
1678 cs = _("%s contains invalid byte %s\n");
1680 c = NAME_ADDRSPEC_ERR_GETWC(f);
1681 snprintf(cbuf, sizeof cbuf,
1682 (ok8bit && c >= 040 && c <= 0177 ? "'%c'" : fmt), c);
1683 goto jprint;
1685 goto jleave;
1688 /* *expandaddr* stuff */
1689 if (!(rv = ((eacm & EACM_MODE_MASK) != EACM_NONE)))
1690 goto jleave;
1692 if ((eacm & EACM_STRICT) && (f & NAME_ADDRSPEC_ISFILEORPIPE)) {
1693 if (eaf & EAF_FAIL)
1694 rv = -rv;
1695 cs = _("%s%s: file or pipe addressees not allowed here\n");
1696 if (eacm & EACM_NOLOG)
1697 goto jleave;
1698 else
1699 goto j0print;
1702 eaf |= (eacm & EAF_TARGET_MASK);
1703 if (eacm & EACM_NONAME)
1704 eaf &= ~EAF_NAME;
1706 if (eaf == EAF_NONE) {
1707 rv = FAL0;
1708 goto jleave;
1710 if (eaf & EAF_FAIL)
1711 rv = -rv;
1713 if (!(eaf & EAF_FILE) && (f & NAME_ADDRSPEC_ISFILE)) {
1714 cs = _("%s%s: *expandaddr* doesn't allow file target\n");
1715 if (eacm & EACM_NOLOG)
1716 goto jleave;
1717 } else if (!(eaf & EAF_PIPE) && (f & NAME_ADDRSPEC_ISPIPE)) {
1718 cs = _("%s%s: *expandaddr* doesn't allow command pipe target\n");
1719 if (eacm & EACM_NOLOG)
1720 goto jleave;
1721 } else if (!(eaf & EAF_NAME) && (f & NAME_ADDRSPEC_ISNAME)) {
1722 cs = _("%s%s: *expandaddr* doesn't allow user name target\n");
1723 if (eacm & EACM_NOLOG)
1724 goto jleave;
1725 } else if (!(eaf & EAF_ADDR) && (f & NAME_ADDRSPEC_ISADDR)) {
1726 cs = _("%s%s: *expandaddr* doesn't allow mail address target\n");
1727 if (eacm & EACM_NOLOG)
1728 goto jleave;
1729 } else {
1730 rv = FAL0;
1731 goto jleave;
1734 j0print:
1735 cbuf[0] = '\0';
1736 jprint:
1737 n_err(cs, n_shexp_quote_cp(np->n_name, TRU1), cbuf);
1738 jleave:
1739 NYD_LEAVE;
1740 return rv;
1743 FL char *
1744 skin(char const *name)
1746 struct n_addrguts ag;
1747 char *rv;
1748 NYD_ENTER;
1750 if(name != NULL){
1751 name = n_addrspec_with_guts(&ag,name, TRU1, FAL0);
1752 rv = ag.ag_skinned;
1753 if(!(ag.ag_n_flags & NAME_NAME_SALLOC))
1754 rv = savestrbuf(rv, ag.ag_slen);
1755 }else
1756 rv = NULL;
1757 NYD_LEAVE;
1758 return rv;
1761 /* TODO addrspec_with_guts: RFC 5322
1762 * TODO addrspec_with_guts: trim whitespace ETC. ETC. ETC.!!! */
1763 FL char const *
1764 n_addrspec_with_guts(struct n_addrguts *agp, char const *name, bool_t doskin,
1765 bool_t issingle_hack){
1766 char const *cp;
1767 char *cp2, *bufend, *nbuf, c;
1768 enum{
1769 a_NONE,
1770 a_GOTLT = 1<<0,
1771 a_GOTADDR = 1<<1,
1772 a_GOTSPACE = 1<<2,
1773 a_LASTSP = 1<<3
1774 } flags;
1775 NYD_ENTER;
1777 memset(agp, 0, sizeof *agp);
1779 if((agp->ag_input = name) == NULL || (agp->ag_ilen = strlen(name)) == 0){
1780 agp->ag_skinned = n_UNCONST(n_empty); /* ok: NAME_SALLOC is not set */
1781 agp->ag_slen = 0;
1782 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
1783 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
1784 goto jleave;
1785 }else if(!doskin){
1786 /*agp->ag_iaddr_start = 0;*/
1787 agp->ag_iaddr_aend = agp->ag_ilen;
1788 agp->ag_skinned = n_UNCONST(name); /* (NAME_SALLOC not set) */
1789 agp->ag_slen = agp->ag_ilen;
1790 agp->ag_n_flags = NAME_SKINNED;
1791 goto jcheck;
1794 flags = a_NONE;
1795 nbuf = n_lofi_alloc(agp->ag_ilen +1);
1796 /*agp->ag_iaddr_start = 0;*/
1797 cp2 = bufend = nbuf;
1799 /* TODO This is complete crap and should use a token parser */
1800 for(cp = name++; (c = *cp++) != '\0';){
1801 switch (c) {
1802 case '(':
1803 cp = skip_comment(cp);
1804 flags &= ~a_LASTSP;
1805 break;
1806 case '"':
1807 /* Start of a "quoted-string". Copy it in its entirety */
1808 /* XXX RFC: quotes are "semantically invisible"
1809 * XXX But it was explicitly added (Changelog.Heirloom,
1810 * XXX [9.23] released 11/15/00, "Do not remove quotes
1811 * XXX when skinning names"? No more info.. */
1812 *cp2++ = c;
1813 while ((c = *cp) != '\0') { /* TODO improve */
1814 ++cp;
1815 if (c == '"') {
1816 *cp2++ = c;
1817 break;
1819 if (c != '\\')
1820 *cp2++ = c;
1821 else if ((c = *cp) != '\0') {
1822 *cp2++ = c;
1823 ++cp;
1826 flags &= ~a_LASTSP;
1827 break;
1828 case ' ':
1829 case '\t':
1830 if((flags & (a_GOTADDR | a_GOTSPACE)) == a_GOTADDR){
1831 flags |= a_GOTSPACE;
1832 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1834 if (cp[0] == 'a' && cp[1] == 't' && blankchar(cp[2]))
1835 cp += 3, *cp2++ = '@';
1836 else if (cp[0] == '@' && blankchar(cp[1]))
1837 cp += 2, *cp2++ = '@';
1838 else
1839 flags |= a_LASTSP;
1840 break;
1841 case '<':
1842 agp->ag_iaddr_start = PTR2SIZE(cp - (name - 1));
1843 cp2 = bufend;
1844 flags &= ~(a_GOTSPACE | a_LASTSP);
1845 flags |= a_GOTLT | a_GOTADDR;
1846 break;
1847 case '>':
1848 if(flags & a_GOTLT){
1849 /* (_addrspec_check() verifies these later!) */
1850 flags &= ~(a_GOTLT | a_LASTSP);
1851 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1853 /* Skip over the entire remaining field */
1854 while((c = *cp) != '\0' && c != ','){
1855 ++cp;
1856 if (c == '(')
1857 cp = skip_comment(cp);
1858 else if (c == '"')
1859 while ((c = *cp) != '\0') {
1860 ++cp;
1861 if (c == '"')
1862 break;
1863 if (c == '\\' && *cp != '\0')
1864 ++cp;
1867 break;
1869 /* FALLTHRU */
1870 default:
1871 if(flags & a_LASTSP){
1872 flags &= ~a_LASTSP;
1873 if(flags & a_GOTADDR)
1874 *cp2++ = ' ';
1876 *cp2++ = c;
1877 /* This character is forbidden here, but it may nonetheless be
1878 * present: ensure we turn this into something valid! (E.g., if the
1879 * next character would be a "..) */
1880 if(c == '\\' && *cp != '\0')
1881 *cp2++ = *cp++;
1882 if(c == ',' && !issingle_hack){
1883 if(!(flags & a_GOTLT)){
1884 *cp2++ = ' ';
1885 for(; blankchar(*cp); ++cp)
1887 flags &= ~a_LASTSP;
1888 bufend = cp2;
1890 }else if(!(flags & a_GOTADDR)){
1891 flags |= a_GOTADDR;
1892 agp->ag_iaddr_start = PTR2SIZE(cp - name);
1896 --name;
1897 agp->ag_slen = PTR2SIZE(cp2 - nbuf);
1898 if (agp->ag_iaddr_aend == 0)
1899 agp->ag_iaddr_aend = agp->ag_ilen;
1900 /* Misses > */
1901 else if (agp->ag_iaddr_aend < agp->ag_iaddr_start) {
1902 cp2 = n_autorec_alloc(agp->ag_ilen + 1 +1);
1903 memcpy(cp2, agp->ag_input, agp->ag_ilen);
1904 agp->ag_iaddr_aend = agp->ag_ilen;
1905 cp2[agp->ag_ilen++] = '>';
1906 cp2[agp->ag_ilen] = '\0';
1908 agp->ag_skinned = savestrbuf(nbuf, agp->ag_slen);
1909 n_lofi_free(nbuf);
1910 agp->ag_n_flags = NAME_NAME_SALLOC | NAME_SKINNED;
1911 jcheck:
1912 if(a_head_addrspec_check(agp, doskin) <= FAL0)
1913 name = NULL;
1914 else
1915 name = agp->ag_input;
1916 jleave:
1917 NYD_LEAVE;
1918 return name;
1921 FL char *
1922 realname(char const *name)
1924 char const *cp, *cq, *cstart = NULL, *cend = NULL;
1925 char *rname, *rp;
1926 struct str in, out;
1927 int quoted, good, nogood;
1928 NYD_ENTER;
1930 if ((cp = n_UNCONST(name)) == NULL)
1931 goto jleave;
1932 for (; *cp != '\0'; ++cp) {
1933 switch (*cp) {
1934 case '(':
1935 if (cstart != NULL) {
1936 /* More than one comment in address, doesn't make sense to display
1937 * it without context. Return the entire field */
1938 cp = mime_fromaddr(name);
1939 goto jleave;
1941 cstart = cp++;
1942 cp = skip_comment(cp);
1943 cend = cp--;
1944 if (cend <= cstart)
1945 cend = cstart = NULL;
1946 break;
1947 case '"':
1948 while (*cp) {
1949 if (*++cp == '"')
1950 break;
1951 if (*cp == '\\' && cp[1])
1952 ++cp;
1954 break;
1955 case '<':
1956 if (cp > name) {
1957 cstart = name;
1958 cend = cp;
1960 break;
1961 case ',':
1962 /* More than one address. Just use the first one */
1963 goto jbrk;
1967 jbrk:
1968 if (cstart == NULL) {
1969 if (*name == '<') {
1970 /* If name contains only a route-addr, the surrounding angle brackets
1971 * don't serve any useful purpose when displaying, so remove */
1972 cp = prstr(skin(name));
1973 } else
1974 cp = mime_fromaddr(name);
1975 goto jleave;
1978 /* Strip quotes. Note that quotes that appear within a MIME encoded word are
1979 * not stripped. The idea is to strip only syntactical relevant things (but
1980 * this is not necessarily the most sensible way in practice) */
1981 rp = rname = ac_alloc(PTR2SIZE(cend - cstart +1));
1982 quoted = 0;
1983 for (cp = cstart; cp < cend; ++cp) {
1984 if (*cp == '(' && !quoted) {
1985 cq = skip_comment(++cp);
1986 if (PTRCMP(--cq, >, cend))
1987 cq = cend;
1988 while (cp < cq) {
1989 if (*cp == '\\' && PTRCMP(cp + 1, <, cq))
1990 ++cp;
1991 *rp++ = *cp++;
1993 } else if (*cp == '\\' && PTRCMP(cp + 1, <, cend))
1994 *rp++ = *++cp;
1995 else if (*cp == '"') {
1996 quoted = !quoted;
1997 continue;
1998 } else
1999 *rp++ = *cp;
2001 *rp = '\0';
2002 in.s = rname;
2003 in.l = rp - rname;
2004 mime_fromhdr(&in, &out, TD_ISPR | TD_ICONV);
2005 ac_free(rname);
2006 rname = savestr(out.s);
2007 free(out.s);
2009 while (blankchar(*rname))
2010 ++rname;
2011 for (rp = rname; *rp != '\0'; ++rp)
2013 while (PTRCMP(--rp, >=, rname) && blankchar(*rp))
2014 *rp = '\0';
2015 if (rp == rname) {
2016 cp = mime_fromaddr(name);
2017 goto jleave;
2020 /* mime_fromhdr() has converted all nonprintable characters to question
2021 * marks now. These and blanks are considered uninteresting; if the
2022 * displayed part of the real name contains more than 25% of them, it is
2023 * probably better to display the plain email address instead */
2024 good = 0;
2025 nogood = 0;
2026 for (rp = rname; *rp != '\0' && PTRCMP(rp, <, rname + 20); ++rp)
2027 if (*rp == '?' || blankchar(*rp))
2028 ++nogood;
2029 else
2030 ++good;
2031 cp = (good * 3 < nogood) ? prstr(skin(name)) : rname;
2032 jleave:
2033 NYD_LEAVE;
2034 return n_UNCONST(cp);
2037 FL char *
2038 name1(struct message *mp, int reptype)
2040 char *namebuf, *cp, *cp2, *linebuf = NULL /* TODO line pool */;
2041 size_t namesize, linesize = 0;
2042 FILE *ibuf;
2043 int f1st = 1;
2044 NYD_ENTER;
2046 if ((cp = hfield1("from", mp)) != NULL && *cp != '\0')
2047 goto jleave;
2048 if (reptype == 0 && (cp = hfield1("sender", mp)) != NULL && *cp != '\0')
2049 goto jleave;
2051 namebuf = smalloc(namesize = 1);
2052 namebuf[0] = 0;
2053 if (mp->m_flag & MNOFROM)
2054 goto jout;
2055 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2056 goto jout;
2057 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2058 goto jout;
2060 jnewname:
2061 if (namesize <= linesize)
2062 namebuf = srealloc(namebuf, namesize = linesize +1);
2063 for (cp = linebuf; *cp != '\0' && *cp != ' '; ++cp)
2065 for (; blankchar(*cp); ++cp)
2067 for (cp2 = namebuf + strlen(namebuf);
2068 *cp && !blankchar(*cp) && PTRCMP(cp2, <, namebuf + namesize -1);)
2069 *cp2++ = *cp++;
2070 *cp2 = '\0';
2072 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2073 goto jout;
2074 if ((cp = strchr(linebuf, 'F')) == NULL)
2075 goto jout;
2076 if (strncmp(cp, "From", 4))
2077 goto jout;
2078 if (namesize <= linesize)
2079 namebuf = srealloc(namebuf, namesize = linesize + 1);
2081 while ((cp = strchr(cp, 'r')) != NULL) {
2082 if (!strncmp(cp, "remote", 6)) {
2083 if ((cp = strchr(cp, 'f')) == NULL)
2084 break;
2085 if (strncmp(cp, "from", 4) != 0)
2086 break;
2087 if ((cp = strchr(cp, ' ')) == NULL)
2088 break;
2089 cp++;
2090 if (f1st) {
2091 strncpy(namebuf, cp, namesize);
2092 f1st = 0;
2093 } else {
2094 cp2 = strrchr(namebuf, '!') + 1;
2095 strncpy(cp2, cp, PTR2SIZE(namebuf + namesize - cp2));
2097 namebuf[namesize - 2] = '!';
2098 namebuf[namesize - 1] = '\0';
2099 goto jnewname;
2101 cp++;
2103 jout:
2104 if (*namebuf != '\0' || ((cp = hfield1("return-path", mp))) == NULL ||
2105 *cp == '\0')
2106 cp = savestr(namebuf);
2108 if (linebuf != NULL)
2109 free(linebuf);
2110 free(namebuf);
2111 jleave:
2112 NYD_LEAVE;
2113 return cp;
2116 FL char const *
2117 subject_re_trim(char const *s){
2118 struct{
2119 ui8_t len;
2120 char dat[7];
2121 }const *pp, ignored[] = { /* Update *reply-strings* manual upon change! */
2122 {3, "re:"},
2123 {3, "aw:"}, {5, "antw:"}, /* de */
2124 {3, "wg:"}, /* Seen too often in the wild */
2125 {0, ""}
2128 bool_t any;
2129 char *re_st, *re_st_x;
2130 char const *orig_s;
2131 size_t re_l;
2132 NYD_ENTER;
2134 any = FAL0;
2135 orig_s = s;
2136 re_st = NULL;
2137 n_UNINIT(re_l, 0);
2139 if((re_st_x = ok_vlook(reply_strings)) != NULL &&
2140 (re_l = strlen(re_st_x)) > 0){
2141 re_st = n_lofi_alloc(++re_l * 2);
2142 memcpy(re_st, re_st_x, re_l);
2145 jouter:
2146 while(*s != '\0'){
2147 while(spacechar(*s))
2148 ++s;
2150 for(pp = ignored; pp->len > 0; ++pp)
2151 if(is_asccaseprefix(pp->dat, s)){
2152 s += pp->len;
2153 any = TRU1;
2154 goto jouter;
2157 if(re_st != NULL){
2158 char *cp;
2160 memcpy(re_st_x = &re_st[re_l], re_st, re_l);
2161 while((cp = n_strsep(&re_st_x, ',', TRU1)) != NULL)
2162 if(is_asccaseprefix(cp, s)){
2163 s += strlen(cp);
2164 any = TRU1;
2165 goto jouter;
2168 break;
2171 if(re_st != NULL)
2172 n_lofi_free(re_st);
2173 NYD_LEAVE;
2174 return any ? s : orig_s;
2177 FL int
2178 msgidcmp(char const *s1, char const *s2)
2180 int q1 = 0, q2 = 0, c1, c2;
2181 NYD_ENTER;
2183 while(*s1 == '<')
2184 ++s1;
2185 while(*s2 == '<')
2186 ++s2;
2188 do {
2189 c1 = msgidnextc(&s1, &q1);
2190 c2 = msgidnextc(&s2, &q2);
2191 if (c1 != c2)
2192 break;
2193 } while (c1 && c2);
2194 NYD_LEAVE;
2195 return c1 - c2;
2198 FL char const *
2199 fakefrom(struct message *mp)
2201 char const *name;
2202 NYD_ENTER;
2204 if (((name = skin(hfield1("return-path", mp))) == NULL || *name == '\0' ) &&
2205 ((name = skin(hfield1("from", mp))) == NULL || *name == '\0'))
2206 /* XXX MAILER-DAEMON is what an old MBOX manual page says.
2207 * RFC 4155 however requires a RFC 5322 (2822) conforming
2208 * "addr-spec", but we simply can't provide that */
2209 name = "MAILER-DAEMON";
2210 NYD_LEAVE;
2211 return name;
2214 FL char const *
2215 fakedate(time_t t)
2217 char *cp, *cq;
2218 NYD_ENTER;
2220 cp = ctime(&t);
2221 for (cq = cp; *cq != '\0' && *cq != '\n'; ++cq)
2223 *cq = '\0';
2224 cp = savestr(cp);
2225 NYD_LEAVE;
2226 return cp;
2229 #ifdef HAVE_IMAP_SEARCH
2230 FL time_t
2231 unixtime(char const *fromline)
2233 char const *fp, *xp;
2234 time_t t;
2235 si32_t i, year, month, day, hour, minute, second, tzdiff;
2236 struct tm *tmptr;
2237 NYD2_ENTER;
2239 for (fp = fromline; *fp != '\0' && *fp != '\n'; ++fp)
2241 fp -= 24;
2242 if (PTR2SIZE(fp - fromline) < 7)
2243 goto jinvalid;
2244 if (fp[3] != ' ')
2245 goto jinvalid;
2246 for (i = 0;;) {
2247 if (!strncmp(fp + 4, n_month_names[i], 3))
2248 break;
2249 if (n_month_names[++i][0] == '\0')
2250 goto jinvalid;
2252 month = i + 1;
2253 if (fp[7] != ' ')
2254 goto jinvalid;
2255 n_idec_si32_cp(&day, &fp[8], 10, &xp);
2256 if (*xp != ' ' || xp != fp + 10)
2257 goto jinvalid;
2258 n_idec_si32_cp(&hour, &fp[11], 10, &xp);
2259 if (*xp != ':' || xp != fp + 13)
2260 goto jinvalid;
2261 n_idec_si32_cp(&minute, &fp[14], 10, &xp);
2262 if (*xp != ':' || xp != fp + 16)
2263 goto jinvalid;
2264 n_idec_si32_cp(&second, &fp[17], 10, &xp);
2265 if (*xp != ' ' || xp != fp + 19)
2266 goto jinvalid;
2267 n_idec_si32_cp(&year, &fp[20], 10, &xp);
2268 if (xp != fp + 24)
2269 goto jinvalid;
2270 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
2271 goto jinvalid;
2272 tzdiff = t - mktime(gmtime(&t));
2273 tmptr = localtime(&t);
2274 if (tmptr->tm_isdst > 0)
2275 tzdiff += 3600;
2276 t -= tzdiff;
2277 jleave:
2278 NYD2_LEAVE;
2279 return t;
2280 jinvalid:
2281 t = n_time_epoch();
2282 goto jleave;
2284 #endif /* HAVE_IMAP_SEARCH */
2286 FL time_t
2287 rfctime(char const *date) /* TODO n_idec_ return tests */
2289 char const *cp, *x;
2290 time_t t;
2291 si32_t i, year, month, day, hour, minute, second;
2292 NYD2_ENTER;
2294 cp = date;
2296 if ((cp = nexttoken(cp)) == NULL)
2297 goto jinvalid;
2298 if (alphachar(cp[0]) && alphachar(cp[1]) && alphachar(cp[2]) &&
2299 cp[3] == ',') {
2300 if ((cp = nexttoken(&cp[4])) == NULL)
2301 goto jinvalid;
2303 n_idec_si32_cp(&day, cp, 10, &x);
2304 if ((cp = nexttoken(x)) == NULL)
2305 goto jinvalid;
2306 for (i = 0;;) {
2307 if (!strncmp(cp, n_month_names[i], 3))
2308 break;
2309 if (n_month_names[++i][0] == '\0')
2310 goto jinvalid;
2312 month = i + 1;
2313 if ((cp = nexttoken(&cp[3])) == NULL)
2314 goto jinvalid;
2315 /* RFC 5322, 4.3:
2316 * Where a two or three digit year occurs in a date, the year is to be
2317 * interpreted as follows: If a two digit year is encountered whose
2318 * value is between 00 and 49, the year is interpreted by adding 2000,
2319 * ending up with a value between 2000 and 2049. If a two digit year
2320 * is encountered with a value between 50 and 99, or any three digit
2321 * year is encountered, the year is interpreted by adding 1900 */
2322 n_idec_si32_cp(&year, cp, 10, &x);
2323 i = (int)PTR2SIZE(x - cp);
2324 if (i == 2 && year >= 0 && year <= 49)
2325 year += 2000;
2326 else if (i == 3 || (i == 2 && year >= 50 && year <= 99))
2327 year += 1900;
2328 if ((cp = nexttoken(x)) == NULL)
2329 goto jinvalid;
2330 n_idec_si32_cp(&hour, cp, 10, &x);
2331 if (*x != ':')
2332 goto jinvalid;
2333 cp = &x[1];
2334 n_idec_si32_cp(&minute, cp, 10, &x);
2335 if (*x == ':') {
2336 cp = &x[1];
2337 n_idec_si32_cp(&second, cp, 10, &x);
2338 } else
2339 second = 0;
2341 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
2342 goto jinvalid;
2343 if ((cp = nexttoken(x)) != NULL) {
2344 char buf[3];
2345 int sign = 1;
2347 switch (*cp) {
2348 case '+':
2349 sign = -1;
2350 /* FALLTHRU */
2351 case '-':
2352 ++cp;
2353 break;
2355 if (digitchar(cp[0]) && digitchar(cp[1]) && digitchar(cp[2]) &&
2356 digitchar(cp[3])) {
2357 si64_t tadj;
2359 buf[2] = '\0';
2360 buf[0] = cp[0];
2361 buf[1] = cp[1];
2362 n_idec_si32_cp(&i, buf, 10, NULL);
2363 tadj = (si64_t)i * 3600; /* XXX */
2364 buf[0] = cp[2];
2365 buf[1] = cp[3];
2366 n_idec_si32_cp(&i, buf, 10, NULL);
2367 tadj += (si64_t)i * 60; /* XXX */
2368 if (sign < 0)
2369 tadj = -tadj;
2370 t += (time_t)tadj;
2372 /* TODO WE DO NOT YET PARSE (OBSOLETE) ZONE NAMES
2373 * TODO once again, Christos Zoulas and NetBSD Mail have done
2374 * TODO a really good job already, but using strptime(3), which
2375 * TODO is not portable. Nonetheless, WE must improve, not
2376 * TODO at last because we simply ignore obsolete timezones!!
2377 * TODO See RFC 5322, 4.3! */
2379 jleave:
2380 NYD2_LEAVE;
2381 return t;
2382 jinvalid:
2383 t = 0;
2384 goto jleave;
2387 FL time_t
2388 combinetime(int year, int month, int day, int hour, int minute, int second){
2389 size_t const jdn_epoch = 2440588;
2390 bool_t const y2038p = (sizeof(time_t) == 4);
2392 size_t jdn;
2393 time_t t;
2394 NYD2_ENTER;
2396 if(UICMP(32, second, >/*XXX leap=*/, n_DATE_SECSMIN) ||
2397 UICMP(32, minute, >=, n_DATE_MINSHOUR) ||
2398 UICMP(32, hour, >=, n_DATE_HOURSDAY) ||
2399 day < 1 || day > 31 ||
2400 month < 1 || month > 12 ||
2401 year < 1970)
2402 goto jerr;
2404 if(year >= 1970 + ((y2038p ? SI32_MAX : SI64_MAX) /
2405 (n_DATE_SECSDAY * n_DATE_DAYSYEAR))){
2406 /* Be a coward regarding Y2038, many people (mostly myself, that is) do
2407 * test by stepping second-wise around the flip. Don't care otherwise */
2408 if(!y2038p)
2409 goto jerr;
2410 if(year > 2038 || month > 1 || day > 19 ||
2411 hour > 3 || minute > 14 || second > 7)
2412 goto jerr;
2415 t = second;
2416 t += minute * n_DATE_SECSMIN;
2417 t += hour * n_DATE_SECSHOUR;
2419 jdn = a_head_gregorian_to_jdn(year, month, day);
2420 jdn -= jdn_epoch;
2421 t += (time_t)jdn * n_DATE_SECSDAY;
2422 jleave:
2423 NYD2_LEAVE;
2424 return t;
2425 jerr:
2426 t = (time_t)-1;
2427 goto jleave;
2430 FL void
2431 substdate(struct message *m)
2433 char const *cp;
2434 NYD_ENTER;
2436 /* Determine the date to print in faked 'From ' lines. This is traditionally
2437 * the date the message was written to the mail file. Try to determine this
2438 * using RFC message header fields, or fall back to current time */
2439 if ((cp = hfield1("received", m)) != NULL) {
2440 while ((cp = nexttoken(cp)) != NULL && *cp != ';') {
2442 ++cp;
2443 while (alnumchar(*cp));
2445 if (cp && *++cp)
2446 m->m_time = rfctime(cp);
2448 if (m->m_time == 0 || m->m_time > time_current.tc_time) {
2449 if ((cp = hfield1("date", m)) != NULL)
2450 m->m_time = rfctime(cp);
2452 if (m->m_time == 0 || m->m_time > time_current.tc_time)
2453 m->m_time = time_current.tc_time;
2454 NYD_LEAVE;
2457 FL void
2458 setup_from_and_sender(struct header *hp)
2460 char const *addr;
2461 struct name *np;
2462 NYD_ENTER;
2464 /* If -t parsed or composed From: then take it. With -t we otherwise
2465 * want -r to be honoured in favour of *from* in order to have
2466 * a behaviour that is compatible with what users would expect from e.g.
2467 * postfix(1) */
2468 if ((np = hp->h_from) != NULL ||
2469 ((n_psonce & n_PSO_t_FLAG) && (np = n_poption_arg_r) != NULL)) {
2471 } else if ((addr = myaddrs(hp)) != NULL)
2472 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
2473 hp->h_from = np;
2475 if ((np = hp->h_sender) != NULL) {
2477 } else if ((addr = ok_vlook(sender)) != NULL)
2478 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
2479 hp->h_sender = np;
2481 NYD_LEAVE;
2484 FL struct name const *
2485 check_from_and_sender(struct name const *fromfield,
2486 struct name const *senderfield)
2488 struct name const *rv = NULL;
2489 NYD_ENTER;
2491 if (senderfield != NULL) {
2492 if (senderfield->n_flink != NULL) {
2493 n_err(_("The Sender: field may contain only one address\n"));
2494 goto jleave;
2496 rv = senderfield;
2499 if (fromfield != NULL) {
2500 if (fromfield->n_flink != NULL && senderfield == NULL) {
2501 n_err(_("A Sender: is required when there are multiple "
2502 "addresses in From:\n"));
2503 goto jleave;
2505 if (rv == NULL)
2506 rv = fromfield;
2509 if (rv == NULL)
2510 rv = (struct name*)0x1;
2511 jleave:
2512 NYD_LEAVE;
2513 return rv;
2516 #ifdef HAVE_XSSL
2517 FL char *
2518 getsender(struct message *mp)
2520 char *cp;
2521 struct name *np;
2522 NYD_ENTER;
2524 if ((cp = hfield1("from", mp)) == NULL ||
2525 (np = lextract(cp, GEXTRA | GSKIN)) == NULL)
2526 cp = NULL;
2527 else
2528 cp = (np->n_flink != NULL) ? skin(hfield1("sender", mp)) : np->n_name;
2529 NYD_LEAVE;
2530 return cp;
2532 #endif
2534 FL int
2535 grab_headers(enum n_go_input_flags gif, struct header *hp, enum gfield gflags,
2536 int subjfirst)
2538 /* TODO grab_headers: again, check counts etc. against RFC;
2539 * TODO (now assumes check_from_and_sender() is called afterwards ++ */
2540 int errs;
2541 int volatile comma;
2542 NYD_ENTER;
2544 errs = 0;
2545 comma = (ok_blook(bsdcompat) || ok_blook(bsdmsgs)) ? 0 : GCOMMA;
2547 if (gflags & GTO)
2548 hp->h_to = grab_names(gif, "To: ", hp->h_to, comma, GTO | GFULL);
2549 if (subjfirst && (gflags & GSUBJECT))
2550 hp->h_subject = n_go_input_cp(gif, "Subject: ", hp->h_subject);
2551 if (gflags & GCC)
2552 hp->h_cc = grab_names(gif, "Cc: ", hp->h_cc, comma, GCC | GFULL);
2553 if (gflags & GBCC)
2554 hp->h_bcc = grab_names(gif, "Bcc: ", hp->h_bcc, comma, GBCC | GFULL);
2556 if (gflags & GEXTRA) {
2557 if (hp->h_from == NULL)
2558 hp->h_from = lextract(myaddrs(hp), GEXTRA | GFULL | GFULLEXTRA);
2559 hp->h_from = grab_names(gif, "From: ", hp->h_from, comma,
2560 GEXTRA | GFULL | GFULLEXTRA);
2561 if (hp->h_replyto == NULL)
2562 hp->h_replyto = lextract(ok_vlook(replyto), GEXTRA | GFULL);
2563 hp->h_replyto = grab_names(gif, "Reply-To: ", hp->h_replyto, comma,
2564 GEXTRA | GFULL);
2565 if (hp->h_sender == NULL)
2566 hp->h_sender = extract(ok_vlook(sender), GEXTRA | GFULL);
2567 hp->h_sender = grab_names(gif, "Sender: ", hp->h_sender, comma,
2568 GEXTRA | GFULL);
2571 if (!subjfirst && (gflags & GSUBJECT))
2572 hp->h_subject = n_go_input_cp(gif, "Subject: ", hp->h_subject);
2574 NYD_LEAVE;
2575 return errs;
2578 FL bool_t
2579 header_match(struct message *mp, struct search_expr const *sep)
2581 struct str in, out;
2582 FILE *ibuf;
2583 int lc;
2584 size_t linesize = 0; /* TODO line pool */
2585 char *linebuf = NULL, *colon;
2586 bool_t rv = FAL0;
2587 NYD_ENTER;
2589 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2590 goto jleave;
2591 if ((lc = mp->m_lines - 1) < 0)
2592 goto jleave;
2594 if ((mp->m_flag & MNOFROM) == 0 &&
2595 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2596 goto jleave;
2597 while (lc > 0) {
2598 if (gethfield(ibuf, &linebuf, &linesize, lc, &colon) <= 0)
2599 break;
2600 if (blankchar(*++colon))
2601 ++colon;
2602 in.l = strlen(in.s = colon);
2603 mime_fromhdr(&in, &out, TD_ICONV);
2604 #ifdef HAVE_REGEX
2605 if (sep->ss_sexpr == NULL)
2606 rv = (regexec(&sep->ss_regex, out.s, 0,NULL, 0) != REG_NOMATCH);
2607 else
2608 #endif
2609 rv = substr(out.s, sep->ss_sexpr);
2610 free(out.s);
2611 if (rv)
2612 break;
2615 jleave:
2616 if (linebuf != NULL)
2617 free(linebuf);
2618 NYD_LEAVE;
2619 return rv;
2622 FL struct n_header_field *
2623 n_customhdr_query(void){
2624 char const *vp;
2625 struct n_header_field *rv, **tail, *hfp;
2626 NYD_ENTER;
2628 rv = NULL;
2630 if((vp = ok_vlook(customhdr)) != NULL){
2631 char *buf;
2633 tail = &rv;
2634 buf = savestr(vp);
2635 jch_outer:
2636 while((vp = a_head_customhdr__sep(&buf)) != NULL){
2637 ui32_t nl, bl;
2638 char const *nstart, *cp;
2640 for(nstart = cp = vp;; ++cp){
2641 if(fieldnamechar(*cp))
2642 continue;
2643 if(*cp == '\0'){
2644 if(cp == nstart){
2645 n_err(_("Invalid nameless *customhdr* entry\n"));
2646 goto jch_outer;
2648 }else if(*cp != ':' && !blankchar(*cp)){
2649 jch_badent:
2650 n_err(_("Invalid *customhdr* entry: %s\n"), vp);
2651 goto jch_outer;
2653 break;
2655 nl = (ui32_t)PTR2SIZE(cp - nstart);
2657 while(blankchar(*cp))
2658 ++cp;
2659 if(*cp++ != ':')
2660 goto jch_badent;
2661 while(blankchar(*cp))
2662 ++cp;
2663 bl = (ui32_t)strlen(cp) +1;
2665 *tail =
2666 hfp = salloc(n_VSTRUCT_SIZEOF(struct n_header_field, hf_dat) +
2667 nl +1 + bl);
2668 tail = &hfp->hf_next;
2669 hfp->hf_next = NULL;
2670 hfp->hf_nl = nl;
2671 hfp->hf_bl = bl - 1;
2672 memcpy(hfp->hf_dat, nstart, nl);
2673 hfp->hf_dat[nl++] = '\0';
2674 memcpy(hfp->hf_dat + nl, cp, bl);
2677 NYD_LEAVE;
2678 return rv;
2681 /* s-it-mode */