rfc2047.c
15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
/* GNU Mailutils -- a suite of utilities for electronic mail
Copyright (C) 2003, 2004 Free Software Foundation, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <mailutils/stream.h>
#include <mailutils/filter.h>
#include <mailutils/errno.h>
enum mu_iconv_fallback_mode rfc2047_fallback_mode = mu_fallback_copy_octal;
int
rfc2047_decode (const char *tocode, const char *input, char **ptostr)
{
int status = 0;
char *tmpcopy, *fromstr;
char *start_position = NULL;
char *buffer;
size_t bufsize;
size_t bufpos;
size_t run_count = 0;
if (!tocode || !input)
return EINVAL;
if (!ptostr)
return MU_ERR_OUT_PTR_NULL;
/* Prepare a temporary copy of the input string (strtok_r is
going to modify it. */
tmpcopy = strdup (input);
if (!tmpcopy)
return ENOMEM;
fromstr = tmpcopy;
/* Allocate the buffer. It is assumed that encoded string is always
longer than it's decoded variant, so it's safe to use its length
as the first estimate */
bufsize = strlen (fromstr) + 1;
buffer = malloc (bufsize);
if (buffer == NULL)
{
free (tmpcopy);
return ENOMEM;
}
bufpos = 0;
while (*fromstr)
{
if (strncmp (fromstr, "=?", 2) == 0)
{
char *fromcode = NULL;
char *encoding_type = NULL;
char *encoded_text = NULL;
stream_t filter = NULL, cvt = NULL;
stream_t in_stream = NULL;
const char *filter_type = NULL;
size_t nbytes = 0, size;
char *sp = NULL;
start_position = fromstr;
fromcode = strtok_r (start_position + 2, "?", &sp);
encoding_type = strtok_r (NULL, "?", &sp);
encoded_text = strtok_r (NULL, "?", &sp);
if (sp == NULL || sp[0] != '=')
{
status = MU_ERR_BAD_2047_INPUT;
break;
}
if (fromcode == NULL
|| encoding_type == NULL
|| encoded_text == NULL)
{
status = MU_ERR_BAD_2047_INPUT;
break;
}
size = strlen (encoded_text);
switch (toupper (encoding_type[0]))
{
case 'B':
filter_type = "base64";
break;
case 'Q':
filter_type = "Q";
break;
default:
status = MU_ERR_BAD_2047_INPUT;
break;
}
if (status != 0)
break;
memory_stream_create (&in_stream, 0, 0);
stream_write (in_stream, encoded_text, size, 0, NULL);
status = filter_create (&filter, in_stream, filter_type,
MU_FILTER_DECODE, MU_STREAM_READ);
if (status != 0)
break;
status = filter_iconv_create (&cvt, filter, fromcode, tocode,
MU_STREAM_NO_CLOSE,
rfc2047_fallback_mode);
if (status)
{
cvt = filter;
/* Note: the filter stream is already open! */
}
else
{
if (stream_open (cvt))
{
stream_destroy (&cvt, stream_get_owner (cvt));
cvt = filter;
}
else
{
int flags;
stream_get_flags (cvt, &flags);
flags &= ~MU_STREAM_NO_CLOSE;
stream_set_flags (cvt, flags);
}
}
while (stream_sequential_read (cvt, buffer + bufpos,
bufsize - bufpos,
&nbytes) == 0 && nbytes)
{
bufpos += nbytes;
}
stream_close (cvt);
stream_destroy (&cvt, stream_get_owner (cvt));
fromstr = sp + 1;
run_count = 1;
}
else if (run_count)
{
if (*fromstr == ' ' || *fromstr == '\t')
{
run_count++;
fromstr++;
continue;
}
else
{
if (--run_count)
{
memcpy (buffer + bufpos, fromstr - run_count, run_count);
bufpos += run_count;
run_count = 0;
}
buffer[bufpos++] = *fromstr++;
}
}
else
buffer[bufpos++] = *fromstr++;
}
if (*fromstr)
{
size_t len = strlen (fromstr);
if (bufpos + len + 1 > bufsize) /* just in case */
status = MU_ERR_BAD_2047_INPUT;
else
{
memcpy (buffer + bufpos, fromstr, strlen (fromstr));
bufpos += strlen (fromstr);
}
}
buffer[bufpos++] = 0;
free (tmpcopy);
*ptostr = realloc (buffer, bufpos);
return status;
}
/* ==================================================
RFC 2047 Encoder
================================================== */
#define MAX_QUOTE 75
/* Be more conservative in what we quote than in RFC2045, as in some
circumstances, additional symbols (like parenthesis) must be quoted
in headers. This is never a problem for the recipient, except for
the extra overhead in the message size */
static int
must_quote (char c)
{
if (((c > 32) && (c <= 57)) ||
((c >= 64) && (c <= 126)))
return 0;
return 1;
}
/* State of the encoder */
typedef struct _encoder rfc2047_encoder;
struct _encoder {
/* Name of the encoding (either B or Q) */
char encoding;
/* Charset of the input stream */
const char * charset;
/* Compute the size of the next character (in bytes), according to
the charset */
int (* charcount) (const char *);
/* Size of the next character (in bytes) */
int charblock;
/* TRUE if we need to open a quoted-word at the next byte */
int must_open;
/* Pointer on the current input byte */
const unsigned char * src;
/* Pointer on the current output byte and on the complete output */
char * dst, * result;
/* todo: number of bytes remaining in the input, done: number of
bytes written in the output, quotesize: number of bytes in the
current quoted-word */
int todo, done, quotesize;
/* Virtual methods implemented for the encoders:
count: return how many bytes would be used by inserting the
current input and updates 'charblock'
next: quote the current input byte on the output
flush: output any pending byte
*/
int (* count) (rfc2047_encoder * enc);
int (* next) (rfc2047_encoder * enc);
void (* flush) (rfc2047_encoder * enc);
/* Extra data for the Base64 encoder */
unsigned char buffer [4];
int state;
};
/* --------------------------------------------------
Quoted-words building blocks
-------------------------------------------------- */
/* Write the opening of a quoted-word and return the minimum number of
bytes it will use */
static int
_open_quote (const char * charset,
char encoding,
char ** dst, int * done)
{
int len = strlen (charset) + 5;
(* done) += len;
if (* dst)
{
sprintf (* dst, "=?%s?%c?", charset, encoding);
(* dst) += len;
}
/* in the initial length of the quote we already count the final ?= */
return len + 2;
}
/* Terminate a quoted-word */
static void
_close_quote (char ** dst, int * done)
{
* done += 2;
if (* dst)
{
strcpy (* dst, "?=");
(* dst) += 2;
}
}
/* Call this function before the beginning of a quoted-word */
static void
init_quoted (rfc2047_encoder * enc)
{
enc->must_open = 1;
}
/* Insert the current byte in the quoted-word (handling maximum
quoted-word sizes,...) */
static void
insert_quoted (rfc2047_encoder * enc)
{
if (enc->must_open)
{
enc->must_open = 0;
/* The quotesize holds the known size of the quoted-word, even
if all the bytes have not yet been inserted in the output
stream. */
enc->quotesize =
_open_quote (enc->charset, enc->encoding,
& enc->dst, & enc->done) + enc->count (enc);
}
else
{
if (enc->charblock == 0)
{
/* The quotesize holds the known size of the quoted-word,
even if all the bytes have not yet been inserted in the
output stream. */
enc->quotesize += enc->count (enc);
if (enc->quotesize > MAX_QUOTE)
{
/* Start a new quoted-word */
_close_quote (& enc->dst, & enc->done);
if (enc->dst) * (enc->dst ++) = ' ';
enc->done ++;
enc->quotesize = _open_quote (enc->charset, enc->encoding,
& enc->dst, & enc->done);
}
}
}
/* We are ready to process one more byte from the input stream */
enc->charblock --;
enc->next (enc);
}
/* Flush the current quoted-word */
static void
flush_quoted (rfc2047_encoder * enc)
{
if (enc->must_open) return;
enc->flush (enc);
_close_quote (& enc->dst, & enc->done);
}
/* Insert the current byte unquoted */
static void
insert_unquoted (rfc2047_encoder * enc)
{
if (enc->dst) * (enc->dst ++) = * (enc->src);
enc->src ++;
enc->todo --;
enc->done ++;
}
/* Check if the next word will need to be quoted */
static int
is_next_quoted (const char * src)
{
while (isspace (* src)) src ++;
while (* src)
{
if (isspace (* src)) return 0;
if (must_quote (* src)) return 1;
src ++;
}
return 0;
}
/* --------------------------------------------------
Known character encodings
-------------------------------------------------- */
static int
ce_single_byte (const char * src)
{
return 1;
}
static int
ce_utf_8 (const char * src)
{
unsigned char c = * src;
if (c <= 0x7F) return 1;
if (c >= 0xFC) return 6;
if (c >= 0xF8) return 5;
if (c >= 0xF0) return 4;
if (c >= 0xE0) return 3;
if (c >= 0xC0) return 2;
/* otherwise, this is not a first byte (and the UTF-8 is possibly
broken), continue with a single byte. */
return 1;
}
/* --------------------------------------------------
Quoted-printable encoder
-------------------------------------------------- */
static void
qp_init (rfc2047_encoder * enc)
{
return;
}
static int
qp_count (rfc2047_encoder * enc)
{
int len = 0, todo;
unsigned const char * curr;
/* count the size of a complete (multibyte) character */
enc->charblock = enc->charcount (enc->src);
for (todo = 0, curr = enc->src ;
todo < enc->charblock && * curr;
todo ++, curr ++)
{
len += must_quote (* curr) ? 3 : 1;
}
return len;
}
static const char _hexdigit[16] = "0123456789ABCDEF";
static int
qp_next (rfc2047_encoder * enc)
{
int done;
if (* enc->src == '_' || must_quote (* enc->src))
{
/* special encoding of space as a '_' to increase readability */
if (* enc->src == ' ')
{
if (enc->dst)
{
* (enc->dst ++) = '_';
}
done = 1;
}
else {
/* default encoding */
if (enc->dst)
{
* (enc->dst ++) = '=';
* (enc->dst ++) = _hexdigit [* (enc->src) >> 4];
* (enc->dst ++) = _hexdigit [* (enc->src) & 0xF];
}
done = 3;
}
}
else
{
if (enc->dst)
{
* (enc->dst ++) = * enc->src;
}
done = 1;
}
enc->src ++;
enc->done += done;
enc->todo --;
return done;
}
static void
qp_flush (rfc2047_encoder * enc)
{
return;
}
/* --------------------------------------------------
Base64 encoder
-------------------------------------------------- */
const char *b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static void
base64_init (rfc2047_encoder * enc)
{
enc->state = 0;
return;
}
static int
base64_count (rfc2047_encoder * enc)
{
int len = 0, todo;
/* Check the size of a complete (multibyte) character */
enc->charblock = enc->charcount (enc->src);
for (todo = 0 ; todo < enc->charblock; todo ++)
{
/* Count the size of the encoded block only once, at the first
byte transmitted. */
len += ((enc->state + todo) % 3 == 0) ? 4 : 0;
}
return len;
}
static int
base64_next (rfc2047_encoder * enc)
{
enc->buffer [enc->state ++] = * (enc->src ++);
enc->todo --;
if (enc->state < 3) return 0;
/* We have a full quantum */
if (enc->dst)
{
* (enc->dst ++) = b64 [(enc->buffer[0] >> 2)];
* (enc->dst ++) = b64 [((enc->buffer[0] & 0x3) << 4) | (enc->buffer[1] >> 4)];
* (enc->dst ++) = b64 [((enc->buffer[1] & 0xF) << 2) | (enc->buffer[2] >> 6)];
* (enc->dst ++) = b64 [(enc->buffer[2] & 0x3F)];
}
enc->done += 4;
enc->state = 0;
return 4;
}
static void
base64_flush (rfc2047_encoder * enc)
{
if (enc->state == 0) return;
if (enc->dst)
{
switch (enc->state)
{
case 1:
* (enc->dst ++) = b64 [(enc->buffer[0] >> 2)];
* (enc->dst ++) = b64 [((enc->buffer[0] & 0x3) << 4)];
* (enc->dst ++) = '=';
* (enc->dst ++) = '=';
break;
case 2:
* (enc->dst ++) = b64 [(enc->buffer[0] >> 2)];
* (enc->dst ++) = b64 [((enc->buffer[0] & 0x3) << 4) | (enc->buffer[1] >> 4)];
* (enc->dst ++) = b64 [((enc->buffer[1] & 0xF) << 2)];
* (enc->dst ++) = '=';
break;
}
}
enc->done += 4;
enc->state = 0;
return;
}
/* States of the RFC2047 encoder */
enum {
ST_SPACE, /* waiting for non-quoted whitespace */
ST_WORD, /* waiting for non-quoted word */
ST_QUOTED, /* waiting for quoted word */
ST_QUOTED_SPACE, /* waiting for quoted whitespace */
};
/**
Encode a header according to RFC 2047
@param charset
Charset of the text to encode
@param encoding
Requested encoding (must be "base64" or "quoted-printable")
@param text
Actual text to encode
@param result [OUT]
Encoded string
@return 0 on success
*/
int
rfc2047_encode (const char *charset, const char *encoding,
const char *text, char ** result)
{
rfc2047_encoder enc;
int is_compose;
int state;
if (!charset || !encoding || !text)
return EINVAL;
if (!result)
return MU_ERR_OUT_PTR_NULL;
/* Check for a known encoding */
do
{
if (strcasecmp (encoding, "base64") == 0)
{
base64_init (& enc);
enc.encoding = 'B';
enc.next = base64_next;
enc.count = base64_count;
enc.flush = base64_flush;
break;
}
if (strcasecmp (encoding, "quoted-printable") == 0)
{
qp_init (& enc);
enc.encoding = 'Q';
enc.next = qp_next;
enc.count = qp_count;
enc.flush = qp_flush;
break;
}
return MU_ERR_NOENT;
}
while (0);
/* Check for a known charset */
do
{
if (strcasecmp (charset, "utf-8") == 0)
{
enc.charcount = ce_utf_8;
break;
}
enc.charcount = ce_single_byte;
}
while (0);
enc.dst = NULL;
enc.charset = charset;
/* proceed in two passes: estimate the required space, then fill */
for (is_compose = 0 ; is_compose <= 1 ; is_compose ++)
{
state = ST_SPACE;
enc.src = text;
enc.todo = strlen (text);
enc.done = 0;
while (enc.todo)
{
switch (state)
{
case ST_SPACE:
if (isspace (* enc.src))
{
insert_unquoted (& enc);
break;
}
if (is_next_quoted (enc.src))
{
init_quoted (& enc);
state = ST_QUOTED;
}
else
{
state = ST_WORD;
}
break;
case ST_WORD:
if (isspace (* enc.src))
{
state = ST_SPACE;
break;
}
insert_unquoted (& enc);
break;
case ST_QUOTED:
if (isspace (* enc.src))
{
if (is_next_quoted (enc.src))
{
state = ST_QUOTED_SPACE;
}
else
{
flush_quoted (& enc);
state = ST_SPACE;
}
break;
}
insert_quoted (& enc);
break;
case ST_QUOTED_SPACE:
if (! isspace (* enc.src))
{
state = ST_QUOTED;
break;
}
insert_quoted (& enc);
break;
}
}
if (state == ST_QUOTED ||
state == ST_QUOTED_SPACE)
{
flush_quoted (& enc);
}
if (enc.dst == NULL)
{
enc.dst = malloc (enc.done + 1);
if (enc.dst == NULL) return -ENOMEM;
enc.result = enc.dst;
}
}
* (enc.dst) = '\0';
* result = enc.result;
return 0;
}