1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ MIME support functions.
3 *@ TODO Complete rewrite.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
10 * Gunnar Ritter. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by Gunnar Ritter
23 * and his contributors.
24 * 4. Neither the name of Gunnar Ritter nor the names of his contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY GUNNAR RITTER AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL GUNNAR RITTER OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 #ifndef HAVE_AMALGAMATION
47 /* Don't ask, but it keeps body and soul together */
48 enum a_mime_structure_hack
{
54 static char *_cs_iter_base
, *_cs_iter
;
56 # define _CS_ITER_GET() \
57 ((_cs_iter != NULL) ? _cs_iter : ok_vlook(CHARSET_8BIT_OKEY))
59 # define _CS_ITER_GET() ((_cs_iter != NULL) ? _cs_iter : ok_vlook(ttycharset))
61 #define _CS_ITER_STEP() _cs_iter = n_strsep(&_cs_iter_base, ',', TRU1)
63 /* Is 7-bit enough? */
65 static bool_t
_has_highbit(char const *s
);
66 static bool_t
_name_highbit(struct name
*np
);
69 /* fwrite(3) while checking for displayability */
70 static ssize_t
_fwrite_td(struct str
const *input
, enum tdflags flags
,
71 struct str
*outrest
, struct quoteflt
*qf
);
73 /* Convert header fields to RFC 2047 format and write to the file fo */
74 static ssize_t
mime_write_tohdr(struct str
*in
, FILE *fo
,
75 size_t *colp
, enum a_mime_structure_hack msh
);
77 /* Write len characters of the passed string to the passed file, doing charset
78 * and header conversion */
80 /* Write an address to a header field */
81 static ssize_t
mime_write_tohdr_a(struct str
*in
, FILE *f
,
84 static ssize_t
a_mime__convhdra(struct str
*inp
, FILE *fp
, size_t *colp
,
85 enum a_mime_structure_hack msh
);
87 # define a_mime__convhdra(S,F,C,MSH) mime_write_tohdr(S, F, C, MSH)
90 /* Append to buf, handling resizing */
91 static void _append_str(char **buf
, size_t *sz
, size_t *pos
,
92 char const *str
, size_t len
);
93 static void _append_conv(char **buf
, size_t *sz
, size_t *pos
,
94 char const *str
, size_t len
);
98 _has_highbit(char const *s
)
105 if ((ui8_t
)*s
& 0x80)
107 while (*s
++ != '\0');
116 _name_highbit(struct name
*np
)
122 if (_has_highbit(np
->n_name
) || _has_highbit(np
->n_fullname
))
131 #endif /* HAVE_ICONV */
133 static sigjmp_buf __mimefwtd_actjmp
; /* TODO someday.. */
134 static int __mimefwtd_sig
; /* TODO someday.. */
135 static sighandler_type __mimefwtd_opipe
;
137 __mimefwtd_onsig(int sig
) /* TODO someday, we won't need it no more */
139 NYD_X
; /* Signal handler */
140 __mimefwtd_sig
= sig
;
141 siglongjmp(__mimefwtd_actjmp
, 1);
145 _fwrite_td(struct str
const *input
, enum tdflags flags
, struct str
*outrest
,
148 /* TODO note: after send/MIME layer rewrite we will have a string pool
149 * TODO so that memory allocation count drops down massively; for now,
150 * TODO v14.* that is, we pay a lot & heavily depend on the allocator */
151 /* TODO well if we get a broken pipe here, and it happens to
152 * TODO happen pretty easy when sleeping in a full pipe buffer,
153 * TODO then the current codebase performs longjump away;
154 * TODO this leaves memory leaks behind ('think up to 3 per,
155 * TODO dep. upon alloca availability). For this to be fixed
156 * TODO we either need to get rid of the longjmp()s (tm) or
157 * TODO the storage must come from the outside or be tracked
158 * TODO in a carrier struct. Best both. But storage reuse
159 * TODO would be a bigbig win besides */
160 /* *input* _may_ point to non-modifyable buffer; but even then it only
161 * needs to be dup'ed away if we have to transform the content */
172 if ((flags
& TD_ICONV
) && iconvd
!= (iconv_t
)-1) {
178 if (outrest
!= NULL
&& outrest
->l
> 0) {
179 in
.l
= outrest
->l
+ input
->l
;
180 in
.s
= buf
= smalloc(in
.l
+1);
181 memcpy(in
.s
, outrest
->s
, outrest
->l
);
182 memcpy(&in
.s
[outrest
->l
], input
->s
, input
->l
);
186 if((err
= n_iconv_str(iconvd
, n_ICONV_UNIDEFAULT
, &out
, &in
, &in
)) != 0 &&
187 outrest
!= NULL
&& in
.l
> 0){
188 if(err
!= n_ERR_INVAL
)
189 n_iconv_reset(iconvd
);
191 /* Incomplete multibyte at EOF is special xxx _INVAL? */
192 if (flags
& _TD_EOF
) {
193 out
.s
= srealloc(out
.s
, out
.l
+ sizeof(n_unirepl
));
194 if(n_psonce
& n_PSO_UNICODE
){
195 memcpy(&out
.s
[out
.l
], n_unirepl
, sizeof(n_unirepl
) -1);
196 out
.l
+= sizeof(n_unirepl
) -1;
198 out
.s
[out
.l
++] = '?';
200 n_str_add(outrest
, &in
);
205 flags
&= ~_TD_BUFCOPY
;
210 #endif /* HAVE_ICONV */
211 /* Else, if we will modify the data bytes and thus introduce the potential
212 * of messing up multibyte sequences which become splitted over buffer
213 * boundaries TODO and unless we don't have our filter chain which will
214 * TODO make these hacks go by, buffer data until we see a NL */
215 if((flags
& (TD_ISPR
| TD_DELCTRL
)) && outrest
!= NULL
&&
217 iconvd
== (iconv_t
)-1 &&
219 (!(flags
& _TD_EOF
) || outrest
->l
> 0)
224 for (cp
= &in
.s
[in
.l
]; cp
> in
.s
&& cp
[-1] != '\n'; --cp
)
226 i
= PTR2SIZE(cp
- in
.s
);
230 n_str_assign_buf(outrest
, cp
, in
.l
- i
);
232 memcpy(cp
, in
.s
, in
.l
= i
);
233 (in
.s
= cp
)[in
.l
= i
] = '\0';
234 flags
&= ~_TD_BUFCOPY
;
236 n_str_add_buf(outrest
, input
->s
, input
->l
);
244 makeprint(&in
, &out
);
245 else if (flags
& _TD_BUFCOPY
)
246 n_str_dup(&out
, &in
);
249 if (flags
& TD_DELCTRL
)
250 out
.l
= delctrl(out
.s
, out
.l
);
253 __mimefwtd_opipe
= safe_signal(SIGPIPE
, &__mimefwtd_onsig
);
254 if (sigsetjmp(__mimefwtd_actjmp
, 1)) {
259 rv
= quoteflt_push(qf
, out
.s
, out
.l
);
264 if (in
.s
!= input
->s
)
266 safe_signal(SIGPIPE
, __mimefwtd_opipe
);
267 if (__mimefwtd_sig
!= 0)
268 n_raise(__mimefwtd_sig
);
275 mime_write_tohdr(struct str
*in
, FILE *fo
, size_t *colp
,
276 enum a_mime_structure_hack msh
)
278 /* TODO mime_write_tohdr(): we don't know the name of our header->maxcol..
279 * TODO MIME/send layer rewrite: more available state!!
280 * TODO Because of this we cannot make a difference in between structured
281 * TODO and unstructured headers (RFC 2047, 5. (2))
282 * TODO This means, e.g., that this gets called multiple times for a
283 * TODO structured header and always starts thinking it is at column 0.
284 * TODO I.e., it may get called for only the content of a comment etc.,
285 * TODO not knowing anything of its context.
286 * TODO Instead we should have a list of header body content tokens,
287 * TODO convert them, and then dump the converted tokens, breaking lines.
288 * TODO I.e., get rid of convhdra, mime_write_tohdr_a and such...
289 * TODO Somewhen, the following should produce smooth stuff:
290 * TODO ' "Hallo\"," Dr. Backe "Bl\"ö\"d" (Gell) <ha@llöch.en>
291 * TODO "Nochm\"a\"l"<ta@tu.da>(Dümm)'
292 * TODO NOT MULTIBYTE SAFE IF AN ENCODED WORD HAS TO BE SPLITTED!
293 * TODO To be better we had to mbtowc_l() (non-std! and no locale!!) and
294 * TODO work char-wise! -> S-CText..
295 * TODO The real problem for STD compatibility is however that "in" is
296 * TODO already iconv(3) encoded to the target character set! We could
297 * TODO also solve it (very expensively!) if we would narrow down to an
298 * TODO encoded word and then iconv(3)+MIME encode in one go, in which
299 * TODO case multibyte errors could be catched! */
301 /* Maximum line length */
302 a_MAXCOL_NENC
= MIME_LINELEN
,
303 a_MAXCOL
= MIME_LINELEN_RFC2047
306 struct str cout
, cin
;
308 _FIRST
= 1<<0, /* Nothing written yet, start of string */
309 _MSH_NOTHING
= 1<<1, /* Now, really: nothing at all has been written */
310 a_ANYENC
= 1<<2, /* We have RFC 2047 anything at least once */
311 _NO_QP
= 1<<3, /* No quoted-printable allowed */
312 _NO_B64
= 1<<4, /* Ditto, base64 */
313 _ENC_LAST
= 1<<5, /* Last round generated encoded word */
314 _SHOULD_BEE
= 1<<6, /* Avoid lines longer than SHOULD via encoding */
316 _RND_MASK
= (1<<_RND_SHIFT
) - 1,
317 _SPACE
= 1<<(_RND_SHIFT
+1), /* Leading whitespace */
318 _8BIT
= 1<<(_RND_SHIFT
+2), /* High bit set */
319 _ENCODE
= 1<<(_RND_SHIFT
+3), /* Need encoding */
320 _ENC_B64
= 1<<(_RND_SHIFT
+4), /* - let it be base64 */
321 _OVERLONG
= 1<<(_RND_SHIFT
+5) /* Temporarily rised limit */
323 char const *cset7
, *cset8
, *wbot
, *upper
, *wend
, *wcur
;
324 ui32_t cset7_len
, cset8_len
;
330 cout
.s
= NULL
, cout
.l
= 0;
331 cset7
= ok_vlook(charset_7bit
);
332 cset7_len
= (ui32_t
)strlen(cset7
);
333 cset8
= _CS_ITER_GET(); /* TODO MIME/send layer: iter active? iter! else */
334 cset8_len
= (ui32_t
)strlen(cset8
);
337 if(msh
!= a_MIME_SH_NONE
)
338 flags
|= _MSH_NOTHING
;
340 /* RFC 1468, "MIME Considerations":
341 * ISO-2022-JP may also be used in MIME Part 2 headers. The "B"
342 * encoding should be used with ISO-2022-JP text. */
343 /* TODO of course, our current implementation won't deal properly with
344 * TODO any stateful encoding at all... (the standard says each encoded
345 * TODO word must include all necessary reset sequences..., i.e., each
346 * TODO encoded word must be a self-contained iconv(3) life cycle) */
347 if (!asccasecmp(cset8
, "iso-2022-jp") || mime_enc_target() == MIMEE_B64
)
351 upper
= wbot
+ in
->l
;
354 if(colp
== NULL
|| (col
= *colp
) == 0)
355 col
= sizeof("Mail-Followup-To: ") -1; /* TODO dreadful thing */
357 /* The user may specify empy quoted-strings or comments, keep them! */
359 if(flags
& _MSH_NOTHING
){
360 flags
&= ~_MSH_NOTHING
;
361 putc((msh
== a_MIME_SH_COMMENT
? '(' : '"'), fo
);
365 } else for (; wbot
< upper
; flags
&= ~_FIRST
, wbot
= wend
) {
368 while (wcur
< upper
&& whitechar(*wcur
)) {
373 /* Any occurrence of whitespace resets prevention of lines >SHOULD via
374 * enforced encoding (xxx SHOULD, but.. encoding is expensive!!) */
376 flags
&= ~_SHOULD_BEE
;
378 /* Data ends with WS - dump it and done.
379 * Also, if we have seen multiple successive whitespace characters, then
380 * if there was no encoded word last, i.e., if we can simply take them
381 * over to the output as-is, keep one WS for possible later separation
382 * purposes and simply print the others as-is, directly! */
387 if ((flags
& (_ENC_LAST
| _SPACE
)) == _SPACE
&& wcur
- wbot
> 1) {
392 /* Skip over a word to next non-whitespace, keep track along the way
393 * whether our 7-bit charset suffices to represent the data */
394 for (wend
= wcur
; wend
< upper
; ++wend
) {
395 if (whitechar(*wend
))
397 if ((uc_i
)*wend
& 0x80)
401 /* Decide whether the range has to become encoded or not */
402 i
= PTR2SIZE(wend
- wcur
);
403 j
= mime_enc_mustquote(wcur
, i
, MIMEEF_ISHEAD
);
404 /* If it just cannot fit on a SHOULD line length, force encode */
405 if (i
> a_MAXCOL_NENC
) {
406 flags
|= _SHOULD_BEE
; /* (Sigh: SHOULD only, not MUST..) */
409 if ((flags
& _SHOULD_BEE
) || j
> 0) {
412 /* Use base64 if requested or more than 50% -37.5-% of the bytes of
413 * the string need to be encoded */
414 if ((flags
& _NO_QP
) || j
>= i
>> 1)/*(i >> 2) + (i >> 3))*/
417 DBG( if (flags
& _8BIT
) assert(flags
& _ENCODE
); )
419 if (!(flags
& _ENCODE
)) {
420 /* Encoded word produced, but no linear whitespace for necessary RFC
421 * 2047 separation? Generate artificial data (bad standard!) */
422 if ((flags
& (_ENC_LAST
| _SPACE
)) == _ENC_LAST
) {
423 if (col
>= a_MAXCOL
) {
428 if(flags
& _MSH_NOTHING
){
429 flags
&= ~_MSH_NOTHING
;
430 putc((msh
== a_MIME_SH_COMMENT
? '(' : '"'), fo
);
442 /* todo No effort here: (1) v15.0 has to bring complete rewrite,
443 * todo (2) the standard is braindead and (3) usually this is one
444 * todo word only, and why be smarter than the standard? */
446 i
= PTR2SIZE(wend
- wbot
);
447 if (i
+ col
+ ((flags
& _MSH_NOTHING
) != 0) <=
448 (flags
& _OVERLONG
? MIME_LINELEN_MAX
449 : (flags
& a_ANYENC
? a_MAXCOL
: a_MAXCOL_NENC
))) {
450 if(flags
& _MSH_NOTHING
){
451 flags
&= ~_MSH_NOTHING
;
452 putc((msh
== a_MIME_SH_COMMENT
? '(' : '"'), fo
);
456 i
= fwrite(wbot
, sizeof *wbot
, i
, fo
);
462 /* Doesn't fit, try to break the line first; */
465 if (whitechar(*wbot
)) {
466 putc((uc_i
)*wbot
, fo
);
469 putc(' ', fo
); /* Bad standard: artificial data! */
472 if(flags
& _MSH_NOTHING
){
473 flags
&= ~_MSH_NOTHING
;
474 putc((msh
== a_MIME_SH_COMMENT
? '(' : '"'), fo
);
482 /* It is so long that it needs to be broken, effectively causing
483 * artificial spaces to be inserted (bad standard), yuck */
484 /* todo This is not multibyte safe, as above; and completely stupid
485 * todo P.S.: our _SHOULD_BEE prevents these cases in the meanwhile */
486 /* FIXME n_PSO_UNICODE and parse using UTF-8 sync possibility! */
487 wcur
= wbot
+ MIME_LINELEN_MAX
- 8;
492 /* Encoding to encoded word(s); deal with leading whitespace, place
493 * a separator first as necessary: encoded words must always be
494 * separated from text and other encoded words with linear WS.
495 * And if an encoded word was last, intermediate whitespace must
496 * also be encoded, otherwise it would get stripped away! */
497 wcur
= n_UNCONST(n_empty
);
498 if ((flags
& (_ENC_LAST
| _SPACE
)) != _SPACE
) {
499 /* Reinclude whitespace */
501 /* We don't need to place a separator at the very beginning */
502 if (!(flags
& _FIRST
))
503 wcur
= n_UNCONST(" ");
507 flags
|= a_ANYENC
| _ENC_LAST
;
508 n_pstate
|= n_PS_HEADER_NEEDED_MIME
;
511 * An 'encoded-word' may not be more than 75 characters long,
512 * including 'charset', 'encoding', 'encoded-text', and
513 * delimiters. If it is desirable to encode more text than will
514 * fit in an 'encoded-word' of 75 characters, multiple
515 * 'encoded-word's (separated by CRLF SPACE) may be used.
517 * While there is no limit to the length of a multiple-line
518 * header field, each line of a header field that contains one
519 * or more 'encoded-word's is limited to 76 characters */
521 cin
.s
= n_UNCONST(wbot
);
522 cin
.l
= PTR2SIZE(wend
- wbot
);
528 xout
= b64_encode(&cout
, &cin
, B64_ISHEAD
| B64_ISENCWORD
);
530 xout
= qp_encode(&cout
, &cin
, QP_ISHEAD
| QP_ISENCWORD
);
537 /* (Avoid trigraphs in the RFC 2047 placeholder..) */
538 i
= j
+ (flags
& _8BIT
? cset8_len
: cset7_len
) + sizeof("=!!B!!=") -1;
543 /* Unfortunately RFC 2047 explicitly disallows encoded words to be
544 * longer (just like RFC 5322's "a line SHOULD fit in 78 but MAY be
545 * 998 characters long"), so we cannot use the _OVERLONG mechanism,
546 * even though all tested mailers seem to support it */
547 if (i
+ col
<= (/*flags & _OVERLONG ? MIME_LINELEN_MAX :*/ a_MAXCOL
)) {
548 if(flags
& _MSH_NOTHING
){
549 flags
&= ~_MSH_NOTHING
;
550 putc((msh
== a_MIME_SH_COMMENT
? '(' : '"'), fo
);
554 fprintf(fo
, "%.1s=?%s?%c?%.*s?=",
555 wcur
, (flags
& _8BIT
? cset8
: cset7
),
556 (flags
& _ENC_B64
? 'B' : 'Q'),
557 (int)cout
.l
, cout
.s
);
563 /* Doesn't fit, try to break the line first */
564 /* TODO I've commented out the _FIRST test since we (1) cannot do
565 * TODO _OVERLONG since (MUAs support but) the standard disallows,
566 * TODO and because of our iconv problem i prefer an empty first line
567 * TODO in favour of a possibly messed up multibytes character. :-( */
568 if (col
> 1 /* TODO && !(flags & _FIRST)*/) {
572 if (!(flags
& _SPACE
)) {
574 wcur
= n_UNCONST(n_empty
);
575 /*flags |= _OVERLONG;*/
576 goto jenc_retry_same
;
578 putc((uc_i
)*wcur
, fo
);
579 if (whitechar(*(wcur
= wbot
)))
583 wcur
= n_UNCONST(n_empty
);
585 /*flags &= ~_OVERLONG;*/
590 /* It is so long that it needs to be broken, effectively causing
591 * artificial data to be inserted (bad standard), yuck */
592 /* todo This is not multibyte safe, as above */
593 /*if (!(flags & _OVERLONG)) { Mechanism explicitly forbidden by 2047
598 /* FIXME n_PSO_UNICODE and parse using UTF-8 sync possibility! */
599 i
= PTR2SIZE(wend
- wbot
) + !!(flags
& _SPACE
);
600 j
= 3 + !(flags
& _ENC_B64
);
604 /* (Note the problem most likely is the transfer-encoding blow,
605 * which is why we test this *after* the decrements.. */
613 if(!(flags
& _MSH_NOTHING
) && msh
!= a_MIME_SH_NONE
){
614 putc((msh
== a_MIME_SH_COMMENT
? ')' : '"'), fo
);
629 mime_write_tohdr_a(struct str
*in
, FILE *f
, size_t *colp
)
633 char const *cp
, *lastcp
;
639 if((cp
= routeaddr(in
->s
)) != NULL
&& cp
> lastcp
) {
641 xin
.l
= PTR2SIZE(cp
- in
->s
);
642 if ((sz
= mime_write_tohdr_a(&xin
, f
, colp
)) < 0)
651 for( ; *cp
!= '\0'; ++cp
){
654 i
= PTR2SIZE(cp
- lastcp
);
656 if(fwrite(lastcp
, 1, i
, f
) != i
)
661 cp
= skip_comment(cp
);
664 /* We want to keep empty comments, too! */
665 xin
.s
= n_UNCONST(lastcp
);
666 xin
.l
= PTR2SIZE(cp
- lastcp
);
667 if ((x
= a_mime__convhdra(&xin
, f
, colp
, a_MIME_SH_COMMENT
)) < 0)
673 i
= PTR2SIZE(cp
- lastcp
);
675 if(fwrite(lastcp
, 1, i
, f
) != i
)
679 for(lastcp
= ++cp
; *cp
!= '\0'; ++cp
){
682 if(*cp
== '\\' && cp
[1] != '\0')
685 /* We want to keep empty quoted-strings, too! */
686 xin
.s
= n_UNCONST(lastcp
);
687 xin
.l
= PTR2SIZE(cp
- lastcp
);
688 if((x
= a_mime__convhdra(&xin
, f
, colp
, a_MIME_SH_QUOTE
)) < 0)
697 i
= PTR2SIZE(cp
- lastcp
);
699 if(fwrite(lastcp
, 1, i
, f
) != i
)
713 a_mime__convhdra(struct str
*inp
, FILE *fp
, size_t *colp
,
714 enum a_mime_structure_hack msh
){
722 if(inp
->l
> 0 && iconvd
!= (iconv_t
)-1){
724 if(n_iconv_str(iconvd
, n_ICONV_IGN_NOREVERSE
, &ciconv
, inp
, NULL
) != 0){
725 n_iconv_reset(iconvd
);
731 rv
= mime_write_tohdr(inp
, fp
, colp
, msh
);
738 #endif /* HAVE_ICONV */
741 _append_str(char **buf
, size_t *sz
, size_t *pos
, char const *str
, size_t len
)
744 *buf
= srealloc(*buf
, *sz
+= len
);
745 memcpy(&(*buf
)[*pos
], str
, len
);
751 _append_conv(char **buf
, size_t *sz
, size_t *pos
, char const *str
, size_t len
)
756 in
.s
= n_UNCONST(str
);
758 mime_fromhdr(&in
, &out
, TD_ISPR
| TD_ICONV
);
759 _append_str(buf
, sz
, pos
, out
.s
, out
.l
);
765 charset_iter_reset(char const *a_charset_to_try_first
) /* TODO elim. dups! */
768 size_t sarrl
[3], len
;
771 n_UNUSED(a_charset_to_try_first
);
774 sarr
[2] = ok_vlook(CHARSET_8BIT_OKEY
);
776 if(a_charset_to_try_first
!= NULL
&& strcmp(a_charset_to_try_first
, sarr
[2]))
777 sarr
[0] = a_charset_to_try_first
;
781 if((sarr
[1] = ok_vlook(sendcharsets
)) == NULL
&&
782 ok_blook(sendcharsets_else_ttycharset
)){
783 cp
= n_UNCONST(ok_vlook(ttycharset
));
784 if(strcmp(cp
, sarr
[2]) && (sarr
[0] == NULL
|| strcmp(cp
, sarr
[0])))
788 sarr
[2] = ok_vlook(ttycharset
);
791 sarrl
[2] = len
= strlen(sarr
[2]);
793 if ((cp
= n_UNCONST(sarr
[1])) != NULL
)
794 len
+= (sarrl
[1] = strlen(cp
));
797 if ((cp
= n_UNCONST(sarr
[0])) != NULL
)
798 len
+= (sarrl
[0] = strlen(cp
));
803 _cs_iter_base
= cp
= salloc(len
+ 1 + 1 +1);
806 if ((len
= sarrl
[0]) != 0) {
807 memcpy(cp
, sarr
[0], len
);
811 if ((len
= sarrl
[1]) != 0) {
812 memcpy(cp
, sarr
[1], len
);
818 memcpy(cp
, sarr
[2], len
);
823 return (_cs_iter
!= NULL
);
827 charset_iter_next(void)
833 rv
= (_cs_iter
!= NULL
);
839 charset_iter_is_valid(void)
844 rv
= (_cs_iter
!= NULL
);
861 charset_iter_or_fallback(void)
872 charset_iter_recurse(char *outer_storage
[2]) /* TODO LEGACY FUN, REMOVE */
875 outer_storage
[0] = _cs_iter_base
;
876 outer_storage
[1] = _cs_iter
;
881 charset_iter_restore(char *outer_storage
[2]) /* TODO LEGACY FUN, REMOVE */
884 _cs_iter_base
= outer_storage
[0];
885 _cs_iter
= outer_storage
[1];
891 need_hdrconv(struct header
*hp
) /* TODO once only, then iter */
893 struct n_header_field
*hfp
;
899 if((hfp
= hp
->h_user_headers
) != NULL
)
900 do if(_has_highbit(hfp
->hf_dat
+ hfp
->hf_nl
+1))
902 while((hfp
= hfp
->hf_next
) != NULL
);
904 if((hfp
= hp
->h_custom_headers
) != NULL
||
905 (hp
->h_custom_headers
= hfp
= n_customhdr_query()) != NULL
)
906 do if(_has_highbit(hfp
->hf_dat
+ hfp
->hf_nl
+1))
908 while((hfp
= hfp
->hf_next
) != NULL
);
910 if (hp
->h_mft
!= NULL
) {
911 if (_name_highbit(hp
->h_mft
))
914 if (hp
->h_from
!= NULL
) {
915 if (_name_highbit(hp
->h_from
))
917 } else if (_has_highbit(myaddrs(NULL
)))
919 if (hp
->h_reply_to
) {
920 if (_name_highbit(hp
->h_reply_to
))
923 char const *v15compat
;
925 if((v15compat
= ok_vlook(replyto
)) != NULL
)
926 n_OBSOLETE(_("please use *reply-to*, not *replyto*"));
927 if(_has_highbit(v15compat
))
929 if(_has_highbit(ok_vlook(reply_to
)))
933 if (_name_highbit(hp
->h_sender
))
935 } else if (_has_highbit(ok_vlook(sender
)))
938 if (_name_highbit(hp
->h_to
))
940 if (_name_highbit(hp
->h_cc
))
942 if (_name_highbit(hp
->h_bcc
))
944 if (_has_highbit(hp
->h_subject
))
946 rv
= _CS_ITER_GET(); /* TODO MIME/send: iter active? iter! else */
950 #endif /* HAVE_ICONV */
953 mime_fromhdr(struct str
const *in
, struct str
*out
, enum tdflags flags
)
955 /* TODO mime_fromhdr(): is called with strings that contain newlines;
956 * TODO this is the usual newline problem all around the codebase;
957 * TODO i.e., if we strip it, then the display misses it ;>
958 * TODO this is why it is so messy and why S-nail v14.2 plus additional
959 * TODO patch for v14.5.2 (and maybe even v14.5.3 subminor) occurred, and
960 * TODO why our display reflects what is contained in the message: the 1:1
961 * TODO relationship of message content and display!
962 * TODO instead a header line should be decoded to what it is (a single
963 * TODO line that is) and it should be objective to the backend whether
964 * TODO it'll be folded to fit onto the display or not, e.g., for search
965 * TODO purposes etc. then the only condition we have to honour in here
966 * TODO is that whitespace in between multiple adjacent MIME encoded words
967 * TODO á la RFC 2047 is discarded; i.e.: this function should deal with
968 * TODO RFC 2047 and be renamed: mime_fromhdr() -> mime_rfc2047_decode() */
969 struct str cin
, cout
;
970 char *p
, *op
, *upper
;
971 ui32_t convert
, lastenc
, lastoutl
;
975 iconv_t fhicd
= (iconv_t
)-1;
981 *(out
->s
= smalloc(1)) = '\0';
987 tcs
= ok_vlook(ttycharset
);
991 lastenc
= lastoutl
= 0;
995 if (*p
== '=' && *(p
+ 1) == '?') {
1000 while (p
< upper
&& *p
!= '?')
1001 ++p
; /* strip charset */
1006 if (flags
& TD_ICONV
) {
1007 size_t i
= PTR2SIZE(p
- cbeg
);
1008 char *ltag
, *cs
= ac_alloc(i
);
1010 memcpy(cs
, cbeg
, --i
);
1012 /* RFC 2231 extends the RFC 2047 character set definition in
1013 * encoded words by language tags - silently strip those off */
1014 if ((ltag
= strchr(cs
, '*')) != NULL
)
1017 if (fhicd
!= (iconv_t
)-1)
1018 n_iconv_close(fhicd
);
1019 fhicd
= asccasecmp(cs
, tcs
) ? n_iconv_open(tcs
, cs
) : (iconv_t
)-1;
1025 convert
= CONV_FROMB64
;
1028 convert
= CONV_FROMQP
;
1030 default: /* invalid, ignore */
1038 if (PTRCMP(p
+ 1, >=, upper
))
1040 if (*p
++ == '?' && *p
== '=')
1049 if (convert
== CONV_FROMB64
) {
1050 if(!b64_decode_header(&cout
, &cin
))
1051 n_str_assign_cp(&cout
, _("[Invalid Base64 encoding]"));
1052 }else if(!qp_decode_header(&cout
, &cin
))
1053 n_str_assign_cp(&cout
, _("[Invalid Quoted-Printable encoding]"));
1057 if ((flags
& TD_ICONV
) && fhicd
!= (iconv_t
)-1) {
1058 cin
.s
= NULL
, cin
.l
= 0; /* XXX string pool ! */
1059 convert
= n_iconv_str(fhicd
, n_ICONV_UNIDEFAULT
, &cin
, &cout
, NULL
);
1060 out
= n_str_add(out
, &cin
);
1061 if (convert
) {/* n_ERR_INVAL at EOS */
1062 n_iconv_reset(fhicd
);
1063 out
= n_str_add_buf(out
, n_qm
, 1); /* TODO unicode replacement */
1068 out
= n_str_add(out
, &cout
);
1069 lastenc
= lastoutl
= out
->l
;
1076 onlyws
= (lastenc
> 0);
1080 if (op
[0] == '=' && (PTRCMP(op
+ 1, ==, upper
) || op
[1] == '?'))
1082 if (onlyws
&& !blankchar(*op
))
1086 out
= n_str_add_buf(out
, p
, PTR2SIZE(op
- p
));
1088 if (!onlyws
|| lastoutl
!= lastenc
)
1093 out
->s
[out
->l
] = '\0';
1095 if (flags
& TD_ISPR
) {
1096 makeprint(out
, &cout
);
1100 if (flags
& TD_DELCTRL
)
1101 out
->l
= delctrl(out
->s
, out
->l
);
1103 if (fhicd
!= (iconv_t
)-1)
1104 n_iconv_close(fhicd
);
1112 mime_fromaddr(char const *name
)
1114 char const *cp
, *lastcp
;
1116 size_t ressz
= 1, rescur
= 0;
1121 if (*name
== '\0') {
1122 res
= savestr(name
);
1126 if ((cp
= routeaddr(name
)) != NULL
&& cp
> name
) {
1127 _append_conv(&res
, &ressz
, &rescur
, name
, PTR2SIZE(cp
- name
));
1132 for ( ; *cp
; ++cp
) {
1135 _append_str(&res
, &ressz
, &rescur
, lastcp
, PTR2SIZE(cp
- lastcp
+ 1));
1137 cp
= skip_comment(cp
);
1139 _append_conv(&res
, &ressz
, &rescur
, lastcp
, PTR2SIZE(cp
- lastcp
));
1146 if (*cp
== '\\' && cp
[1] != '\0')
1153 _append_str(&res
, &ressz
, &rescur
, lastcp
, PTR2SIZE(cp
- lastcp
));
1158 res
= savestrbuf(res
, rescur
);
1168 xmime_write(char const *ptr
, size_t size
, FILE *f
, enum conversion convert
,
1169 enum tdflags dflags
, struct str
* volatile outrest
,
1170 struct str
* volatile inrest
)
1173 struct quoteflt
*qf
;
1176 quoteflt_reset(qf
= quoteflt_dummy(), f
);
1177 rv
= mime_write(ptr
, size
, f
, convert
, dflags
, qf
, outrest
, inrest
);
1183 static sigjmp_buf __mimemw_actjmp
; /* TODO someday.. */
1184 static int __mimemw_sig
; /* TODO someday.. */
1185 static sighandler_type __mimemw_opipe
;
1187 __mimemw_onsig(int sig
) /* TODO someday, we won't need it no more */
1189 NYD_X
; /* Signal handler */
1191 siglongjmp(__mimemw_actjmp
, 1);
1195 mime_write(char const *ptr
, size_t size
, FILE *f
,
1196 enum conversion convert
, enum tdflags
volatile dflags
,
1197 struct quoteflt
*qf
, struct str
* volatile outrest
,
1198 struct str
* volatile inrest
)
1200 /* TODO note: after send/MIME layer rewrite we will have a string pool
1201 * TODO so that memory allocation count drops down massively; for now,
1202 * TODO v14.0 that is, we pay a lot & heavily depend on the allocator.
1203 * TODO P.S.: furthermore all this encapsulated in filter objects instead */
1205 ssize_t
volatile sz
;
1208 dflags
|= _TD_BUFCOPY
;
1209 in
.s
= n_UNCONST(ptr
);
1214 if((sz
= size
) == 0){
1215 if(inrest
!= NULL
&& inrest
->l
!= 0)
1217 if(outrest
!= NULL
&& outrest
->l
!= 0)
1222 /* TODO This crap requires linewise input, then. We need a filter chain
1223 * TODO as in input->iconv->base64 where each filter can have its own
1224 * TODO buffer, with a filter->fflush() call to get rid of those! */
1226 if ((dflags
& TD_ICONV
) && iconvd
!= (iconv_t
)-1 &&
1227 (convert
== CONV_TOQP
|| convert
== CONV_8BIT
||
1228 convert
== CONV_TOB64
|| convert
== CONV_TOHDR
)) {
1229 if (n_iconv_str(iconvd
, n_ICONV_IGN_NOREVERSE
, &out
, &in
, NULL
) != 0) {
1230 n_iconv_reset(iconvd
);
1231 /* TODO This causes hard-failure. We would need to have an action
1232 * TODO policy FAIL|IGNORE|SETERROR(but continue) */
1238 dflags
&= ~_TD_BUFCOPY
;
1243 if(inrest
!= NULL
&& inrest
->l
> 0){
1249 out
.s
= n_alloc(in
.l
+ inrest
->l
+ 1);
1250 memcpy(out
.s
, inrest
->s
, inrest
->l
);
1252 memcpy(&out
.s
[inrest
->l
], in
.s
, in
.l
);
1255 (in
.s
= out
.s
)[in
.l
+= inrest
->l
] = '\0';
1259 dflags
&= ~_TD_BUFCOPY
;
1264 __mimemw_opipe
= safe_signal(SIGPIPE
, &__mimemw_onsig
);
1265 if (sigsetjmp(__mimemw_actjmp
, 1))
1270 if(!qp_decode_part(&out
, &in
, outrest
, inrest
)){
1271 n_err(_("Invalid Quoted-Printable encoding ignored\n"));
1272 sz
= 0; /* TODO sz = -1 stops outer levels! */
1277 if(qp_encode(&out
, &in
, QP_NONE
) == NULL
){
1278 sz
= 0; /* TODO sz = -1 stops outer levels! */
1283 sz
= quoteflt_push(qf
, in
.s
, in
.l
);
1286 if(!b64_decode_part(&out
, &in
, outrest
, inrest
))
1291 case CONV_FROMB64_T
:
1292 if(!b64_decode_part(&out
, &in
, outrest
, inrest
)){
1294 n_err(_("Invalid Base64 encoding ignored\n"));
1295 sz
= 0; /* TODO sz = -1 stops outer levels! */
1300 if ((sz
= out
.l
) != 0) {
1301 ui32_t opl
= qf
->qf_pfix_len
;
1302 sz
= _fwrite_td(&out
, (dflags
& ~_TD_BUFCOPY
), outrest
, qf
);
1303 qf
->qf_pfix_len
= opl
;
1307 /* TODO hack which is necessary unless this is a filter based approach
1308 * TODO and each filter has its own buffer (as necessary): we must not
1309 * TODO pass through a number of bytes which causes padding, otherwise we
1310 * TODO produce multiple adjacent base64 streams, and that is not treated
1311 * TODO in the same relaxed fashion like completely bogus bytes by at
1312 * TODO least mutt and OpenSSL. So we need an expensive workaround
1313 * TODO unless we have input->iconv->base64 filter chain as such!! :( */
1314 if(size
!= 0 && /* for Coverity, else assert() */ inrest
!= NULL
){
1315 if(in
.l
> B64_ENCODE_INPUT_PER_LINE
){
1318 i
= in
.l
% B64_ENCODE_INPUT_PER_LINE
;
1322 assert(inrest
->l
== 0);
1323 inrest
->s
= n_realloc(inrest
->s
, i
+1);
1324 memcpy(inrest
->s
, &in
.s
[in
.l
], i
);
1325 inrest
->s
[inrest
->l
= i
] = '\0';
1327 }else if(in
.l
< B64_ENCODE_INPUT_PER_LINE
){
1328 inrest
->s
= n_realloc(inrest
->s
, in
.l
+1);
1329 memcpy(inrest
->s
, in
.s
, in
.l
);
1330 inrest
->s
[inrest
->l
= in
.l
] = '\0';
1336 if(b64_encode(&out
, &in
, B64_LF
| B64_MULTILINE
) == NULL
){
1341 sz
= fwrite(out
.s
, sizeof *out
.s
, out
.l
, f
);
1342 if (sz
!= (ssize_t
)out
.l
)
1346 mime_fromhdr(&in
, &out
, TD_ISPR
| TD_ICONV
| (dflags
& TD_DELCTRL
));
1347 sz
= quoteflt_push(qf
, out
.s
, out
.l
);
1350 sz
= mime_write_tohdr(&in
, f
, NULL
, a_MIME_SH_NONE
);
1355 if(dflags
& _TD_BUFCOPY
){
1356 n_str_dup(&out
, &in
);
1359 dflags
&= ~_TD_BUFCOPY
;
1362 sz
= mime_write_tohdr_a(&in
, f
, &col
);
1365 sz
= _fwrite_td(&in
, dflags
, NULL
, qf
);
1374 safe_signal(SIGPIPE
, __mimemw_opipe
);
1375 if (__mimemw_sig
!= 0)
1376 n_raise(__mimemw_sig
);