MLE: stop an "unused" CC warning
[s-mailx.git] / head.c
blob5648f6ea32db43c3530cc6107f40c32255da2edf
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 - 2016 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 _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)) >= _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 (!(options & OPT_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 && errno == EINVAL);
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(agp->ag_slen - 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 (options & OPT_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(agp->ag_slen - 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 {char c; unsigned char u; ui32_t ui32;} 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 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 else{
519 /* If we seem to know that this is an address. Perform some simple checks
520 * for dot-atom as of RFC 5322 and ensure we fix that "Dr. problem".
521 * TODO We need a real RFC 5322 parser which produces tokens, to store them
522 * TODO in a list including typeattr, as in atom-text, dot-atom-text,
523 * TODO quote, comment address, so then we could simply join as many
524 * TODO consecutive -text tokens and convert them to quote as possible
525 * TODO For now bad and expensive; wrong for some comments in tokens.
526 * TODO In fact i haven't read RFC 5322 so much, esp. before doing this */
527 struct n_string ost, *ostp;
528 char lastc;
529 size_t rangestart, lastpoi;
530 char const *cp, *cpmax, *xp;
532 #ifdef HAVE_IDNA
533 if(use_idna == 2)
534 agp = a_head_idna_apply(agp);
535 #endif
537 ostp = n_string_creat_auto(&ost);
538 if((c.ui32 = agp->ag_ilen) <= UI32_MAX >> 1)
539 ostp = n_string_reserve(ostp, c.ui32 <<= 1);
541 hadat = FAL0;
542 cp = agp->ag_input;
543 if((c.ui32 = agp->ag_iaddr_start) > 0)
544 --c.ui32;
545 cpmax = &cp[c.ui32];
546 rangestart = 0;
548 while(cp < cpmax && blankchar(*cp))
549 ++cp;
551 lastc = '\0';
552 jdotatom_redo:
553 for(lastpoi = UIZ_MAX; cp < cpmax;){
554 switch((c.c = *cp)){
555 case '(':
556 jdotatom_comment:
557 lastc = 0;
558 if((c.ui32 = ostp->s_len) > 0){
559 while(c.ui32 > 0 && blankchar(ostp->s_dat[c.ui32 - 1]))
560 --c.ui32;
561 ostp = n_string_trunc(ostp, c.ui32);
563 if(c.ui32 > 0){
564 --c.ui32;
565 /* Can we join two comments? */
566 if(ostp->s_dat[c.ui32] == ')'){
567 ostp->s_dat[c.ui32] = ' ';
568 lastc = 1;
570 /* Otherwise ensure it is separated! */
571 else if(!blankchar(ostp->s_dat[c.ui32]))
572 ostp = n_string_push_c(ostp, ' ');
575 if(!lastc)
576 ostp = n_string_push_c(ostp, '(');
578 xp = skip_comment(++cp);
579 c.ui32 = (ui32_t)PTR2SIZE(xp - cp);
580 if(c.ui32 > 0){
581 if(xp[-1] == ')')
582 --c.ui32;
583 /* Run out of buffer while searching for comment close, this is
584 * artificial and we strip all blanks at EOS */
585 else while(blankchar(xp[-1])){
586 --xp;
587 if(--c.ui32 == 0)
588 break;
591 ostp = n_string_push_buf(ostp, cp, c.ui32);
593 ostp = n_string_push_c(ostp, ')');
594 lastpoi = ostp->s_len - 1;
595 lastc = '\0';
596 cp = xp;
597 break;
598 case '"':
599 lastc = 0;
600 jdotatom_quote:
601 xp = ++cp;
602 if((c.ui32 = ostp->s_len) > 0){
603 while(c.ui32 > 0 && blankchar(ostp->s_dat[c.ui32 - 1]))
604 --c.ui32;
605 ostp = n_string_trunc(ostp, c.ui32);
607 if(c.ui32 > 0){
608 --c.ui32;
609 /* Can we join two quotes? */
610 if(ostp->s_dat[c.ui32] == '"'){
611 ostp->s_dat[c.ui32] = ' ';
612 lastc = 1;
614 /* Otherwise ensure it is separated! */
615 else if(!blankchar(ostp->s_dat[c.ui32]))
616 ostp = n_string_push_c(ostp, ' ');
619 if(!lastc)
620 ostp = n_string_push_c(ostp, '"');
622 for(; xp < cpmax; ++xp){
623 if((c.c = *xp) == '"')
624 break;
625 if(c.c == '\\' && xp[1] != '\0')
626 ++xp;
628 c.ui32 = (ui32_t)PTR2SIZE(xp - cp);
629 if(c.ui32 > 0){
630 if(xp != cpmax && *xp == '"')
631 ++xp;
632 /* Run out of buffer while searching for quote close, this is
633 * artificial and we strip all blanks at EOS */
634 else while(blankchar(xp[-1])){
635 --xp;
636 if(--c.ui32 == 0)
637 break;
640 ostp = n_string_push_buf(ostp, cp, c.ui32);
642 ostp = n_string_push_c(ostp, '"');
643 lastpoi = ostp->s_len - 1;
644 lastc = '\0';
645 cp = xp;
646 break;
647 case '.':
648 if(lastpoi != UIZ_MAX){
649 if(ostp->s_dat[lastpoi] == '"')
650 /* Simply join backward to a yet existing quote */
651 ostp = n_string_cut(ostp, lastpoi, 1);
652 }else
653 /* Otherwise convert anything before to a quote */
654 ostp = n_string_insert_c(ostp, rangestart, '"');
656 for(xp = cp; cp < cpmax; ++cp){
657 /* If we reach another quote, join forward */
658 if((c.c = *cp) == '"'){
659 lastc = 1;
660 goto jdotatom_quote;
662 else if(c.c == '('){
663 /* End the quote before the whitespace before the comment */
664 for(c.ui32 = 0; blankchar(cp[-1 - c.ui32]); ++c.ui32)
666 if(c.ui32 > 0)
667 ostp = n_string_trunc(ostp, ostp->s_len - c.ui32);
668 ostp = n_string_push_c(ostp, '"');
669 goto jdotatom_comment;
671 ostp = n_string_push_c(ostp, c.c);
674 /* Since we have created this quote it would be false to let it end
675 * in a series of whitespace */
676 for(c.ui32 = ostp->s_len;
677 c.ui32 > 0 && blankchar(ostp->s_dat[c.ui32 - 1]); --c.ui32)
679 ostp = n_string_trunc(ostp, c.ui32);
681 ostp = n_string_push_c(ostp, '"');
682 lastpoi = ostp->s_len - 1;
683 lastc = '\0';
684 break;
685 default:
686 if(lastc == '\0' || !blankchar(c.c) || !blankchar(lastc))
687 ostp = n_string_push_c(ostp, lastc = c.c);
688 ++cp;
689 break;
693 if(hadat == FAL0){
694 hadat = TRU1;
695 if((c.ui32 = ostp->s_len) > 0 && !blankchar(ostp->s_dat[c.ui32 - 1])){
696 ostp = n_string_push_c(ostp, ' ');
697 ++c.ui32;
699 if(c.ui32 != 0)
700 ++c.ui32;
701 agp->ag_iaddr_start = c.ui32;
702 cp = &agp->ag_input[agp->ag_iaddr_aend];
703 if(cp != &agp->ag_input[agp->ag_ilen])
704 ++cp;
705 c.ui32 = (ui32_t)PTR2SIZE(cp - cpmax);
706 ostp = n_string_push_buf(ostp, cpmax, c.ui32);
707 agp->ag_iaddr_aend = ostp->s_len - 1;
708 cpmax = &agp->ag_input[agp->ag_ilen];
710 c.ui32 = (ui32_t)PTR2SIZE(cpmax - cp);
711 if(c.ui32 > 0){
712 ostp = n_string_push_c(ostp, lastc = ' ');
713 rangestart = ostp->s_len;
714 goto jdotatom_redo;
716 }else if((c.ui32 = ostp->s_len) > 0){
717 while(blankchar(ostp->s_dat[c.ui32 - 1]))
718 --c.ui32;
719 ostp = n_string_trunc(ostp, c.ui32);
722 agp->ag_input = n_string_cp(ostp);
723 agp->ag_ilen = ostp->s_len;
724 ostp = n_string_drop_ownership(ostp);
726 jleave:
727 NYD_LEAVE;
728 return ((agp->ag_n_flags & NAME_ADDRSPEC_INVALID) != 0);
731 static int
732 gethfield(FILE *f, char **linebuf, size_t *linesize, int rem, char **colon)
734 char *line2 = NULL, *cp, *cp2;
735 size_t line2size = 0;
736 int c, isenc;
737 NYD2_ENTER;
739 if (*linebuf == NULL)
740 *linebuf = srealloc(*linebuf, *linesize = 1);
741 **linebuf = '\0';
742 for (;;) {
743 if (--rem < 0) {
744 rem = -1;
745 break;
747 if ((c = readline_restart(f, linebuf, linesize, 0)) <= 0) {
748 rem = -1;
749 break;
751 for (cp = *linebuf; fieldnamechar(*cp); ++cp)
753 if (cp > *linebuf)
754 while (blankchar(*cp))
755 ++cp;
756 if (*cp != ':' || cp == *linebuf)
757 continue;
759 /* I guess we got a headline. Handle wraparound */
760 *colon = cp;
761 cp = *linebuf + c;
762 for (;;) {
763 isenc = 0;
764 while (PTRCMP(--cp, >=, *linebuf) && blankchar(*cp))
766 cp++;
767 if (rem <= 0)
768 break;
769 if (PTRCMP(cp - 8, >=, *linebuf) && cp[-1] == '=' && cp[-2] == '?')
770 isenc |= 1;
771 ungetc(c = getc(f), f);
772 if (!blankchar(c))
773 break;
774 c = readline_restart(f, &line2, &line2size, 0);
775 if (c < 0)
776 break;
777 --rem;
778 for (cp2 = line2; blankchar(*cp2); ++cp2)
780 c -= (int)PTR2SIZE(cp2 - line2);
781 if (cp2[0] == '=' && cp2[1] == '?' && c > 8)
782 isenc |= 2;
783 if (PTRCMP(cp + c, >=, *linebuf + *linesize - 2)) {
784 size_t diff = PTR2SIZE(cp - *linebuf),
785 colondiff = PTR2SIZE(*colon - *linebuf);
786 *linebuf = srealloc(*linebuf, *linesize += c + 2);
787 cp = &(*linebuf)[diff];
788 *colon = &(*linebuf)[colondiff];
790 if (isenc != 3)
791 *cp++ = ' ';
792 memcpy(cp, cp2, c);
793 cp += c;
795 *cp = '\0';
797 if (line2 != NULL)
798 free(line2);
799 break;
801 NYD2_LEAVE;
802 return rem;
805 static int
806 msgidnextc(char const **cp, int *status)
808 int c;
809 NYD2_ENTER;
811 assert(cp != NULL);
812 assert(*cp != NULL);
813 assert(status != NULL);
815 for (;;) {
816 if (*status & 01) {
817 if (**cp == '"') {
818 *status &= ~01;
819 (*cp)++;
820 continue;
822 if (**cp == '\\') {
823 (*cp)++;
824 if (**cp == '\0')
825 goto jeof;
827 goto jdfl;
829 switch (**cp) {
830 case '(':
831 *cp = skip_comment(&(*cp)[1]);
832 continue;
833 case '>':
834 case '\0':
835 jeof:
836 c = '\0';
837 goto jleave;
838 case '"':
839 (*cp)++;
840 *status |= 01;
841 continue;
842 case '@':
843 *status |= 02;
844 /*FALLTHRU*/
845 default:
846 jdfl:
847 c = *(*cp)++ & 0377;
848 c = (*status & 02) ? lowerconv(c) : c;
849 goto jleave;
852 jleave:
853 NYD2_LEAVE;
854 return c;
857 static int
858 charcount(char *str, int c)
860 char *cp;
861 int i;
862 NYD2_ENTER;
864 for (i = 0, cp = str; *cp; ++cp)
865 if (*cp == c)
866 ++i;
867 NYD2_LEAVE;
868 return i;
871 static char const *
872 nexttoken(char const *cp)
874 NYD2_ENTER;
875 for (;;) {
876 if (*cp == '\0') {
877 cp = NULL;
878 break;
881 if (*cp == '(') {
882 size_t nesting = 1;
884 do switch (*++cp) {
885 case '(':
886 ++nesting;
887 break;
888 case ')':
889 --nesting;
890 break;
891 } while (nesting > 0 && *cp != '\0'); /* XXX error? */
892 } else if (blankchar(*cp) || *cp == ',')
893 ++cp;
894 else
895 break;
897 NYD2_LEAVE;
898 return cp;
901 static char *
902 a_head_customhdr__sep(char **iolist){
903 char *cp, c, *base;
904 bool_t isesc, anyesc;
905 NYD2_ENTER;
907 for(base = *iolist; base != NULL; base = *iolist){
908 while((c = *base) != '\0' && blankspacechar(c))
909 ++base;
911 for(isesc = anyesc = FAL0, cp = base;; ++cp){
912 if(n_UNLIKELY((c = *cp) == '\0')){
913 *iolist = NULL;
914 break;
915 }else if(!isesc){
916 if(c == ','){
917 *iolist = cp + 1;
918 break;
920 isesc = (c == '\\');
921 }else{
922 isesc = FAL0;
923 anyesc |= (c == ',');
927 while(cp > base && blankspacechar(cp[-1]))
928 --cp;
929 *cp = '\0';
931 if(*base != '\0'){
932 if(anyesc){
933 char *ins;
935 for(ins = cp = base;; ++ins)
936 if((c = *cp) == '\\' && cp[1] == ','){
937 *ins = ',';
938 cp += 2;
939 }else if((*ins = (++cp, c)) == '\0')
940 break;
942 break;
945 NYD2_LEAVE;
946 return base;
949 FL char const *
950 myaddrs(struct header *hp)
952 struct name *np;
953 char const *rv, *mta;
954 NYD_ENTER;
956 if (hp != NULL && (np = hp->h_from) != NULL) {
957 if ((rv = np->n_fullname) != NULL)
958 goto jleave;
959 if ((rv = np->n_name) != NULL)
960 goto jleave;
963 if ((rv = ok_vlook(from)) != NULL)
964 goto jleave;
966 /* When invoking *sendmail* directly, it's its task to generate an otherwise
967 * undeterminable From: address. However, if the user sets *hostname*,
968 * accept his desire */
969 if (ok_vlook(hostname) != NULL)
970 goto jnodename;
971 if (ok_vlook(smtp) != NULL || /* TODO obsolete -> mta */
972 /* TODO pretty hacky for now (this entire fun), later: url_creat()! */
973 ((mta = ok_vlook(mta)) != NULL &&
974 (mta = n_servbyname(mta, NULL)) != NULL && *mta != '\0'))
975 goto jnodename;
976 jleave:
977 NYD_LEAVE;
978 return rv;
980 jnodename:{
981 char *hn, *cp;
982 size_t i;
984 hn = nodename(1);
985 i = strlen(myname) + strlen(hn) + 1 +1;
986 rv = cp = salloc(i);
987 sstpcpy(sstpcpy(sstpcpy(cp, myname), "@"), hn);
989 goto jleave;
992 FL char const *
993 myorigin(struct header *hp)
995 char const *rv = NULL, *ccp;
996 struct name *np;
997 NYD_ENTER;
999 if ((ccp = myaddrs(hp)) != NULL &&
1000 (np = lextract(ccp, GEXTRA | GFULL)) != NULL)
1001 rv = (np->n_flink != NULL) ? ok_vlook(sender) : ccp;
1002 NYD_LEAVE;
1003 return rv;
1006 FL bool_t
1007 is_head(char const *linebuf, size_t linelen, bool_t check_rfc4155)
1009 char date[FROM_DATEBUF];
1010 bool_t rv;
1011 NYD2_ENTER;
1013 if ((rv = (linelen >= 5 && !memcmp(linebuf, "From ", 5))) && check_rfc4155 &&
1014 (extract_date_from_from_(linebuf, linelen, date) <= 0 ||
1015 !_is_date(date)))
1016 rv = TRUM1;
1017 NYD2_LEAVE;
1018 return rv;
1021 FL int
1022 extract_date_from_from_(char const *line, size_t linelen,
1023 char datebuf[FROM_DATEBUF])
1025 int rv;
1026 char const *cp = line;
1027 NYD_ENTER;
1029 rv = 1;
1031 /* "From " */
1032 cp = _from__skipword(cp);
1033 if (cp == NULL)
1034 goto jerr;
1035 /* "addr-spec " */
1036 cp = _from__skipword(cp);
1037 if (cp == NULL)
1038 goto jerr;
1039 if (cp[0] == 't' && cp[1] == 't' && cp[2] == 'y') {
1040 cp = _from__skipword(cp);
1041 if (cp == NULL)
1042 goto jerr;
1044 /* It seems there are invalid MBOX archives in the wild, compare
1045 * . http://bugs.debian.org/624111
1046 * . [Mutt] #3868: mutt should error if the imported mailbox is invalid
1047 * What they do is that they obfuscate the address to "name at host",
1048 * and even "name at host dot dom dot dom. I think we should handle that */
1049 else if(cp[0] == 'a' && cp[1] == 't' && cp[2] == ' '){
1050 rv = -1;
1051 cp += 3;
1052 jat_dot:
1053 cp = _from__skipword(cp);
1054 if (cp == NULL)
1055 goto jerr;
1056 if(cp[0] == 'd' && cp[1] == 'o' && cp[2] == 't' && cp[3] == ' '){
1057 cp += 4;
1058 goto jat_dot;
1062 linelen -= PTR2SIZE(cp - line);
1063 if (linelen < _DATE_MINLEN)
1064 goto jerr;
1065 if (cp[linelen - 1] == '\n') {
1066 --linelen;
1067 /* (Rather IMAP/POP3 only) */
1068 if (cp[linelen - 1] == '\r')
1069 --linelen;
1070 if (linelen < _DATE_MINLEN)
1071 goto jerr;
1073 if (linelen >= FROM_DATEBUF)
1074 goto jerr;
1076 jleave:
1077 memcpy(datebuf, cp, linelen);
1078 datebuf[linelen] = '\0';
1079 NYD_LEAVE;
1080 return rv;
1081 jerr:
1082 cp = _("<Unknown date>");
1083 linelen = strlen(cp);
1084 if (linelen >= FROM_DATEBUF)
1085 linelen = FROM_DATEBUF;
1086 rv = 0;
1087 goto jleave;
1090 FL void
1091 extract_header(FILE *fp, struct header *hp, si8_t *checkaddr_err)
1093 /* See the prototype declaration for the hairy relationship of
1094 * options&OPT_t_FLAG and/or pstate&PS_t_FLAG in here */
1095 struct n_header_field **hftail;
1096 struct header nh, *hq = &nh;
1097 char *linebuf = NULL /* TODO line pool */, *colon;
1098 size_t linesize = 0, seenfields = 0;
1099 int lc, c;
1100 char const *val, *cp;
1101 NYD_ENTER;
1103 memset(hq, 0, sizeof *hq);
1104 if ((pstate & PS_t_FLAG) && (options & OPT_t_FLAG)) {
1105 hq->h_to = hp->h_to;
1106 hq->h_cc = hp->h_cc;
1107 hq->h_bcc = hp->h_bcc;
1109 hftail = &hq->h_user_headers;
1111 for (lc = 0; readline_restart(fp, &linebuf, &linesize, 0) > 0; ++lc)
1114 /* TODO yippieia, cat(check(lextract)) :-) */
1115 rewind(fp);
1116 while ((lc = gethfield(fp, &linebuf, &linesize, lc, &colon)) >= 0) {
1117 struct name *np;
1119 /* We explicitly allow EAF_NAME for some addressees since aliases are not
1120 * yet expanded when we parse these! */
1121 if ((val = thisfield(linebuf, "to")) != NULL) {
1122 ++seenfields;
1123 hq->h_to = cat(hq->h_to, checkaddrs(lextract(val, GTO | GFULL),
1124 EACM_NORMAL | EAF_NAME, checkaddr_err));
1125 } else if ((val = thisfield(linebuf, "cc")) != NULL) {
1126 ++seenfields;
1127 hq->h_cc = cat(hq->h_cc, checkaddrs(lextract(val, GCC | GFULL),
1128 EACM_NORMAL | EAF_NAME, checkaddr_err));
1129 } else if ((val = thisfield(linebuf, "bcc")) != NULL) {
1130 ++seenfields;
1131 hq->h_bcc = cat(hq->h_bcc, checkaddrs(lextract(val, GBCC | GFULL),
1132 EACM_NORMAL | EAF_NAME, checkaddr_err));
1133 } else if ((val = thisfield(linebuf, "from")) != NULL) {
1134 if (!(pstate & PS_t_FLAG) || (options & OPT_t_FLAG)) {
1135 ++seenfields;
1136 hq->h_from = cat(hq->h_from,
1137 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
1138 EACM_STRICT, NULL));
1140 } else if ((val = thisfield(linebuf, "reply-to")) != NULL) {
1141 ++seenfields;
1142 hq->h_replyto = cat(hq->h_replyto,
1143 checkaddrs(lextract(val, GEXTRA | GFULL), EACM_STRICT, NULL));
1144 } else if ((val = thisfield(linebuf, "sender")) != NULL) {
1145 if (!(pstate & PS_t_FLAG) || (options & OPT_t_FLAG)) {
1146 ++seenfields;
1147 hq->h_sender = cat(hq->h_sender, /* TODO cat? check! */
1148 checkaddrs(lextract(val, GEXTRA | GFULL | GFULLEXTRA),
1149 EACM_STRICT, NULL));
1150 } else
1151 goto jebadhead;
1152 } else if ((val = thisfield(linebuf, "subject")) != NULL ||
1153 (val = thisfield(linebuf, "subj")) != NULL) {
1154 ++seenfields;
1155 for (cp = val; blankchar(*cp); ++cp)
1157 hq->h_subject = (hq->h_subject != NULL)
1158 ? save2str(hq->h_subject, cp) : savestr(cp);
1160 /* The remaining are mostly hacked in and thus TODO -- at least in
1161 * TODO respect to their content checking */
1162 else if((val = thisfield(linebuf, "message-id")) != NULL){
1163 if(pstate & PS_t_FLAG){
1164 np = checkaddrs(lextract(val, GREF),
1165 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1166 NULL);
1167 if (np == NULL || np->n_flink != NULL)
1168 goto jebadhead;
1169 ++seenfields;
1170 hq->h_message_id = np;
1171 }else
1172 goto jebadhead;
1173 }else if((val = thisfield(linebuf, "in-reply-to")) != NULL){
1174 if(pstate & PS_t_FLAG){
1175 np = checkaddrs(lextract(val, GREF),
1176 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1177 NULL);
1178 ++seenfields;
1179 hq->h_in_reply_to = np;
1180 }else
1181 goto jebadhead;
1182 }else if((val = thisfield(linebuf, "references")) != NULL){
1183 if(pstate & PS_t_FLAG){
1184 ++seenfields;
1185 /* TODO Limit number of references TODO better on parser side */
1186 hq->h_ref = cat(hq->h_ref, checkaddrs(extract(val, GREF),
1187 /*EACM_STRICT | TODO '/' valid!! */ EACM_NOLOG | EACM_NONAME,
1188 NULL));
1189 }else
1190 goto jebadhead;
1192 /* and that is very hairy */
1193 else if((val = thisfield(linebuf, "mail-followup-to")) != NULL){
1194 if(pstate & PS_t_FLAG){
1195 ++seenfields;
1196 hq->h_mft = cat(hq->h_mft, checkaddrs(lextract(val, GEXTRA | GFULL),
1197 /*EACM_STRICT | TODO '/' valid!! | EACM_NOLOG | */EACM_NONAME,
1198 checkaddr_err));
1199 }else
1200 goto jebadhead;
1202 /* A free-form user header; gethfield() did some verification already.. */
1203 else{
1204 struct n_header_field *hfp;
1205 ui32_t nl, bl;
1206 char const *nstart;
1208 for(nstart = cp = linebuf;; ++cp)
1209 if(!fieldnamechar(*cp))
1210 break;
1211 nl = (ui32_t)PTR2SIZE(cp - nstart);
1213 while(blankchar(*cp))
1214 ++cp;
1215 if(*cp++ != ':'){
1216 jebadhead:
1217 n_err(_("Ignoring header field: %s\n"), linebuf);
1218 continue;
1220 while(blankchar(*cp))
1221 ++cp;
1222 bl = (ui32_t)strlen(cp) +1;
1224 ++seenfields;
1225 *hftail = hfp = salloc(n_VSTRUCT_SIZEOF(struct n_header_field, hf_dat
1226 ) + nl +1 + bl);
1227 hftail = &hfp->hf_next;
1228 hfp->hf_next = NULL;
1229 hfp->hf_nl = nl;
1230 hfp->hf_bl = bl - 1;
1231 memcpy(hfp->hf_dat, nstart, nl);
1232 hfp->hf_dat[nl++] = '\0';
1233 memcpy(hfp->hf_dat + nl, cp, bl);
1237 /* In case the blank line after the header has been edited out. Otherwise,
1238 * fetch the header separator */
1239 if (linebuf != NULL) {
1240 if (linebuf[0] != '\0') {
1241 for (cp = linebuf; *(++cp) != '\0';)
1243 fseek(fp, (long)-PTR2SIZE(1 + cp - linebuf), SEEK_CUR);
1244 } else {
1245 if ((c = getc(fp)) != '\n' && c != EOF)
1246 ungetc(c, fp);
1250 if (seenfields > 0 && (checkaddr_err == NULL || *checkaddr_err == 0)) {
1251 hp->h_to = hq->h_to;
1252 hp->h_cc = hq->h_cc;
1253 hp->h_bcc = hq->h_bcc;
1254 hp->h_from = hq->h_from;
1255 hp->h_replyto = hq->h_replyto;
1256 hp->h_sender = hq->h_sender;
1257 if (hq->h_subject != NULL || !(pstate & PS_t_FLAG) ||
1258 !(options & OPT_t_FLAG))
1259 hp->h_subject = hq->h_subject;
1260 hp->h_user_headers = hq->h_user_headers;
1262 if (pstate & PS_t_FLAG) {
1263 hp->h_ref = hq->h_ref;
1264 hp->h_message_id = hq->h_message_id;
1265 hp->h_in_reply_to = hq->h_in_reply_to;
1266 hp->h_mft = hq->h_mft;
1268 /* And perform additional validity checks so that we don't bail later
1269 * on TODO this is good and the place where this should occur,
1270 * TODO unfortunately a lot of other places do again and blabla */
1271 if (pstate & PS_t_FLAG) {
1272 if (hp->h_from == NULL)
1273 hp->h_from = option_r_arg;
1274 else if (hp->h_from->n_flink != NULL && hp->h_sender == NULL)
1275 hp->h_sender = lextract(ok_vlook(sender),
1276 GEXTRA | GFULL | GFULLEXTRA);
1279 } else
1280 n_err(_("Restoring deleted header lines\n"));
1282 if (linebuf != NULL)
1283 free(linebuf);
1284 NYD_LEAVE;
1287 FL char *
1288 hfield_mult(char const *field, struct message *mp, int mult)
1290 FILE *ibuf;
1291 int lc;
1292 struct str hfs;
1293 size_t linesize = 0; /* TODO line pool */
1294 char *linebuf = NULL, *colon;
1295 char const *hfield;
1296 NYD_ENTER;
1298 /* There are (spam) messages which have header bytes which are many KB when
1299 * joined, so resize a single heap storage until we are done if we shall
1300 * collect a field that may have multiple bodies; only otherwise use the
1301 * string dope directly */
1302 memset(&hfs, 0, sizeof hfs);
1304 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
1305 goto jleave;
1306 if ((lc = mp->m_lines - 1) < 0)
1307 goto jleave;
1309 if ((mp->m_flag & MNOFROM) == 0 &&
1310 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1311 goto jleave;
1312 while (lc > 0) {
1313 if ((lc = gethfield(ibuf, &linebuf, &linesize, lc, &colon)) < 0)
1314 break;
1315 if ((hfield = thisfield(linebuf, field)) != NULL && *hfield != '\0') {
1316 if (mult)
1317 n_str_add_buf(&hfs, hfield, strlen(hfield));
1318 else {
1319 hfs.s = savestr(hfield);
1320 break;
1325 jleave:
1326 if (linebuf != NULL)
1327 free(linebuf);
1328 if (mult && hfs.s != NULL) {
1329 colon = savestrbuf(hfs.s, hfs.l);
1330 free(hfs.s);
1331 hfs.s = colon;
1333 NYD_LEAVE;
1334 return hfs.s;
1337 FL char const *
1338 thisfield(char const *linebuf, char const *field)
1340 char const *rv = NULL;
1341 NYD2_ENTER;
1343 while (lowerconv(*linebuf) == lowerconv(*field)) {
1344 ++linebuf;
1345 ++field;
1347 if (*field != '\0')
1348 goto jleave;
1350 while (blankchar(*linebuf))
1351 ++linebuf;
1352 if (*linebuf++ != ':')
1353 goto jleave;
1355 while (blankchar(*linebuf)) /* TODO header parser.. strip trailing WS?!? */
1356 ++linebuf;
1357 rv = linebuf;
1358 jleave:
1359 NYD2_LEAVE;
1360 return rv;
1363 FL char *
1364 nameof(struct message *mp, int reptype)
1366 char *cp, *cp2;
1367 NYD_ENTER;
1369 cp = skin(name1(mp, reptype));
1370 if (reptype != 0 || charcount(cp, '!') < 2)
1371 goto jleave;
1372 cp2 = strrchr(cp, '!');
1373 --cp2;
1374 while (cp2 > cp && *cp2 != '!')
1375 --cp2;
1376 if (*cp2 == '!')
1377 cp = cp2 + 1;
1378 jleave:
1379 NYD_LEAVE;
1380 return cp;
1383 FL char const *
1384 skip_comment(char const *cp)
1386 size_t nesting;
1387 NYD_ENTER;
1389 for (nesting = 1; nesting > 0 && *cp; ++cp) {
1390 switch (*cp) {
1391 case '\\':
1392 if (cp[1])
1393 ++cp;
1394 break;
1395 case '(':
1396 ++nesting;
1397 break;
1398 case ')':
1399 --nesting;
1400 break;
1403 NYD_LEAVE;
1404 return cp;
1407 FL char const *
1408 routeaddr(char const *name)
1410 char const *np, *rp = NULL;
1411 NYD_ENTER;
1413 for (np = name; *np; np++) {
1414 switch (*np) {
1415 case '(':
1416 np = skip_comment(np + 1) - 1;
1417 break;
1418 case '"':
1419 while (*np) {
1420 if (*++np == '"')
1421 break;
1422 if (*np == '\\' && np[1])
1423 np++;
1425 break;
1426 case '<':
1427 rp = np;
1428 break;
1429 case '>':
1430 goto jleave;
1433 rp = NULL;
1434 jleave:
1435 NYD_LEAVE;
1436 return rp;
1439 FL enum expand_addr_flags
1440 expandaddr_to_eaf(void)
1442 struct eafdesc {
1443 char const *eafd_name;
1444 bool_t eafd_is_target;
1445 ui8_t eafd_andoff;
1446 ui8_t eafd_or;
1447 } const eafa[] = {
1448 {"restrict", FAL0, EAF_TARGET_MASK, EAF_RESTRICT | EAF_RESTRICT_TARGETS},
1449 {"fail", FAL0, EAF_NONE, EAF_FAIL},
1450 {"failinvaddr", FAL0, EAF_NONE, EAF_FAILINVADDR | EAF_ADDR},
1451 {"all", TRU1, EAF_NONE, EAF_TARGET_MASK},
1452 {"file", TRU1, EAF_NONE, EAF_FILE},
1453 {"pipe", TRU1, EAF_NONE, EAF_PIPE},
1454 {"name", TRU1, EAF_NONE, EAF_NAME},
1455 {"addr", TRU1, EAF_NONE, EAF_ADDR}
1456 }, *eafp;
1458 char *buf;
1459 enum expand_addr_flags rv;
1460 char const *cp;
1461 NYD2_ENTER;
1463 if ((cp = ok_vlook(expandaddr)) == NULL)
1464 rv = EAF_RESTRICT_TARGETS;
1465 else if (*cp == '\0')
1466 rv = EAF_TARGET_MASK;
1467 else {
1468 rv = EAF_TARGET_MASK;
1470 for (buf = savestr(cp); (cp = n_strsep(&buf, ',', TRU1)) != NULL;) {
1471 bool_t minus;
1473 if ((minus = (*cp == '-')) || *cp == '+')
1474 ++cp;
1475 for (eafp = eafa;; ++eafp) {
1476 if (eafp == eafa + n_NELEM(eafa)) {
1477 if (options & OPT_D_V)
1478 n_err(_("Unknown *expandaddr* value: %s\n"), cp);
1479 break;
1480 } else if (!asccasecmp(cp, eafp->eafd_name)) {
1481 if (!minus) {
1482 rv &= ~eafp->eafd_andoff;
1483 rv |= eafp->eafd_or;
1484 } else {
1485 if (eafp->eafd_is_target)
1486 rv &= ~eafp->eafd_or;
1487 else if (options & OPT_D_V)
1488 n_err(_("minus - prefix invalid for *expandaddr* value: "
1489 "%s\n"), --cp);
1491 break;
1492 } else if (!asccasecmp(cp, "noalias")) { /* TODO v15 OBSOLETE */
1493 OBSOLETE(_("*expandaddr*: noalias is henceforth -name"));
1494 rv &= ~EAF_NAME;
1495 break;
1500 if ((rv & EAF_RESTRICT) && (options & (OPT_INTERACTIVE | OPT_TILDE_FLAG)))
1501 rv |= EAF_TARGET_MASK;
1502 else if (options & OPT_D_V) {
1503 if (!(rv & EAF_TARGET_MASK))
1504 n_err(_("*expandaddr* doesn't allow any addressees\n"));
1505 else if ((rv & EAF_FAIL) && (rv & EAF_TARGET_MASK) == EAF_TARGET_MASK)
1506 n_err(_("*expandaddr* with fail, but no restrictions to apply\n"));
1509 NYD2_LEAVE;
1510 return rv;
1513 FL si8_t
1514 is_addr_invalid(struct name *np, enum expand_addr_check_mode eacm)
1516 char cbuf[sizeof "'\\U12340'"];
1517 char const *cs;
1518 int f;
1519 si8_t rv;
1520 enum expand_addr_flags eaf;
1521 NYD_ENTER;
1523 eaf = expandaddr_to_eaf();
1524 f = np->n_flags;
1526 if ((rv = ((f & NAME_ADDRSPEC_INVALID) != 0))) {
1527 if (eaf & EAF_FAILINVADDR)
1528 rv = -rv;
1530 if ((eacm & EACM_NOLOG) || (f & NAME_ADDRSPEC_ERR_EMPTY)) {
1532 } else {
1533 ui32_t c;
1534 char const *fmt = "'\\x%02X'";
1535 bool_t ok8bit = TRU1;
1537 if (f & NAME_ADDRSPEC_ERR_IDNA) {
1538 cs = _("Invalid domain name: %s, character %s\n");
1539 fmt = "'\\U%04X'";
1540 ok8bit = FAL0;
1541 } else if (f & NAME_ADDRSPEC_ERR_ATSEQ)
1542 cs = _("%s contains invalid %s sequence\n");
1543 else
1544 cs = _("%s contains invalid non-ASCII byte %s\n");
1546 c = NAME_ADDRSPEC_ERR_GETWC(f);
1547 snprintf(cbuf, sizeof cbuf,
1548 (ok8bit && c >= 040 && c <= 0177 ? "'%c'" : fmt), c);
1549 goto jprint;
1551 goto jleave;
1554 /* *expandaddr* stuff */
1555 if (!(rv = ((eacm & EACM_MODE_MASK) != EACM_NONE)))
1556 goto jleave;
1558 if ((eacm & EACM_STRICT) && (f & NAME_ADDRSPEC_ISFILEORPIPE)) {
1559 if (eaf & EAF_FAIL)
1560 rv = -rv;
1561 cs = _("%s%s: file or pipe addressees not allowed here\n");
1562 if (eacm & EACM_NOLOG)
1563 goto jleave;
1564 else
1565 goto j0print;
1568 eaf |= (eacm & EAF_TARGET_MASK);
1569 if (eacm & EACM_NONAME)
1570 eaf &= ~EAF_NAME;
1572 if (eaf == EAF_NONE) {
1573 rv = FAL0;
1574 goto jleave;
1576 if (eaf & EAF_FAIL)
1577 rv = -rv;
1579 if (!(eaf & EAF_FILE) && (f & NAME_ADDRSPEC_ISFILE)) {
1580 cs = _("%s%s: *expandaddr* doesn't allow file target\n");
1581 if (eacm & EACM_NOLOG)
1582 goto jleave;
1583 } else if (!(eaf & EAF_PIPE) && (f & NAME_ADDRSPEC_ISPIPE)) {
1584 cs = _("%s%s: *expandaddr* doesn't allow command pipe target\n");
1585 if (eacm & EACM_NOLOG)
1586 goto jleave;
1587 } else if (!(eaf & EAF_NAME) && (f & NAME_ADDRSPEC_ISNAME)) {
1588 cs = _("%s%s: *expandaddr* doesn't allow user name target\n");
1589 if (eacm & EACM_NOLOG)
1590 goto jleave;
1591 } else if (!(eaf & EAF_ADDR) && (f & NAME_ADDRSPEC_ISADDR)) {
1592 cs = _("%s%s: *expandaddr* doesn't allow mail address target\n");
1593 if (eacm & EACM_NOLOG)
1594 goto jleave;
1595 } else {
1596 rv = FAL0;
1597 goto jleave;
1600 j0print:
1601 cbuf[0] = '\0';
1602 jprint:
1603 n_err(cs, n_shexp_quote_cp(np->n_name, TRU1), cbuf);
1604 jleave:
1605 NYD_LEAVE;
1606 return rv;
1609 FL char *
1610 skin(char const *name)
1612 struct n_addrguts ag;
1613 char *rv;
1614 NYD_ENTER;
1616 if(name != NULL){
1617 name = n_addrspec_with_guts(&ag,name, TRU1);
1618 rv = ag.ag_skinned;
1619 if(!(ag.ag_n_flags & NAME_NAME_SALLOC))
1620 rv = savestrbuf(rv, ag.ag_slen);
1621 }else
1622 rv = NULL;
1623 NYD_LEAVE;
1624 return rv;
1627 /* TODO addrspec_with_guts: RFC 5322
1628 * TODO addrspec_with_guts: trim whitespace ETC. ETC. ETC.!!! */
1629 FL char const *
1630 n_addrspec_with_guts(struct n_addrguts *agp, char const *name, bool_t doskin){
1631 char const *cp;
1632 char *cp2, *bufend, *nbuf, c;
1633 enum{
1634 a_NONE,
1635 a_GOTLT = 1<<0,
1636 a_GOTADDR = 1<<1,
1637 a_GOTSPACE = 1<<2,
1638 a_LASTSP = 1<<3
1639 } flags;
1640 NYD_ENTER;
1642 memset(agp, 0, sizeof *agp);
1644 if((agp->ag_input = name) == NULL || (agp->ag_ilen = strlen(name)) == 0){
1645 agp->ag_skinned = n_UNCONST(n_empty); /* ok: NAME_SALLOC is not set */
1646 agp->ag_slen = 0;
1647 agp->ag_n_flags |= NAME_ADDRSPEC_CHECKED;
1648 NAME_ADDRSPEC_ERR_SET(agp->ag_n_flags, NAME_ADDRSPEC_ERR_EMPTY, 0);
1649 goto jleave;
1650 }else if(!doskin){
1651 /*agp->ag_iaddr_start = 0;*/
1652 agp->ag_iaddr_aend = agp->ag_ilen;
1653 agp->ag_skinned = n_UNCONST(name); /* (NAME_SALLOC not set) */
1654 agp->ag_slen = agp->ag_ilen;
1655 agp->ag_n_flags = NAME_SKINNED;
1656 goto jcheck;
1659 flags = a_NONE;
1660 nbuf = n_lofi_alloc(agp->ag_ilen +1);
1661 /*agp->ag_iaddr_start = 0;*/
1662 cp2 = bufend = nbuf;
1664 for(cp = name++; (c = *cp++) != '\0';){
1665 switch (c) {
1666 case '(':
1667 cp = skip_comment(cp);
1668 flags &= ~a_LASTSP;
1669 break;
1670 case '"':
1671 /* Start of a "quoted-string". Copy it in its entirety */
1672 /* XXX RFC: quotes are "semantically invisible"
1673 * XXX But it was explicitly added (Changelog.Heirloom,
1674 * XXX [9.23] released 11/15/00, "Do not remove quotes
1675 * XXX when skinning names"? No more info.. */
1676 *cp2++ = c;
1677 while ((c = *cp) != '\0') { /* TODO improve */
1678 ++cp;
1679 if (c == '"') {
1680 *cp2++ = c;
1681 break;
1683 if (c != '\\')
1684 *cp2++ = c;
1685 else if ((c = *cp) != '\0') {
1686 *cp2++ = c;
1687 ++cp;
1690 flags &= ~a_LASTSP;
1691 break;
1692 case ' ':
1693 case '\t':
1694 if((flags & (a_GOTADDR | a_GOTSPACE)) == a_GOTADDR){
1695 flags |= a_GOTADDR | a_GOTSPACE;
1696 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1698 if (cp[0] == 'a' && cp[1] == 't' && blankchar(cp[2]))
1699 cp += 3, *cp2++ = '@';
1700 else if (cp[0] == '@' && blankchar(cp[1]))
1701 cp += 2, *cp2++ = '@';
1702 else
1703 flags |= a_LASTSP;
1704 break;
1705 case '<':
1706 agp->ag_iaddr_start = PTR2SIZE(cp - (name - 1));
1707 cp2 = bufend;
1708 flags &= ~(a_GOTSPACE | a_LASTSP);
1709 flags |= a_GOTLT | a_GOTADDR;
1710 break;
1711 case '>':
1712 if(flags & a_GOTLT){
1713 /* (_addrspec_check() verifies these later!) */
1714 flags &= ~(a_GOTLT | a_LASTSP);
1715 agp->ag_iaddr_aend = PTR2SIZE(cp - name);
1717 /* Skip over the entire remaining field */
1718 while((c = *cp) != '\0' && c != ','){
1719 ++cp;
1720 if (c == '(')
1721 cp = skip_comment(cp);
1722 else if (c == '"')
1723 while ((c = *cp) != '\0') {
1724 ++cp;
1725 if (c == '"')
1726 break;
1727 if (c == '\\' && *cp != '\0')
1728 ++cp;
1731 break;
1733 /* FALLTHRU */
1734 default:
1735 if(flags & a_LASTSP){
1736 flags &= ~a_LASTSP;
1737 if(flags & a_GOTADDR)
1738 *cp2++ = ' ';
1740 *cp2++ = c;
1741 if(c == ','){
1742 if(!(flags & a_GOTLT)){
1743 *cp2++ = ' ';
1744 for(; blankchar(*cp); ++cp)
1746 flags &= ~a_LASTSP;
1747 bufend = cp2;
1749 }else if(!(flags & a_GOTADDR)){
1750 flags |= a_GOTADDR;
1751 agp->ag_iaddr_start = PTR2SIZE(cp - name);
1755 --name;
1756 agp->ag_slen = PTR2SIZE(cp2 - nbuf);
1757 if (agp->ag_iaddr_aend == 0)
1758 agp->ag_iaddr_aend = agp->ag_ilen;
1759 agp->ag_skinned = savestrbuf(nbuf, agp->ag_slen);
1760 n_lofi_free(nbuf);
1761 agp->ag_n_flags = NAME_NAME_SALLOC | NAME_SKINNED;
1762 jcheck:
1763 if(a_head_addrspec_check(agp, doskin) <= 0)
1764 name = NULL;
1765 else
1766 name = agp->ag_input;
1767 jleave:
1768 NYD_LEAVE;
1769 return name;
1772 FL char *
1773 realname(char const *name)
1775 char const *cp, *cq, *cstart = NULL, *cend = NULL;
1776 char *rname, *rp;
1777 struct str in, out;
1778 int quoted, good, nogood;
1779 NYD_ENTER;
1781 if ((cp = n_UNCONST(name)) == NULL)
1782 goto jleave;
1783 for (; *cp != '\0'; ++cp) {
1784 switch (*cp) {
1785 case '(':
1786 if (cstart != NULL) {
1787 /* More than one comment in address, doesn't make sense to display
1788 * it without context. Return the entire field */
1789 cp = mime_fromaddr(name);
1790 goto jleave;
1792 cstart = cp++;
1793 cp = skip_comment(cp);
1794 cend = cp--;
1795 if (cend <= cstart)
1796 cend = cstart = NULL;
1797 break;
1798 case '"':
1799 while (*cp) {
1800 if (*++cp == '"')
1801 break;
1802 if (*cp == '\\' && cp[1])
1803 ++cp;
1805 break;
1806 case '<':
1807 if (cp > name) {
1808 cstart = name;
1809 cend = cp;
1811 break;
1812 case ',':
1813 /* More than one address. Just use the first one */
1814 goto jbrk;
1818 jbrk:
1819 if (cstart == NULL) {
1820 if (*name == '<') {
1821 /* If name contains only a route-addr, the surrounding angle brackets
1822 * don't serve any useful purpose when displaying, so remove */
1823 cp = prstr(skin(name));
1824 } else
1825 cp = mime_fromaddr(name);
1826 goto jleave;
1829 /* Strip quotes. Note that quotes that appear within a MIME encoded word are
1830 * not stripped. The idea is to strip only syntactical relevant things (but
1831 * this is not necessarily the most sensible way in practice) */
1832 rp = rname = ac_alloc(PTR2SIZE(cend - cstart +1));
1833 quoted = 0;
1834 for (cp = cstart; cp < cend; ++cp) {
1835 if (*cp == '(' && !quoted) {
1836 cq = skip_comment(++cp);
1837 if (PTRCMP(--cq, >, cend))
1838 cq = cend;
1839 while (cp < cq) {
1840 if (*cp == '\\' && PTRCMP(cp + 1, <, cq))
1841 ++cp;
1842 *rp++ = *cp++;
1844 } else if (*cp == '\\' && PTRCMP(cp + 1, <, cend))
1845 *rp++ = *++cp;
1846 else if (*cp == '"') {
1847 quoted = !quoted;
1848 continue;
1849 } else
1850 *rp++ = *cp;
1852 *rp = '\0';
1853 in.s = rname;
1854 in.l = rp - rname;
1855 mime_fromhdr(&in, &out, TD_ISPR | TD_ICONV);
1856 ac_free(rname);
1857 rname = savestr(out.s);
1858 free(out.s);
1860 while (blankchar(*rname))
1861 ++rname;
1862 for (rp = rname; *rp != '\0'; ++rp)
1864 while (PTRCMP(--rp, >=, rname) && blankchar(*rp))
1865 *rp = '\0';
1866 if (rp == rname) {
1867 cp = mime_fromaddr(name);
1868 goto jleave;
1871 /* mime_fromhdr() has converted all nonprintable characters to question
1872 * marks now. These and blanks are considered uninteresting; if the
1873 * displayed part of the real name contains more than 25% of them, it is
1874 * probably better to display the plain email address instead */
1875 good = 0;
1876 nogood = 0;
1877 for (rp = rname; *rp != '\0' && PTRCMP(rp, <, rname + 20); ++rp)
1878 if (*rp == '?' || blankchar(*rp))
1879 ++nogood;
1880 else
1881 ++good;
1882 cp = (good * 3 < nogood) ? prstr(skin(name)) : rname;
1883 jleave:
1884 NYD_LEAVE;
1885 return n_UNCONST(cp);
1888 FL char *
1889 name1(struct message *mp, int reptype)
1891 char *namebuf, *cp, *cp2, *linebuf = NULL /* TODO line pool */;
1892 size_t namesize, linesize = 0;
1893 FILE *ibuf;
1894 int f1st = 1;
1895 NYD_ENTER;
1897 if ((cp = hfield1("from", mp)) != NULL && *cp != '\0')
1898 goto jleave;
1899 if (reptype == 0 && (cp = hfield1("sender", mp)) != NULL && *cp != '\0')
1900 goto jleave;
1902 namebuf = smalloc(namesize = 1);
1903 namebuf[0] = 0;
1904 if (mp->m_flag & MNOFROM)
1905 goto jout;
1906 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
1907 goto jout;
1908 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1909 goto jout;
1911 jnewname:
1912 if (namesize <= linesize)
1913 namebuf = srealloc(namebuf, namesize = linesize +1);
1914 for (cp = linebuf; *cp != '\0' && *cp != ' '; ++cp)
1916 for (; blankchar(*cp); ++cp)
1918 for (cp2 = namebuf + strlen(namebuf);
1919 *cp && !blankchar(*cp) && PTRCMP(cp2, <, namebuf + namesize -1);)
1920 *cp2++ = *cp++;
1921 *cp2 = '\0';
1923 if (readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
1924 goto jout;
1925 if ((cp = strchr(linebuf, 'F')) == NULL)
1926 goto jout;
1927 if (strncmp(cp, "From", 4))
1928 goto jout;
1929 if (namesize <= linesize)
1930 namebuf = srealloc(namebuf, namesize = linesize + 1);
1932 while ((cp = strchr(cp, 'r')) != NULL) {
1933 if (!strncmp(cp, "remote", 6)) {
1934 if ((cp = strchr(cp, 'f')) == NULL)
1935 break;
1936 if (strncmp(cp, "from", 4) != 0)
1937 break;
1938 if ((cp = strchr(cp, ' ')) == NULL)
1939 break;
1940 cp++;
1941 if (f1st) {
1942 strncpy(namebuf, cp, namesize);
1943 f1st = 0;
1944 } else {
1945 cp2 = strrchr(namebuf, '!') + 1;
1946 strncpy(cp2, cp, PTR2SIZE(namebuf + namesize - cp2));
1948 namebuf[namesize - 2] = '!';
1949 namebuf[namesize - 1] = '\0';
1950 goto jnewname;
1952 cp++;
1954 jout:
1955 if (*namebuf != '\0' || ((cp = hfield1("return-path", mp))) == NULL ||
1956 *cp == '\0')
1957 cp = savestr(namebuf);
1959 if (linebuf != NULL)
1960 free(linebuf);
1961 free(namebuf);
1962 jleave:
1963 NYD_LEAVE;
1964 return cp;
1967 FL char *
1968 subject_re_trim(char *s)
1970 struct {
1971 ui8_t len;
1972 char dat[7];
1973 } const *pp, ignored[] = { /* Update *reply-strings* manual upon change! */
1974 { 3, "re:" },
1975 { 3, "aw:" }, { 5, "antw:" }, /* de */
1976 { 0, "" }
1979 bool_t any = FAL0;
1980 char *orig_s = s, *re_st = NULL, *re_st_x;
1981 size_t re_l = 0 /* pacify CC */;
1982 NYD_ENTER;
1984 if ((re_st_x = ok_vlook(reply_strings)) != NULL &&
1985 (re_l = strlen(re_st_x)) > 0) {
1986 re_st = ac_alloc(++re_l * 2);
1987 memcpy(re_st, re_st_x, re_l);
1990 jouter:
1991 while (*s != '\0') {
1992 while (spacechar(*s))
1993 ++s;
1995 for (pp = ignored; pp->len > 0; ++pp)
1996 if (is_asccaseprefix(s, pp->dat)) {
1997 s += pp->len;
1998 any = TRU1;
1999 goto jouter;
2002 if (re_st != NULL) {
2003 char *cp;
2005 memcpy(re_st_x = re_st + re_l, re_st, re_l);
2006 while ((cp = n_strsep(&re_st_x, ',', TRU1)) != NULL)
2007 if (is_asccaseprefix(s, cp)) {
2008 s += strlen(cp);
2009 any = TRU1;
2010 goto jouter;
2013 break;
2016 if (re_st != NULL)
2017 ac_free(re_st);
2018 NYD_LEAVE;
2019 return any ? s : orig_s;
2022 FL int
2023 msgidcmp(char const *s1, char const *s2)
2025 int q1 = 0, q2 = 0, c1, c2;
2026 NYD_ENTER;
2028 while(*s1 == '<')
2029 ++s1;
2030 while(*s2 == '<')
2031 ++s2;
2033 do {
2034 c1 = msgidnextc(&s1, &q1);
2035 c2 = msgidnextc(&s2, &q2);
2036 if (c1 != c2)
2037 break;
2038 } while (c1 && c2);
2039 NYD_LEAVE;
2040 return c1 - c2;
2043 FL char const *
2044 fakefrom(struct message *mp)
2046 char const *name;
2047 NYD_ENTER;
2049 if (((name = skin(hfield1("return-path", mp))) == NULL || *name == '\0' ) &&
2050 ((name = skin(hfield1("from", mp))) == NULL || *name == '\0'))
2051 /* XXX MAILER-DAEMON is what an old MBOX manual page says.
2052 * RFC 4155 however requires a RFC 5322 (2822) conforming
2053 * "addr-spec", but we simply can't provide that */
2054 name = "MAILER-DAEMON";
2055 NYD_LEAVE;
2056 return name;
2059 FL char const *
2060 fakedate(time_t t)
2062 char *cp, *cq;
2063 NYD_ENTER;
2065 cp = ctime(&t);
2066 for (cq = cp; *cq != '\0' && *cq != '\n'; ++cq)
2068 *cq = '\0';
2069 cp = savestr(cp);
2070 NYD_LEAVE;
2071 return cp;
2074 #ifdef HAVE_IMAP_SEARCH
2075 FL time_t
2076 unixtime(char const *fromline)
2078 char const *fp;
2079 char *xp;
2080 time_t t;
2081 int i, year, month, day, hour, minute, second, tzdiff;
2082 struct tm *tmptr;
2083 NYD2_ENTER;
2085 for (fp = fromline; *fp != '\0' && *fp != '\n'; ++fp)
2087 fp -= 24;
2088 if (PTR2SIZE(fp - fromline) < 7)
2089 goto jinvalid;
2090 if (fp[3] != ' ')
2091 goto jinvalid;
2092 for (i = 0;;) {
2093 if (!strncmp(fp + 4, month_names[i], 3))
2094 break;
2095 if (month_names[++i][0] == '\0')
2096 goto jinvalid;
2098 month = i + 1;
2099 if (fp[7] != ' ')
2100 goto jinvalid;
2101 day = strtol(fp + 8, &xp, 10);
2102 if (*xp != ' ' || xp != fp + 10)
2103 goto jinvalid;
2104 hour = strtol(fp + 11, &xp, 10);
2105 if (*xp != ':' || xp != fp + 13)
2106 goto jinvalid;
2107 minute = strtol(fp + 14, &xp, 10);
2108 if (*xp != ':' || xp != fp + 16)
2109 goto jinvalid;
2110 second = strtol(fp + 17, &xp, 10);
2111 if (*xp != ' ' || xp != fp + 19)
2112 goto jinvalid;
2113 year = strtol(fp + 20, &xp, 10);
2114 if (xp != fp + 24)
2115 goto jinvalid;
2116 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
2117 goto jinvalid;
2118 tzdiff = t - mktime(gmtime(&t));
2119 tmptr = localtime(&t);
2120 if (tmptr->tm_isdst > 0)
2121 tzdiff += 3600;
2122 t -= tzdiff;
2123 jleave:
2124 NYD2_LEAVE;
2125 return t;
2126 jinvalid:
2127 t = n_time_epoch();
2128 goto jleave;
2130 #endif /* HAVE_IMAP_SEARCH */
2132 FL time_t
2133 rfctime(char const *date)
2135 char const *cp = date;
2136 char *x;
2137 time_t t;
2138 int i, year, month, day, hour, minute, second;
2139 NYD2_ENTER;
2141 if ((cp = nexttoken(cp)) == NULL)
2142 goto jinvalid;
2143 if (alphachar(cp[0]) && alphachar(cp[1]) && alphachar(cp[2]) &&
2144 cp[3] == ',') {
2145 if ((cp = nexttoken(&cp[4])) == NULL)
2146 goto jinvalid;
2148 day = strtol(cp, &x, 10); /* XXX strtol */
2149 if ((cp = nexttoken(x)) == NULL)
2150 goto jinvalid;
2151 for (i = 0;;) {
2152 if (!strncmp(cp, month_names[i], 3))
2153 break;
2154 if (month_names[++i][0] == '\0')
2155 goto jinvalid;
2157 month = i + 1;
2158 if ((cp = nexttoken(&cp[3])) == NULL)
2159 goto jinvalid;
2160 /* RFC 5322, 4.3:
2161 * Where a two or three digit year occurs in a date, the year is to be
2162 * interpreted as follows: If a two digit year is encountered whose
2163 * value is between 00 and 49, the year is interpreted by adding 2000,
2164 * ending up with a value between 2000 and 2049. If a two digit year
2165 * is encountered with a value between 50 and 99, or any three digit
2166 * year is encountered, the year is interpreted by adding 1900 */
2167 year = strtol(cp, &x, 10); /* XXX strtol */
2168 i = (int)PTR2SIZE(x - cp);
2169 if (i == 2 && year >= 0 && year <= 49)
2170 year += 2000;
2171 else if (i == 3 || (i == 2 && year >= 50 && year <= 99))
2172 year += 1900;
2173 if ((cp = nexttoken(x)) == NULL)
2174 goto jinvalid;
2175 hour = strtol(cp, &x, 10); /* XXX strtol */
2176 if (*x != ':')
2177 goto jinvalid;
2178 cp = &x[1];
2179 minute = strtol(cp, &x, 10);
2180 if (*x == ':') {
2181 cp = x + 1;
2182 second = strtol(cp, &x, 10);
2183 } else
2184 second = 0;
2186 if ((t = combinetime(year, month, day, hour, minute, second)) == (time_t)-1)
2187 goto jinvalid;
2188 if ((cp = nexttoken(x)) != NULL) {
2189 char buf[3];
2190 int sign = 1;
2192 switch (*cp) {
2193 case '+':
2194 sign = -1;
2195 /* FALLTHRU */
2196 case '-':
2197 ++cp;
2198 break;
2200 if (digitchar(cp[0]) && digitchar(cp[1]) && digitchar(cp[2]) &&
2201 digitchar(cp[3])) {
2202 long tadj;
2203 buf[2] = '\0';
2204 buf[0] = cp[0];
2205 buf[1] = cp[1];
2206 tadj = strtol(buf, NULL, 10) * 3600;/*XXX strtrol*/
2207 buf[0] = cp[2];
2208 buf[1] = cp[3];
2209 tadj += strtol(buf, NULL, 10) * 60; /* XXX strtol*/
2210 if (sign < 0)
2211 tadj = -tadj;
2212 t += tadj;
2214 /* TODO WE DO NOT YET PARSE (OBSOLETE) ZONE NAMES
2215 * TODO once again, Christos Zoulas and NetBSD Mail have done
2216 * TODO a really good job already, but using strptime(3), which
2217 * TODO is not portable. Nonetheless, WE must improve, not
2218 * TODO at last because we simply ignore obsolete timezones!!
2219 * TODO See RFC 5322, 4.3! */
2221 jleave:
2222 NYD2_LEAVE;
2223 return t;
2224 jinvalid:
2225 t = 0;
2226 goto jleave;
2229 FL time_t
2230 combinetime(int year, int month, int day, int hour, int minute, int second){
2231 size_t const jdn_epoch = 2440588;
2232 bool_t const y2038p = (sizeof(time_t) == 4);
2234 size_t jdn;
2235 time_t t;
2236 NYD2_ENTER;
2238 if(UICMP(32, second, >=, DATE_SECSMIN) || /* XXX (leap- */
2239 UICMP(32, minute, >=, DATE_MINSHOUR) ||
2240 UICMP(32, hour, >=, DATE_HOURSDAY) ||
2241 day < 1 || day > 31 ||
2242 month < 1 || month > 12 ||
2243 year < 1970)
2244 goto jerr;
2246 if(year >= 1970 + ((y2038p ? SI32_MAX : SI64_MAX) /
2247 (DATE_SECSDAY * DATE_DAYSYEAR))){
2248 /* Be a coward regarding Y2038, many people (mostly myself, that is) do
2249 * test by stepping second-wise around the flip. Don't care otherwise */
2250 if(!y2038p)
2251 goto jerr;
2252 if(year > 2038 || month > 1 || day > 19 ||
2253 hour > 3 || minute > 14 || second > 7)
2254 goto jerr;
2257 t = second;
2258 t += minute * DATE_SECSMIN;
2259 t += hour * DATE_SECSHOUR;
2261 jdn = a_head_gregorian_to_jdn(year, month, day);
2262 jdn -= jdn_epoch;
2263 t += (time_t)jdn * DATE_SECSDAY;
2264 jleave:
2265 NYD2_LEAVE;
2266 return t;
2267 jerr:
2268 t = (time_t)-1;
2269 goto jleave;
2272 FL void
2273 substdate(struct message *m)
2275 char const *cp;
2276 NYD_ENTER;
2278 /* Determine the date to print in faked 'From ' lines. This is traditionally
2279 * the date the message was written to the mail file. Try to determine this
2280 * using RFC message header fields, or fall back to current time */
2281 if ((cp = hfield1("received", m)) != NULL) {
2282 while ((cp = nexttoken(cp)) != NULL && *cp != ';') {
2284 ++cp;
2285 while (alnumchar(*cp));
2287 if (cp && *++cp)
2288 m->m_time = rfctime(cp);
2290 if (m->m_time == 0 || m->m_time > time_current.tc_time) {
2291 if ((cp = hfield1("date", m)) != NULL)
2292 m->m_time = rfctime(cp);
2294 if (m->m_time == 0 || m->m_time > time_current.tc_time)
2295 m->m_time = time_current.tc_time;
2296 NYD_LEAVE;
2299 FL void
2300 setup_from_and_sender(struct header *hp)
2302 char const *addr;
2303 struct name *np;
2304 NYD_ENTER;
2306 /* If -t parsed or composed From: then take it. With -t we otherwise
2307 * want -r to be honoured in favour of *from* in order to have
2308 * a behaviour that is compatible with what users would expect from e.g.
2309 * postfix(1) */
2310 if ((np = hp->h_from) != NULL ||
2311 ((pstate & PS_t_FLAG) && (np = option_r_arg) != NULL)) {
2313 } else if ((addr = myaddrs(hp)) != NULL)
2314 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
2315 hp->h_from = np;
2317 if ((np = hp->h_sender) != NULL) {
2319 } else if ((addr = ok_vlook(sender)) != NULL)
2320 np = lextract(addr, GEXTRA | GFULL | GFULLEXTRA);
2321 hp->h_sender = np;
2323 NYD_LEAVE;
2326 FL struct name const *
2327 check_from_and_sender(struct name const *fromfield,
2328 struct name const *senderfield)
2330 struct name const *rv = NULL;
2331 NYD_ENTER;
2333 if (senderfield != NULL) {
2334 if (senderfield->n_flink != NULL) {
2335 n_err(_("The Sender: field may contain only one address\n"));
2336 goto jleave;
2338 rv = senderfield;
2341 if (fromfield != NULL) {
2342 if (fromfield->n_flink != NULL && senderfield == NULL) {
2343 n_err(_("A Sender: is required when there are multiple "
2344 "addresses in From:\n"));
2345 goto jleave;
2347 if (rv == NULL)
2348 rv = fromfield;
2351 if (rv == NULL)
2352 rv = (struct name*)0x1;
2353 jleave:
2354 NYD_LEAVE;
2355 return rv;
2358 #ifdef HAVE_XSSL
2359 FL char *
2360 getsender(struct message *mp)
2362 char *cp;
2363 struct name *np;
2364 NYD_ENTER;
2366 if ((cp = hfield1("from", mp)) == NULL ||
2367 (np = lextract(cp, GEXTRA | GSKIN)) == NULL)
2368 cp = NULL;
2369 else
2370 cp = (np->n_flink != NULL) ? skin(hfield1("sender", mp)) : np->n_name;
2371 NYD_LEAVE;
2372 return cp;
2374 #endif
2376 FL int
2377 grab_headers(enum n_lexinput_flags lif, struct header *hp, enum gfield gflags,
2378 int subjfirst)
2380 /* TODO grab_headers: again, check counts etc. against RFC;
2381 * TODO (now assumes check_from_and_sender() is called afterwards ++ */
2382 int errs;
2383 int volatile comma;
2384 NYD_ENTER;
2386 errs = 0;
2387 comma = (ok_blook(bsdcompat) || ok_blook(bsdmsgs)) ? 0 : GCOMMA;
2389 if (gflags & GTO)
2390 hp->h_to = grab_names(lif, "To: ", hp->h_to, comma, GTO | GFULL);
2391 if (subjfirst && (gflags & GSUBJECT))
2392 hp->h_subject = n_lex_input_cp(lif, "Subject: ", hp->h_subject);
2393 if (gflags & GCC)
2394 hp->h_cc = grab_names(lif, "Cc: ", hp->h_cc, comma, GCC | GFULL);
2395 if (gflags & GBCC)
2396 hp->h_bcc = grab_names(lif, "Bcc: ", hp->h_bcc, comma, GBCC | GFULL);
2398 if (gflags & GEXTRA) {
2399 if (hp->h_from == NULL)
2400 hp->h_from = lextract(myaddrs(hp), GEXTRA | GFULL | GFULLEXTRA);
2401 hp->h_from = grab_names(lif, "From: ", hp->h_from, comma,
2402 GEXTRA | GFULL | GFULLEXTRA);
2403 if (hp->h_replyto == NULL)
2404 hp->h_replyto = lextract(ok_vlook(replyto), GEXTRA | GFULL);
2405 hp->h_replyto = grab_names(lif, "Reply-To: ", hp->h_replyto, comma,
2406 GEXTRA | GFULL);
2407 if (hp->h_sender == NULL)
2408 hp->h_sender = extract(ok_vlook(sender), GEXTRA | GFULL);
2409 hp->h_sender = grab_names(lif, "Sender: ", hp->h_sender, comma,
2410 GEXTRA | GFULL);
2413 if (!subjfirst && (gflags & GSUBJECT))
2414 hp->h_subject = n_lex_input_cp(lif, "Subject: ", hp->h_subject);
2416 NYD_LEAVE;
2417 return errs;
2420 FL bool_t
2421 header_match(struct message *mp, struct search_expr const *sep)
2423 struct str in, out;
2424 FILE *ibuf;
2425 int lc;
2426 size_t linesize = 0; /* TODO line pool */
2427 char *linebuf = NULL, *colon;
2428 bool_t rv = FAL0;
2429 NYD_ENTER;
2431 if ((ibuf = setinput(&mb, mp, NEED_HEADER)) == NULL)
2432 goto jleave;
2433 if ((lc = mp->m_lines - 1) < 0)
2434 goto jleave;
2436 if ((mp->m_flag & MNOFROM) == 0 &&
2437 readline_restart(ibuf, &linebuf, &linesize, 0) < 0)
2438 goto jleave;
2439 while (lc > 0) {
2440 if (gethfield(ibuf, &linebuf, &linesize, lc, &colon) <= 0)
2441 break;
2442 if (blankchar(*++colon))
2443 ++colon;
2444 in.l = strlen(in.s = colon);
2445 mime_fromhdr(&in, &out, TD_ICONV);
2446 #ifdef HAVE_REGEX
2447 if (sep->ss_sexpr == NULL)
2448 rv = (regexec(&sep->ss_regex, out.s, 0,NULL, 0) != REG_NOMATCH);
2449 else
2450 #endif
2451 rv = substr(out.s, sep->ss_sexpr);
2452 free(out.s);
2453 if (rv)
2454 break;
2457 jleave:
2458 if (linebuf != NULL)
2459 free(linebuf);
2460 NYD_LEAVE;
2461 return rv;
2464 FL struct n_header_field *
2465 n_customhdr_query(void){
2466 char const *vp;
2467 struct n_header_field *rv, **tail, *hfp;
2468 NYD_ENTER;
2470 rv = NULL;
2472 if((vp = ok_vlook(customhdr)) != NULL){
2473 char *buf;
2475 tail = &rv;
2476 buf = savestr(vp);
2477 jch_outer:
2478 while((vp = a_head_customhdr__sep(&buf)) != NULL){
2479 ui32_t nl, bl;
2480 char const *nstart, *cp;
2482 for(nstart = cp = vp;; ++cp){
2483 if(fieldnamechar(*cp))
2484 continue;
2485 if(*cp == '\0'){
2486 if(cp == nstart){
2487 n_err(_("Invalid nameless *customhdr* entry\n"));
2488 goto jch_outer;
2490 }else if(*cp != ':' && !blankchar(*cp)){
2491 jch_badent:
2492 n_err(_("Invalid *customhdr* entry: %s\n"), vp);
2493 goto jch_outer;
2495 break;
2497 nl = (ui32_t)PTR2SIZE(cp - nstart);
2499 while(blankchar(*cp))
2500 ++cp;
2501 if(*cp++ != ':')
2502 goto jch_badent;
2503 while(blankchar(*cp))
2504 ++cp;
2505 bl = (ui32_t)strlen(cp) +1;
2507 *tail =
2508 hfp = salloc(n_VSTRUCT_SIZEOF(struct n_header_field, hf_dat) +
2509 nl +1 + bl);
2510 tail = &hfp->hf_next;
2511 hfp->hf_next = NULL;
2512 hfp->hf_nl = nl;
2513 hfp->hf_bl = bl - 1;
2514 memcpy(hfp->hf_dat, nstart, nl);
2515 hfp->hf_dat[nl++] = '\0';
2516 memcpy(hfp->hf_dat + nl, cp, bl);
2519 NYD_LEAVE;
2520 return rv;
2523 /* s-it-mode */