tar: support -T - and -X -
[oweals/busybox.git] / mailutils / mime.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * makemime: create MIME-encoded message
4  * reformime: parse MIME-encoded message
5  *
6  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
7  *
8  * Licensed under GPLv2, see file LICENSE in this source tree.
9  */
10 #include "libbb.h"
11 #include "mail.h"
12
13 /*
14   makemime -c type [-o file] [-e encoding] [-C charset] [-N name] \
15                    [-a "Header: Contents"] file
16            -m [ type ] [-o file] [-e encoding] [-a "Header: Contents"] file
17            -j [-o file] file1 file2
18            @file
19
20    file:  filename    - read or write from filename
21           -           - read or write from stdin or stdout
22           &n          - read or write from file descriptor n
23           \( opts \)  - read from child process, that generates [ opts ]
24
25 Options:
26
27   -c type         - create a new MIME section from "file" with this
28                     Content-Type: (default is application/octet-stream).
29   -C charset      - MIME charset of a new text/plain section.
30   -N name         - MIME content name of the new mime section.
31   -m [ type ]     - create a multipart mime section from "file" of this
32                     Content-Type: (default is multipart/mixed).
33   -e encoding     - use the given encoding (7bit, 8bit, quoted-printable,
34                     or base64), instead of guessing.  Omit "-e" and use
35                     -c auto to set Content-Type: to text/plain or
36                     application/octet-stream based on picked encoding.
37   -j file1 file2  - join mime section file2 to multipart section file1.
38   -o file         - write the result to file, instead of stdout (not
39                     allowed in child processes).
40   -a header       - prepend an additional header to the output.
41
42   @file - read all of the above options from file, one option or
43           value on each line.
44   {which version of makemime is this? What do we support?}
45 */
46
47
48 /* In busybox 1.15.0.svn, makemime generates output like this
49  * (empty lines are shown exactly!):
50 {headers added with -a HDR}
51 Mime-Version: 1.0
52 Content-Type: multipart/mixed; boundary="24269534-2145583448-1655890676"
53
54 --24269534-2145583448-1655890676
55 Content-Type: {set by -c, e.g. text/plain}; charset={set by -C, e.g. us-ascii}
56 Content-Disposition: inline; filename="A"
57 Content-Transfer-Encoding: base64
58
59 ...file A contents...
60 --24269534-2145583448-1655890676
61 Content-Type: {set by -c, e.g. text/plain}; charset={set by -C, e.g. us-ascii}
62 Content-Disposition: inline; filename="B"
63 Content-Transfer-Encoding: base64
64
65 ...file B contents...
66 --24269534-2145583448-1655890676--
67
68 */
69
70
71 /* For reference: here is an example email to LKML which has
72  * 1st unnamed part (so it serves as an email body)
73  * and one attached file:
74 ...other headers...
75 Content-Type: multipart/mixed; boundary="=-tOfTf3byOS0vZgxEWcX+"
76 ...other headers...
77 Mime-Version: 1.0
78 ...other headers...
79
80
81 --=-tOfTf3byOS0vZgxEWcX+
82 Content-Type: text/plain
83 Content-Transfer-Encoding: 7bit
84
85 ...email text...
86 ...email text...
87
88
89 --=-tOfTf3byOS0vZgxEWcX+
90 Content-Disposition: attachment; filename="xyz"
91 Content-Type: text/plain; name="xyz"; charset="UTF-8"
92 Content-Transfer-Encoding: 7bit
93
94 ...file contents...
95 ...file contents...
96
97 --=-tOfTf3byOS0vZgxEWcX+--
98
99 ...random junk added by mailing list robots and such...
100 */
101
102 /* man makemime:
103
104  * -c TYPE: create a (non-multipart) MIME section with Content-Type: TYPE
105  * makemime -c TYPE [-e ENCODING] [-o OUTFILE] [-C CHARSET] [-N NAME] [-a HEADER...] FILE
106  * The -C option sets the MIME charset attribute for text/plain content.
107  * The -N option sets the name attribute for Content-Type:
108  * Encoding must be one of the following: 7bit, 8bit, quoted-printable, or base64.
109
110  * -m multipart/TYPE: create a multipart MIME collection with Content-Type: multipart/TYPE
111  * makemime -m multipart/TYPE [-e ENCODING] [-o OUTFILE] [-a HEADER...] FILE
112  * Type must be either "multipart/mixed", "multipart/alternative", or some other MIME multipart content type.
113  * Additionally, encoding can only be "7bit" or "8bit", and will default to "8bit" if not specified.
114  * Finally, filename must be a MIME-formatted section, NOT a regular file.
115  * The -m option creates an initial multipart MIME collection, that contains only one MIME section, taken from filename.
116  * The collection is written to standard output, or the pipe or to outputfile.
117
118  * -j FILE1: add a section to a multipart MIME collection
119  * makemime -j FILE1 [-o OUTFILE] FILE2
120  * FILE1 must be a MIME collection that was previously created by the -m option.
121  * FILE2 must be a MIME section that was previously created by the -c option.
122  * The -j options adds the MIME section in FILE2 to the MIME collection in FILE1.
123  */
124 int makemime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
125 int makemime_main(int argc UNUSED_PARAM, char **argv)
126 {
127         llist_t *opt_headers = NULL, *l;
128         const char *opt_output;
129 #define boundary opt_output
130
131         enum {
132                 OPT_c = 1 << 0,         // create (non-multipart) section
133                 OPT_e = 1 << 1,         // Content-Transfer-Encoding. Ignored. Assumed base64
134                 OPT_o = 1 << 2,         // output to
135                 OPT_C = 1 << 3,         // charset
136                 OPT_N = 1 << 4,         // COMPAT
137                 OPT_a = 1 << 5,         // additional headers
138                 //OPT_m = 1 << 6,         // create mutipart section
139                 //OPT_j = 1 << 7,         // join section to multipart section
140         };
141
142         INIT_G();
143
144         // parse options
145         opt_complementary = "a::";
146         opts = getopt32(argv,
147                 "c:e:o:C:N:a", //:m:j:",
148                 &G.content_type, NULL, &opt_output, &G.opt_charset, NULL, &opt_headers //, NULL, NULL
149         );
150         //argc -= optind;
151         argv += optind;
152
153         // respect -o output
154         if (opts & OPT_o)
155                 freopen(opt_output, "w", stdout);
156
157         // no files given on command line? -> use stdin
158         if (!*argv)
159                 *--argv = (char *)"-";
160
161         // put additional headers
162         for (l = opt_headers; l; l = l->link)
163                 puts(l->data);
164
165         // make a random string -- it will delimit message parts
166         srand(monotonic_us());
167         boundary = xasprintf("%u-%u-%u",
168                         (unsigned)rand(), (unsigned)rand(), (unsigned)rand());
169
170         // put multipart header
171         printf(
172                 "Mime-Version: 1.0\n"
173                 "Content-Type: multipart/mixed; boundary=\"%s\"\n"
174                 , boundary
175         );
176
177         // put attachments
178         while (*argv) {
179                 printf(
180                         "\n--%s\n"
181                         "Content-Type: %s; charset=%s\n"
182                         "Content-Disposition: inline; filename=\"%s\"\n"
183                         "Content-Transfer-Encoding: base64\n"
184                         , boundary
185                         , G.content_type
186                         , G.opt_charset
187                         , bb_get_last_path_component_strip(*argv)
188                 );
189                 encode_base64(*argv++, (const char *)stdin, "");
190         }
191
192         // put multipart footer
193         printf("\n--%s--\n" "\n", boundary);
194
195         return EXIT_SUCCESS;
196 #undef boundary
197 }
198
199 static const char *find_token(const char *const string_array[], const char *key, const char *defvalue)
200 {
201         const char *r = NULL;
202         int i;
203         for (i = 0; string_array[i] != NULL; i++) {
204                 if (strcasecmp(string_array[i], key) == 0) {
205                         r = (char *)string_array[i+1];
206                         break;
207                 }
208         }
209         return (r) ? r : defvalue;
210 }
211
212 static const char *xfind_token(const char *const string_array[], const char *key)
213 {
214         const char *r = find_token(string_array, key, NULL);
215         if (r)
216                 return r;
217         bb_error_msg_and_die("header: %s", key);
218 }
219
220 enum {
221         OPT_x = 1 << 0,
222         OPT_X = 1 << 1,
223 #if ENABLE_FEATURE_REFORMIME_COMPAT
224         OPT_d = 1 << 2,
225         OPT_e = 1 << 3,
226         OPT_i = 1 << 4,
227         OPT_s = 1 << 5,
228         OPT_r = 1 << 6,
229         OPT_c = 1 << 7,
230         OPT_m = 1 << 8,
231         OPT_h = 1 << 9,
232         OPT_o = 1 << 10,
233         OPT_O = 1 << 11,
234 #endif
235 };
236
237 static int parse(const char *boundary, char **argv)
238 {
239         char *line, *s, *p;
240         const char *type;
241         int boundary_len = strlen(boundary);
242         const char *delims = " ;\"\t\r\n";
243         const char *uniq;
244         int ntokens;
245         const char *tokens[32]; // 32 is enough
246
247         // prepare unique string pattern
248         uniq = xasprintf("%%llu.%u.%s", (unsigned)getpid(), safe_gethostname());
249
250 //bb_info_msg("PARSE[%s]", uniq);
251
252         while ((line = xmalloc_fgets_str(stdin, "\r\n\r\n")) != NULL) {
253
254                 // seek to start of MIME section
255                 // N.B. to avoid false positives let us seek to the _last_ occurance
256                 p = NULL;
257                 s = line;
258                 while ((s = strcasestr(s, "Content-Type:")) != NULL)
259                         p = s++;
260                 if (!p)
261                         goto next;
262 //bb_info_msg("L[%s]", p);
263
264                 // split to tokens
265                 // TODO: strip of comments which are of form: (comment-text)
266                 ntokens = 0;
267                 tokens[ntokens] = NULL;
268                 for (s = strtok(p, delims); s; s = strtok(NULL, delims)) {
269                         tokens[ntokens] = s;
270                         if (ntokens < ARRAY_SIZE(tokens) - 1)
271                                 ntokens++;
272 //bb_info_msg("L[%d][%s]", ntokens, s);
273                 }
274                 tokens[ntokens] = NULL;
275 //bb_info_msg("N[%d]", ntokens);
276
277                 // analyse tokens
278                 type = find_token(tokens, "Content-Type:", "text/plain");
279 //bb_info_msg("T[%s]", type);
280                 if (0 == strncasecmp(type, "multipart/", 10)) {
281                         if (0 == strcasecmp(type+10, "mixed")) {
282                                 parse(xfind_token(tokens, "boundary="), argv);
283                         } else
284                                 bb_error_msg_and_die("no support of content type '%s'", type);
285                 } else {
286                         pid_t pid = pid;
287                         int rc;
288                         FILE *fp;
289                         // fetch charset
290                         const char *charset = find_token(tokens, "charset=", CONFIG_FEATURE_MIME_CHARSET);
291                         // fetch encoding
292                         const char *encoding = find_token(tokens, "Content-Transfer-Encoding:", "7bit");
293                         // compose target filename
294                         char *filename = (char *)find_token(tokens, "filename=", NULL);
295                         if (!filename)
296                                 filename = xasprintf(uniq, monotonic_us());
297                         else
298                                 filename = bb_get_last_path_component_strip(xstrdup(filename));
299
300                         // start external helper, if any
301                         if (opts & OPT_X) {
302                                 int fd[2];
303                                 xpipe(fd);
304                                 pid = vfork();
305                                 if (0 == pid) {
306                                         // child reads from fd[0]
307                                         close(fd[1]);
308                                         xmove_fd(fd[0], STDIN_FILENO);
309                                         xsetenv("CONTENT_TYPE", type);
310                                         xsetenv("CHARSET", charset);
311                                         xsetenv("ENCODING", encoding);
312                                         xsetenv("FILENAME", filename);
313                                         BB_EXECVP_or_die(argv);
314                                 }
315                                 // parent dumps to fd[1]
316                                 close(fd[0]);
317                                 fp = xfdopen_for_write(fd[1]);
318                                 signal(SIGPIPE, SIG_IGN); // ignore EPIPE
319                         // or create a file for dump
320                         } else {
321                                 char *fname = xasprintf("%s%s", *argv, filename);
322                                 fp = xfopen_for_write(fname);
323                                 free(fname);
324                         }
325
326                         // housekeeping
327                         free(filename);
328
329                         // dump to fp
330                         if (0 == strcasecmp(encoding, "base64")) {
331                                 read_base64(stdin, fp, '-');
332                         } else if (0 != strcasecmp(encoding, "7bit")
333                                 && 0 != strcasecmp(encoding, "8bit")
334                         ) {
335                                 // quoted-printable, binary, user-defined are unsupported so far
336                                 bb_error_msg_and_die("no support of encoding '%s'", encoding);
337                         } else {
338                                 // N.B. we have written redundant \n. so truncate the file
339                                 // The following weird 2-tacts reading technique is due to
340                                 // we have to not write extra \n at the end of the file
341                                 // In case of -x option we could truncate the resulting file as
342                                 // fseek(fp, -1, SEEK_END);
343                                 // if (ftruncate(fileno(fp), ftell(fp)))
344                                 //      bb_perror_msg("ftruncate");
345                                 // But in case of -X we have to be much more careful. There is
346                                 // no means to truncate what we already have sent to the helper.
347                                 p = xmalloc_fgets_str(stdin, "\r\n");
348                                 while (p) {
349                                         s = xmalloc_fgets_str(stdin, "\r\n");
350                                         if (s == NULL)
351                                                 break;
352                                         if ('-' == s[0]
353                                          && '-' == s[1]
354                                          && 0 == strncmp(s+2, boundary, boundary_len)
355                                         ) {
356                                                 break;
357                                         }
358                                         fputs(p, fp);
359                                         p = s;
360                                 }
361
362 /*
363                                 while ((s = xmalloc_fgetline_str(stdin, "\r\n")) != NULL) {
364                                         if ('-' == s[0] && '-' == s[1]
365                                                 && 0 == strncmp(s+2, boundary, boundary_len))
366                                                 break;
367                                         fprintf(fp, "%s\n", s);
368                                 }
369                                 // N.B. we have written redundant \n. so truncate the file
370                                 fseek(fp, -1, SEEK_END);
371                                 if (ftruncate(fileno(fp), ftell(fp)))
372                                         bb_perror_msg("ftruncate");
373 */
374                         }
375                         fclose(fp);
376
377                         // finalize helper
378                         if (opts & OPT_X) {
379                                 signal(SIGPIPE, SIG_DFL);
380                                 // exit if helper exited >0
381                                 rc = (wait4pid(pid) & 0xff);
382                                 if (rc)
383                                         return rc+20;
384                         }
385
386                         // check multipart finalized
387                         if (s && '-' == s[2+boundary_len] && '-' == s[2+boundary_len+1]) {
388                                 free(line);
389                                 break;
390                         }
391                 }
392  next:
393                 free(line);
394         }
395
396 //bb_info_msg("ENDPARSE[%s]", boundary);
397
398         return EXIT_SUCCESS;
399 }
400
401 /*
402 Usage: reformime [options]
403     -d - parse a delivery status notification.
404     -e - extract contents of MIME section.
405     -x - extract MIME section to a file.
406     -X - pipe MIME section to a program.
407     -i - show MIME info.
408     -s n.n.n.n - specify MIME section.
409     -r - rewrite message, filling in missing MIME headers.
410     -r7 - also convert 8bit/raw encoding to quoted-printable, if possible.
411     -r8 - also convert quoted-printable encoding to 8bit, if possible.
412     -c charset - default charset for rewriting, -o, and -O.
413     -m [file] [file]... - create a MIME message digest.
414     -h "header" - decode RFC 2047-encoded header.
415     -o "header" - encode unstructured header using RFC 2047.
416     -O "header" - encode address list header using RFC 2047.
417 */
418
419 int reformime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
420 int reformime_main(int argc UNUSED_PARAM, char **argv)
421 {
422         const char *opt_prefix = "";
423
424         INIT_G();
425
426         // parse options
427         // N.B. only -x and -X are supported so far
428         opt_complementary = "x--X:X--x" IF_FEATURE_REFORMIME_COMPAT(":m::");
429         opts = getopt32(argv,
430                 "x:X" IF_FEATURE_REFORMIME_COMPAT("deis:r:c:m:h:o:O:"),
431                 &opt_prefix
432                 IF_FEATURE_REFORMIME_COMPAT(, NULL, NULL, &G.opt_charset, NULL, NULL, NULL, NULL)
433         );
434         //argc -= optind;
435         argv += optind;
436
437         return parse("", (opts & OPT_X) ? argv : (char **)&opt_prefix);
438 }