..and.. FIX previous: do not stop list walk upon match, of course
[s-mailx.git] / mime-enc.c
blob2110dce9daeec25dae49761c1ce9b53f8c7bdb7f
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Content-Transfer-Encodings as defined in RFC 2045 (and RFC 2047;
3 *@ for _header() versions: including "encoded word" as of RFC 2049):
4 *@ - Quoted-Printable, section 6.7
5 *@ - Base64, section 6.8
6 *@ TODO We have no notion of a "current message context" and thus badly log.
7 *@ TODO This is not final yet, v15 will bring "filters".
9 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
10 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
12 /* QP quoting idea, _b64_decode(), b64_encode() taken from NetBSDs mailx(1): */
13 /* $NetBSD: mime_codecs.c,v 1.9 2009/04/10 13:08:25 christos Exp $ */
15 * Copyright (c) 2006 The NetBSD Foundation, Inc.
16 * All rights reserved.
18 * This code is derived from software contributed to The NetBSD Foundation
19 * by Anon Ymous.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
31 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
32 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
34 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
42 #undef n_FILE
43 #define n_FILE mime_enc
45 #ifndef HAVE_AMALGAMATION
46 # include "nail.h"
47 #endif
49 enum a_me_qact{
50 a_ME_N = 0,
51 a_ME_Q = 1, /* Must quote */
52 a_ME_SP = 2, /* sp */
53 a_ME_XF = 3, /* Special character 'F' - maybe quoted */
54 a_ME_XD = 4, /* Special character '.' - maybe quoted */
55 a_ME_UU = 5, /* In header, _ must be quoted in encoded word */
56 a_ME_US = '_', /* In header, ' ' must be quoted as _ in encoded word */
57 a_ME_QM = '?', /* In header, special character ? not always quoted */
58 a_ME_EQ = '=', /* In header, '=' must be quoted in encoded word */
59 a_ME_HT ='\t', /* Body HT=SP. Head HT=HT, BUT quote in encoded word */
60 a_ME_NL = 0, /* Don't quote '\n' (NL) */
61 a_ME_CR = a_ME_Q /* Always quote a '\r' (CR) */
64 /* Lookup tables to decide whether a character must be encoded or not.
65 * Email header differences according to RFC 2047, section 4.2:
66 * - also quote SP (as the underscore _), TAB, ?, _, CR, LF
67 * - don't care about the special ^F[rom] and ^.$ */
68 static ui8_t const a_me_qp_body[] = {
69 a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
70 a_ME_Q, a_ME_SP, a_ME_NL, a_ME_Q, a_ME_Q, a_ME_CR, a_ME_Q, a_ME_Q,
71 a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
72 a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
73 a_ME_SP, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
74 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_XD, a_ME_N,
75 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
76 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_Q, a_ME_N, a_ME_N,
78 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_XF, a_ME_N,
79 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
80 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
81 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
82 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
83 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
84 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
85 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_Q,
86 }, a_me_qp_head[] = {
87 a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
88 a_ME_Q, a_ME_HT, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
89 a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
90 a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q, a_ME_Q,
91 a_ME_US, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
92 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
93 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
94 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_EQ, a_ME_N, a_ME_QM,
96 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
97 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
98 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
99 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_UU,
100 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
101 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
102 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N,
103 a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_N, a_ME_Q,
106 /* The decoding table is only accessed via a_ME_B64_DECUI8() */
107 static char const a_me_b64_enctbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
108 "abcdefghijklmnopqrstuvwxyz" "0123456789" "+/";
109 static signed char const a_me_b64__dectbl[] = {
110 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
111 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
112 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
113 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-2,-1,-1,
114 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
115 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
116 -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
117 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
119 #define a_ME_B64_EQU (ui32_t)-2
120 #define a_ME_B64_BAD (ui32_t)-1
121 #define a_ME_B64_DECUI8(C) \
122 ((ui8_t)(C) >= sizeof(a_me_b64__dectbl)\
123 ? a_ME_B64_BAD : (ui32_t)a_me_b64__dectbl[(ui8_t)(C)])
125 /* (Ugly to place an enum here) */
126 static char const a_me_ctes[] = "7bit\0" "8bit\0" \
127 "base64\0" "quoted-printable\0" "binary\0" \
128 /* abbrevs */ "8b\0" "b64\0" "qp\0";
129 enum a_me_ctes_off{
130 a_ME_CTES_7B_OFF = 0, a_ME_CTES_7B_LEN = 4,
131 a_ME_CTES_8B_OFF = 5, a_ME_CTES_8B_LEN = 4,
132 a_ME_CTES_B64_OFF = 10, a_ME_CTES_B64_LEN = 6,
133 a_ME_CTES_QP_OFF = 17, a_ME_CTES_QP_LEN = 16,
134 a_ME_CTES_BIN_OFF = 34, a_ME_CTES_BIN_LEN = 6,
136 a_ME_CTES_S8B_OFF = 41, a_ME_CTES_S8B_LEN = 2,
137 a_ME_CTES_SB64_OFF = 44, a_ME_CTES_SB64_LEN = 3,
138 a_ME_CTES_SQP_OFF = 48, a_ME_CTES_SQP_LEN = 2
141 /* Check whether *s must be quoted according to flags, else body rules;
142 * sol indicates whether we are at the first character of a line/field */
143 SINLINE enum a_me_qact a_me_mustquote(char const *s, char const *e, bool_t sol,
144 enum mime_enc_flags flags);
146 /* Trim WS and make work point to the decodable range of in.
147 * Return the amount of bytes a b64_decode operation on that buffer requires,
148 * or UIZ_MAX on overflow error */
149 static size_t a_me_b64_decode_prepare(struct str *work, struct str const *in);
151 /* Perform b64_decode on in(put) to sufficiently spaced out(put).
152 * Return number of useful bytes in out or -1 on error.
153 * Note: may enter endless loop if in->l < 4 and 0 return is not handled! */
154 static ssize_t a_me_b64_decode(struct str *out, struct str *in);
156 SINLINE enum a_me_qact
157 a_me_mustquote(char const *s, char const *e, bool_t sol,
158 enum mime_enc_flags flags){
159 ui8_t const *qtab;
160 enum a_me_qact a, r;
161 NYD2_ENTER;
163 qtab = (flags & (MIMEEF_ISHEAD | MIMEEF_ISENCWORD))
164 ? a_me_qp_head : a_me_qp_body;
166 if((ui8_t)*s > 0x7F){
167 r = a_ME_Q;
168 goto jleave;
171 a = qtab[(ui8_t)*s];
173 if((r = a) == a_ME_N || a == a_ME_Q)
174 goto jleave;
176 r = a_ME_Q;
178 /* Special header fields */
179 if(flags & (MIMEEF_ISHEAD | MIMEEF_ISENCWORD)){
180 /* Special massage for encoded words */
181 if(flags & MIMEEF_ISENCWORD){
182 switch(a){
183 case a_ME_HT:
184 case a_ME_US:
185 case a_ME_EQ:
186 r = a;
187 /* FALLTHRU */
188 case a_ME_UU:
189 goto jleave;
190 default:
191 break;
195 /* Treat '?' only special if part of '=?' .. '?=' (still too much quoting
196 * since it's '=?CHARSET?CTE?stuff?=', and especially the trailing ?=
197 * should be hard to match */
198 if(a == a_ME_QM && ((!sol && s[-1] == '=') || (s < e && s[1] == '=')))
199 goto jleave;
200 goto jnquote;
203 /* Body-only */
205 if(a == a_ME_SP){
206 /* WS only if trailing white space */
207 if(&s[1] == e || s[1] == '\n')
208 goto jleave;
209 goto jnquote;
212 /* Rest are special begin-of-line cases */
213 if(!sol)
214 goto jnquote;
216 /* ^From */
217 if(a == a_ME_XF){
218 if(&s[4] < e && s[1] == 'r' && s[2] == 'o' && s[3] == 'm' && s[4] == ' ')
219 goto jleave;
220 goto jnquote;
222 /* ^.$ */
223 if(a == a_ME_XD && (&s[1] == e || s[1] == '\n'))
224 goto jleave;
225 jnquote:
226 r = 0;
227 jleave:
228 NYD2_LEAVE;
229 return r;
232 static size_t
233 a_me_b64_decode_prepare(struct str *work, struct str const *in){
234 size_t cp_len;
235 NYD2_ENTER;
237 *work = *in;
238 cp_len = n_str_trim(work)->l;
240 if(cp_len > 16){
241 /* n_ERR_OVERFLOW */
242 if(UIZ_MAX / 3 <= cp_len){
243 cp_len = UIZ_MAX;
244 goto jleave;
246 cp_len = ((cp_len * 3) >> 2) + (cp_len >> 3);
248 cp_len += (2 * 3) +1;
249 jleave:
250 NYD2_LEAVE;
251 return cp_len;
254 static ssize_t
255 a_me_b64_decode(struct str *out, struct str *in){
256 ui8_t *p, pb;
257 ui8_t const *q, *end;
258 ssize_t rv;
259 NYD2_ENTER;
261 rv = -1;
262 p = (ui8_t*)&out->s[out->l];
263 q = (ui8_t const*)in->s;
265 for(end = &q[in->l]; PTR2SIZE(end - q) >= 4; q += 4){
266 ui32_t a, b, c, d;
268 a = a_ME_B64_DECUI8(q[0]);
269 b = a_ME_B64_DECUI8(q[1]);
270 c = a_ME_B64_DECUI8(q[2]);
271 d = a_ME_B64_DECUI8(q[3]);
273 if(n_UNLIKELY(a >= a_ME_B64_EQU || b >= a_ME_B64_EQU ||
274 c == a_ME_B64_BAD || d == a_ME_B64_BAD))
275 goto jleave;
277 pb = ((a << 2) | ((b & 0x30) >> 4));
278 if(pb != (ui8_t)'\r' || !(n_pstate & n_PS_BASE64_STRIP_CR))
279 *p++ = pb;
281 if(c == a_ME_B64_EQU){ /* got '=' */
282 q += 4;
283 if(n_UNLIKELY(d != a_ME_B64_EQU))
284 goto jleave;
285 break;
288 pb = (((b & 0x0F) << 4) | ((c & 0x3C) >> 2));
289 if(pb != (ui8_t)'\r' || !(n_pstate & n_PS_BASE64_STRIP_CR))
290 *p++ = pb;
292 if(d == a_ME_B64_EQU) /* got '=' */
293 break;
294 pb = (((c & 0x03) << 6) | d);
295 if(pb != (ui8_t)'\r' || !(n_pstate & n_PS_BASE64_STRIP_CR))
296 *p++ = pb;
298 rv ^= rv;
300 jleave:{
301 size_t i;
303 i = PTR2SIZE((char*)p - out->s);
304 out->l = i;
305 if(rv == 0)
306 rv = (ssize_t)i;
308 in->l -= PTR2SIZE(q - (ui8_t*)in->s);
309 in->s = n_UNCONST(q);
310 NYD2_LEAVE;
311 return rv;
314 FL enum mime_enc
315 mime_enc_target(void){
316 char const *cp;
317 enum mime_enc rv;
318 NYD2_ENTER;
320 if((cp = ok_vlook(encoding)) == NULL)
321 rv = MIME_DEFAULT_ENCODING;
322 else if(!asccasecmp(cp, &a_me_ctes[a_ME_CTES_S8B_OFF]) ||
323 !asccasecmp(cp, &a_me_ctes[a_ME_CTES_8B_OFF]))
324 rv = MIMEE_8B;
325 else if(!asccasecmp(cp, &a_me_ctes[a_ME_CTES_SB64_OFF]) ||
326 !asccasecmp(cp, &a_me_ctes[a_ME_CTES_B64_OFF]))
327 rv = MIMEE_B64;
328 else if(!asccasecmp(cp, &a_me_ctes[a_ME_CTES_SQP_OFF]) ||
329 !asccasecmp(cp, &a_me_ctes[a_ME_CTES_QP_OFF]))
330 rv = MIMEE_QP;
331 else{
332 n_err(_("Warning: invalid *encoding*, using Base64: %s\n"), cp);
333 rv = MIMEE_B64;
335 NYD2_LEAVE;
336 return rv;
339 FL enum mime_enc
340 mime_enc_from_ctehead(char const *hbody){
341 enum mime_enc rv;
342 NYD2_ENTER;
344 if(hbody == NULL)
345 rv = MIMEE_7B;
346 else{
347 struct{
348 ui8_t off;
349 ui8_t len;
350 ui8_t enc;
351 ui8_t __dummy;
352 } const *cte, cte_base[] = {
353 {a_ME_CTES_7B_OFF, a_ME_CTES_7B_LEN, MIMEE_7B, 0},
354 {a_ME_CTES_8B_OFF, a_ME_CTES_8B_LEN, MIMEE_8B, 0},
355 {a_ME_CTES_B64_OFF, a_ME_CTES_B64_LEN, MIMEE_B64, 0},
356 {a_ME_CTES_QP_OFF, a_ME_CTES_QP_LEN, MIMEE_QP, 0},
357 {a_ME_CTES_BIN_OFF, a_ME_CTES_BIN_LEN, MIMEE_BIN, 0},
358 {0, 0, MIMEE_NONE, 0}
360 union {char const *s; size_t l;} u;
362 if(*hbody == '"')
363 for(u.s = ++hbody; *u.s != '\0' && *u.s != '"'; ++u.s)
365 else
366 for(u.s = hbody; *u.s != '\0' && !whitechar(*u.s); ++u.s)
368 u.l = PTR2SIZE(u.s - hbody);
370 for(cte = cte_base;;)
371 if(cte->len == u.l && !asccasecmp(&a_me_ctes[cte->off], hbody)){
372 rv = cte->enc;
373 break;
374 }else if((++cte)->enc == MIMEE_NONE){
375 rv = MIMEE_NONE;
376 break;
379 NYD2_LEAVE;
380 return rv;
383 FL char const *
384 mime_enc_from_conversion(enum conversion const convert){
385 char const *rv;
386 NYD2_ENTER;
388 switch(convert){
389 case CONV_7BIT: rv = &a_me_ctes[a_ME_CTES_7B_OFF]; break;
390 case CONV_8BIT: rv = &a_me_ctes[a_ME_CTES_8B_OFF]; break;
391 case CONV_TOQP: rv = &a_me_ctes[a_ME_CTES_QP_OFF]; break;
392 case CONV_TOB64: rv = &a_me_ctes[a_ME_CTES_B64_OFF]; break;
393 case CONV_NONE: rv = &a_me_ctes[a_ME_CTES_BIN_OFF]; break;
394 default: rv = n_empty; break;
396 NYD2_LEAVE;
397 return rv;
400 FL size_t
401 mime_enc_mustquote(char const *ln, size_t lnlen, enum mime_enc_flags flags){
402 size_t rv;
403 bool_t sol;
404 NYD2_ENTER;
406 for(rv = 0, sol = TRU1; lnlen > 0; sol = FAL0, ++ln, --lnlen)
407 switch(a_me_mustquote(ln, ln + lnlen, sol, flags)){
408 case a_ME_US:
409 case a_ME_EQ:
410 case a_ME_HT:
411 assert(flags & MIMEEF_ISENCWORD);
412 /* FALLTHRU */
413 case 0:
414 continue;
415 default:
416 ++rv;
418 NYD2_LEAVE;
419 return rv;
422 FL size_t
423 qp_encode_calc_size(size_t len){
424 size_t bytes, lines;
425 NYD2_ENTER;
427 /* The worst case sequence is 'CRLF' -> '=0D=0A=\n\0'.
428 * However, we must be aware that (a) the output may span multiple lines
429 * and (b) the input does not end with a newline itself (nonetheless):
430 * LC_ALL=C awk 'BEGIN{
431 * for (i = 1; i < 100000; ++i) printf "\xC3\xBC"
432 * }' |
433 * s-nail -:/ -dSsendcharsets=utf8 -s testsub no@where */
435 /* Several n_ERR_OVERFLOW */
436 if(len >= UIZ_MAX / 3){
437 len = UIZ_MAX;
438 goto jleave;
440 bytes = len * 3;
441 lines = bytes / QP_LINESIZE;
442 len += lines;
444 if(len >= UIZ_MAX / 3){
445 len = UIZ_MAX;
446 goto jleave;
448 /* Trailing hard NL may be missing, so there may be two lines.
449 * Thus add soft + hard NL per line and a trailing NUL */
450 bytes = len * 3;
451 lines = (bytes / QP_LINESIZE) + 1;
452 lines <<= 1;
453 ++bytes;
454 /*if(UIZ_MAX - bytes >= lines){
455 len = UIZ_MAX;
456 goto jleave;
458 bytes += lines;
459 len = bytes;
460 jleave:
461 NYD2_LEAVE;
462 return len;
465 #ifdef notyet
466 FL struct str *
467 qp_encode_cp(struct str *out, char const *cp, enum qpflags flags){
468 struct str in;
469 NYD_ENTER;
471 in.s = n_UNCONST(cp);
472 in.l = strlen(cp);
473 out = qp_encode(out, &in, flags);
474 NYD_LEAVE;
475 return out;
478 FL struct str *
479 qp_encode_buf(struct str *out, void const *vp, size_t vp_len,
480 enum qpflags flags){
481 struct str in;
482 NYD_ENTER;
484 in.s = n_UNCONST(vp);
485 in.l = vp_len;
486 out = qp_encode(out, &in, flags);
487 NYD_LEAVE;
488 return out;
490 #endif /* notyet */
492 FL struct str *
493 qp_encode(struct str *out, struct str const *in, enum qpflags flags){
494 size_t lnlen;
495 char *qp;
496 char const *is, *ie;
497 bool_t sol, seenx;
498 NYD_ENTER;
500 sol = (flags & QP_ISHEAD ? FAL0 : TRU1);
502 if(!(flags & QP_BUF)){
503 if((lnlen = qp_encode_calc_size(in->l)) == UIZ_MAX){
504 out = NULL;
505 goto jerr;
507 out->s = (flags & QP_SALLOC) ? salloc(lnlen) : srealloc(out->s, lnlen);
509 qp = out->s;
510 is = in->s;
511 ie = is + in->l;
513 if(flags & QP_ISHEAD){
514 enum mime_enc_flags ef;
516 ef = MIMEEF_ISHEAD | (flags & QP_ISENCWORD ? MIMEEF_ISENCWORD : 0);
518 for(seenx = FAL0, sol = TRU1; is < ie; sol = FAL0, ++qp){
519 char c;
520 enum a_me_qact mq;
522 mq = a_me_mustquote(is, ie, sol, ef);
523 c = *is++;
525 if(mq == a_ME_N){
526 /* We convert into a single *encoded-word*, that'll end up in
527 * =?C?Q??=; quote '?' from when we're inside there on */
528 if(seenx && c == '?')
529 goto jheadq;
530 *qp = c;
531 }else if(mq == a_ME_US)
532 *qp = a_ME_US;
533 else{
534 seenx = TRU1;
535 jheadq:
536 *qp++ = '=';
537 qp = n_c_to_hex_base16(qp, c) + 1;
540 goto jleave;
543 /* The body needs to take care for soft line breaks etc. */
544 for(lnlen = 0, seenx = FAL0; is < ie; sol = FAL0){
545 char c;
546 enum a_me_qact mq;
548 mq = a_me_mustquote(is, ie, sol, MIMEEF_NONE);
549 c = *is++;
551 if(mq == a_ME_N && (c != '\n' || !seenx)){
552 *qp++ = c;
553 if(++lnlen < QP_LINESIZE - 1)
554 continue;
555 /* Don't write a soft line break when we're in the last possible
556 * column and either an LF has been written or only an LF follows, as
557 * that'll end the line anyway */
558 /* XXX but - ensure is+1>=ie, then??
559 * xxx and/or - what about resetting lnlen; that contra
560 * xxx dicts input==1 input line assertion, though */
561 if(c == '\n' || is == ie || is[0] == '\n' || is[1] == '\n')
562 continue;
563 jsoftnl:
564 qp[0] = '=';
565 qp[1] = '\n';
566 qp += 2;
567 lnlen = 0;
568 continue;
571 if(lnlen > QP_LINESIZE - 3 - 1){
572 qp[0] = '=';
573 qp[1] = '\n';
574 qp += 2;
575 lnlen = 0;
577 *qp++ = '=';
578 qp = n_c_to_hex_base16(qp, c);
579 qp += 2;
580 lnlen += 3;
581 if(c != '\n' || !seenx)
582 seenx = (c == '\r');
583 else{
584 seenx = FAL0;
585 goto jsoftnl;
589 /* Enforce soft line break if we haven't seen LF */
590 if(in->l > 0 && *--is != '\n'){
591 qp[0] = '=';
592 qp[1] = '\n';
593 qp += 2;
595 jleave:
596 out->l = PTR2SIZE(qp - out->s);
597 out->s[out->l] = '\0';
598 jerr:
599 NYD_LEAVE;
600 return out;
603 FL bool_t
604 qp_decode_header(struct str *out, struct str const *in){
605 struct n_string s;
606 char const *is, *ie;
607 NYD_ENTER;
609 /* n_ERR_OVERFLOW */
610 if(UIZ_MAX -1 - out->l <= in->l ||
611 SI32_MAX <= out->l + in->l){ /* XXX wrong, we may replace */
612 out->l = 0;
613 out = NULL;
614 goto jleave;
617 n_string_creat(&s);
618 n_string_reserve(n_string_take_ownership(&s, out->s,
619 (out->l == 0 ? 0 : out->l +1), out->l),
620 in->l + (in->l >> 2));
622 for(is = in->s, ie = &is[in->l - 1]; is <= ie;){
623 si32_t c;
625 c = *is++;
626 if(c == '='){
627 if(is >= ie){
628 goto jpushc; /* TODO According to RFC 2045, 6.7,
629 * ++is; TODO we should warn the user, but have no context
630 * goto jehead; TODO to do so; can't over and over */
631 }else if((c = n_c_from_hex_base16(is)) >= 0){
632 is += 2;
633 goto jpushc;
634 }else{
635 /* Invalid according to RFC 2045, section 6.7 */
636 /* TODO Follow RFC 2045, 6.7 advise and simply put through */
637 c = '=';
638 goto jpushc;
639 /* TODO jehead:
640 * TODO if(n_psonce & n_PSO_UNICODE)
641 * n_string_push_buf(&s, n_unirepl, sizeof(n_unirepl) -1);
642 * TODO else{
643 * TODO c = '?';
644 * TODO goto jpushc;
645 * TODO }*/
647 }else{
648 jpushc:
649 if(c == '_' /* a_ME_US */)
650 c = ' ';
651 n_string_push_c(&s, (char)c);
655 out->s = n_string_cp(&s);
656 out->l = s.s_len;
657 n_string_gut(n_string_drop_ownership(&s));
658 jleave:
659 NYD_LEAVE;
660 return (out != NULL);
663 FL bool_t
664 qp_decode_part(struct str *out, struct str const *in, struct str *outrest,
665 struct str *inrest_or_null){
666 struct n_string s, *sp;
667 char const *is, *ie;
668 NYD_ENTER;
670 if(outrest->l != 0){
671 is = out->s;
672 *out = *outrest;
673 outrest->s = n_UNCONST(is);
674 outrest->l = 0;
677 /* n_ERR_OVERFLOW */
678 if(UIZ_MAX -1 - out->l <= in->l ||
679 SI32_MAX <= out->l + in->l) /* XXX wrong, we may replace */
680 goto jerr;
682 sp = n_string_creat(&s);
683 sp = n_string_take_ownership(sp, out->s,
684 (out->l == 0 ? 0 : out->l +1), out->l);
685 sp = n_string_reserve(sp, in->l + (in->l >> 2));
687 for(is = in->s, ie = &is[in->l - 1]; is <= ie;){
688 si32_t c;
690 if((c = *is++) != '='){
691 jpushc:
692 n_string_push_c(&s, (char)c);
693 continue;
696 /* RFC 2045, 6.7:
697 * Therefore, when decoding a Quoted-Printable body, any
698 * trailing white space on a line must be deleted, as it will
699 * necessarily have been added by intermediate transport
700 * agents */
701 for(; is <= ie && blankchar(*is); ++is)
703 if(is >= ie){
704 /* Soft line break? */
705 if(*is == '\n')
706 goto jsoftnl;
707 goto jpushc; /* TODO According to RFC 2045, 6.7,
708 * ++is; TODO we should warn the user, but have no context
709 * goto jebody; TODO to do so; can't over and over */
712 /* Not a soft line break? */
713 if(*is != '\n'){
714 if((c = n_c_from_hex_base16(is)) >= 0){
715 is += 2;
716 goto jpushc;
718 /* Invalid according to RFC 2045, section 6.7 */
719 /* TODO Follow RFC 2045, 6.7 advise and simply put through */
720 c = '=';
721 goto jpushc;
722 /* TODO jebody:
723 * TODO if(n_psonce & n_PSO_UNICODE)
724 * n_string_push_buf(&s, n_unirepl, sizeof(n_unirepl) -1);
725 * TODO else{
726 * TODO c = '?';
727 * TODO goto jpushc;
728 * TODO }*/
731 /* CRLF line endings are encoded as QP, followed by a soft line break, so
732 * check for this special case, and simply forget we have seen one, so as
733 * not to end up with the entire DOS file in a contiguous buffer */
734 jsoftnl:
735 if(s.s_len > 0 && s.s_dat[s.s_len - 1] == '\n'){
736 #if 0 /* TODO qp_decode_part() we do not normalize CRLF
737 * TODO to LF because for that we would need
738 * TODO to know if we are about to write to
739 * TODO the display or do save the file!
740 * TODO 'hope the MIME/send layer rewrite will
741 * TODO offer the possibility to DTRT */
742 if(s.s_len > 1 && s.s_dat[s.s_len - 2] == '\r')
743 n_string_push_c(n_string_trunc(&s, s.s_len - 2), '\n');
744 #endif
745 break;
748 /* C99 */{
749 char *cp;
750 size_t l;
752 if((l = PTR2SIZE(ie - is)) > 0){
753 if(inrest_or_null == NULL)
754 goto jerr;
755 n_str_assign_buf(inrest_or_null, is, l);
757 cp = outrest->s;
758 outrest->s = n_string_cp(&s);
759 outrest->l = s.s_len;
760 n_string_drop_ownership(&s);
761 if(cp != NULL)
762 free(cp);
764 break;
767 out->s = n_string_cp(&s);
768 out->l = s.s_len;
769 n_string_gut(n_string_drop_ownership(&s));
770 jleave:
771 NYD_LEAVE;
772 return (out != NULL);
773 jerr:
774 out->l = 0;
775 out = NULL;
776 goto jleave;
779 FL size_t
780 b64_encode_calc_size(size_t len){
781 NYD2_ENTER;
782 if(len >= UIZ_MAX / 4)
783 len = UIZ_MAX;
784 else{
785 len = (len * 4) / 3;
786 len += (((len / B64_ENCODE_INPUT_PER_LINE) + 1) * 3);
787 len += 2 + 1; /* CRLF, \0 */
789 NYD2_LEAVE;
790 return len;
793 FL struct str *
794 b64_encode(struct str *out, struct str const *in, enum b64flags flags){
795 ui8_t const *p;
796 size_t i, lnlen;
797 char *b64;
798 NYD_ENTER;
800 assert(!(flags & B64_NOPAD) ||
801 !(flags & (B64_CRLF | B64_LF | B64_MULTILINE)));
803 p = (ui8_t const*)in->s;
805 if(!(flags & B64_BUF)){
806 if((i = b64_encode_calc_size(in->l)) == UIZ_MAX){
807 out = NULL;
808 goto jleave;
810 out->s = (flags & B64_SALLOC) ? salloc(i) : srealloc(out->s, i);
812 b64 = out->s;
814 if(!(flags & (B64_CRLF | B64_LF)))
815 flags &= ~B64_MULTILINE;
817 for(lnlen = 0, i = in->l; (ssize_t)i > 0; p += 3, i -= 3){
818 ui32_t a, b, c;
820 a = p[0];
821 b64[0] = a_me_b64_enctbl[a >> 2];
823 switch(i){
824 case 1:
825 b64[1] = a_me_b64_enctbl[((a & 0x3) << 4)];
826 b64[2] =
827 b64[3] = '=';
828 break;
829 case 2:
830 b = p[1];
831 b64[1] = a_me_b64_enctbl[((a & 0x03) << 4) | ((b & 0xF0u) >> 4)];
832 b64[2] = a_me_b64_enctbl[((b & 0x0F) << 2)];
833 b64[3] = '=';
834 break;
835 default:
836 b = p[1];
837 c = p[2];
838 b64[1] = a_me_b64_enctbl[((a & 0x03) << 4) | ((b & 0xF0u) >> 4)];
839 b64[2] = a_me_b64_enctbl[((b & 0x0F) << 2) | ((c & 0xC0u) >> 6)];
840 b64[3] = a_me_b64_enctbl[c & 0x3F];
841 break;
844 b64 += 4;
845 if(!(flags & B64_MULTILINE))
846 continue;
847 lnlen += 4;
848 if(lnlen < B64_LINESIZE)
849 continue;
851 lnlen = 0;
852 if(flags & B64_CRLF)
853 *b64++ = '\r';
854 if(flags & (B64_CRLF | B64_LF))
855 *b64++ = '\n';
858 if((flags & (B64_CRLF | B64_LF)) &&
859 (!(flags & B64_MULTILINE) || lnlen != 0)){
860 if(flags & B64_CRLF)
861 *b64++ = '\r';
862 if(flags & (B64_CRLF | B64_LF))
863 *b64++ = '\n';
864 }else if(flags & B64_NOPAD)
865 while(b64 != out->s && b64[-1] == '=')
866 --b64;
868 out->l = PTR2SIZE(b64 - out->s);
869 out->s[out->l] = '\0';
871 /* Base64 includes + and /, replace them with _ and -.
872 * This is base64url according to RFC 4648, then. Since we only support
873 * that for encoding and it is only used for boundary strings, this is
874 * yet a primitive implementation; xxx use tables; support decoding */
875 if(flags & B64_RFC4648URL){
876 char c;
878 for(b64 = out->s; (c = *b64) != '\0'; ++b64)
879 if(c == '+')
880 *b64 = '-';
881 else if(c == '/')
882 *b64 = '_';
884 jleave:
885 NYD_LEAVE;
886 return out;
889 FL struct str *
890 b64_encode_buf(struct str *out, void const *vp, size_t vp_len,
891 enum b64flags flags){
892 struct str in;
893 NYD_ENTER;
895 in.s = n_UNCONST(vp);
896 in.l = vp_len;
897 out = b64_encode(out, &in, flags);
898 NYD_LEAVE;
899 return out;
902 #ifdef notyet
903 FL struct str *
904 b64_encode_cp(struct str *out, char const *cp, enum b64flags flags){
905 struct str in;
906 NYD_ENTER;
908 in.s = n_UNCONST(cp);
909 in.l = strlen(cp);
910 out = b64_encode(out, &in, flags);
911 NYD_LEAVE;
912 return out;
914 #endif /* notyet */
916 FL bool_t
917 b64_decode(struct str *out, struct str const *in){
918 struct str work;
919 size_t len;
920 NYD_ENTER;
922 out->l = 0;
924 if((len = a_me_b64_decode_prepare(&work, in)) == UIZ_MAX)
925 goto jerr;
927 /* Ignore an empty input, as may happen for an empty final line */
928 if(work.l == 0)
929 out->s = srealloc(out->s, 1);
930 else if(work.l >= 4 && !(work.l & 3)){
931 out->s = srealloc(out->s, len +1);
932 if((ssize_t)(len = a_me_b64_decode(out, &work)) < 0)
933 goto jerr;
934 }else
935 goto jerr;
936 out->s[out->l] = '\0';
937 jleave:
938 NYD_LEAVE;
939 return (out != NULL);
940 jerr:
941 out = NULL;
942 goto jleave;
945 FL bool_t
946 b64_decode_header(struct str *out, struct str const *in){
947 struct str outr, inr;
948 NYD_ENTER;
950 if(!b64_decode(out, in)){
951 memset(&outr, 0, sizeof outr);
952 memset(&inr, 0, sizeof inr);
954 if(!b64_decode_part(out, in, &outr, &inr) || outr.l > 0 || inr.l > 0)
955 out = NULL;
957 if(inr.s != NULL)
958 free(inr.s);
959 if(outr.s != NULL)
960 free(outr.s);
962 NYD_LEAVE;
963 return (out != NULL);
966 FL bool_t
967 b64_decode_part(struct str *out, struct str const *in, struct str *outrest,
968 struct str *inrest_or_null){
969 struct str work, save;
970 ui32_t a, b, c, b64l;
971 char ca, cb, cc, cx;
972 struct n_string s, workbuf;
973 size_t len;
974 NYD_ENTER;
976 n_string_creat(&s);
977 if((len = out->l) > 0 && out->s[len] == '\0')
978 n_string_take_ownership(&s, out->s, len +1, len);
979 else{
980 if(len > 0)
981 n_string_push_buf(&s, out->s, len);
982 if(out->s != NULL)
983 free(out->s);
985 out->s = NULL, out->l = 0;
986 n_string_creat(&workbuf);
988 if((len = a_me_b64_decode_prepare(&work, in)) == UIZ_MAX)
989 goto jerr;
991 if(outrest->l > 0){
992 n_string_push_buf(&s, outrest->s, outrest->l);
993 outrest->l = 0;
996 /* n_ERR_OVERFLOW */
997 if(UIZ_MAX - len <= s.s_len ||
998 SI32_MAX <= len + s.s_len) /* XXX wrong, we may replace */
999 goto jerr;
1001 if(work.l == 0)
1002 goto jok;
1004 /* This text decoder is extremely expensive, especially given that in all
1005 * but _invalid_ cases it is not even needed! So try once to do the normal
1006 * decoding, if that fails, go the hard way */
1007 save = work;
1008 out->s = n_string_resize(&s, len + (out->l = b64l = s.s_len))->s_dat;
1010 if(work.l >= 4 && a_me_b64_decode(out, &work) >= 0){
1011 n_string_trunc(&s, out->l);
1012 if(work.l == 0)
1013 goto jok;
1016 n_string_trunc(&s, b64l);
1017 work = save;
1018 out->s = NULL, out->l = 0;
1020 n_UNINIT(ca, 0);
1021 n_UNINIT(cb, 0);
1022 n_UNINIT(cc, 0);
1023 for(b64l = 0;;){
1024 ui32_t x;
1026 x = a_ME_B64_DECUI8((ui8_t)(cx = *work.s));
1027 switch(b64l){
1028 case 0:
1029 if(x >= a_ME_B64_EQU)
1030 goto jrepl;
1031 ca = cx;
1032 a = x;
1033 ++b64l;
1034 break;
1035 case 1:
1036 if(x >= a_ME_B64_EQU)
1037 goto jrepl;
1038 cb = cx;
1039 b = x;
1040 ++b64l;
1041 break;
1042 case 2:
1043 if(x == a_ME_B64_BAD)
1044 goto jrepl;
1045 cc = cx;
1046 c = x;
1047 ++b64l;
1048 break;
1049 case 3:
1050 if(x == a_ME_B64_BAD){
1051 jrepl:
1052 /* TODO This would be wrong since iconv(3) may be applied first! */
1053 #if 0
1054 if(n_psonce & n_PSO_UNICODE)
1055 n_string_push_buf(&s, n_unirepl, sizeof(n_unirepl) -1);
1056 else
1057 n_string_push_c(&s, '?');
1058 #endif
1060 }else if(c == a_ME_B64_EQU && x != a_ME_B64_EQU){
1061 /* This is not only invalid but bogus. Skip it over! */
1062 /* TODO This would be wrong since iconv(3) may be applied first! */
1063 #if 0
1064 n_string_push_buf(&s, n_UNIREPL n_UNIREPL n_UNIREPL n_UNIREPL,
1065 (sizeof(n_UNIREPL) -1) * 4);
1066 #endif
1067 b64l = 0;
1068 }else{
1069 ui8_t pb;
1071 pb = ((a << 2) | ((b & 0x30) >> 4));
1072 if(pb != (ui8_t)'\r' || !(n_pstate & n_PS_BASE64_STRIP_CR))
1073 n_string_push_c(&s, (char)pb);
1074 pb = (((b & 0x0F) << 4) | ((c & 0x3C) >> 2));
1075 if(pb != (ui8_t)'\r' || !(n_pstate & n_PS_BASE64_STRIP_CR))
1076 n_string_push_c(&s, (char)pb);
1077 if(x != a_ME_B64_EQU){
1078 pb = (((c & 0x03) << 6) | x);
1079 if(pb != (ui8_t)'\r' || !(n_pstate & n_PS_BASE64_STRIP_CR))
1080 n_string_push_c(&s, (char)pb);
1082 ++b64l;
1084 break;
1087 ++work.s;
1088 if(--work.l == 0){
1089 if(b64l > 0 && b64l != 4){
1090 if(inrest_or_null == NULL)
1091 goto jerr;
1092 inrest_or_null->s = srealloc(inrest_or_null->s, b64l +1);
1093 inrest_or_null->s[0] = ca;
1094 if(b64l > 1)
1095 inrest_or_null->s[1] = cb;
1096 if(b64l > 2)
1097 inrest_or_null->s[2] = cc;
1098 inrest_or_null->s[inrest_or_null->l = b64l] = '\0';
1100 goto jok;
1102 if(b64l == 4)
1103 b64l = 0;
1106 jok:
1107 out->s = n_string_cp(&s);
1108 out->l = s.s_len;
1109 n_string_drop_ownership(&s);
1110 jleave:
1111 n_string_gut(&workbuf);
1112 n_string_gut(&s);
1113 NYD_LEAVE;
1114 return (out != NULL);
1115 jerr:
1116 out = NULL;
1117 goto jleave;
1120 /* s-it-mode */