1 /* vi: set sw=4 ts=4: */
3 * makemime: create MIME-encoded message
4 * reformime: parse MIME-encoded message
6 * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
8 * Licensed under GPLv2, see file LICENSE in this source tree.
11 //usage:#define makemime_trivial_usage
12 //usage: "[OPTIONS] [FILE]..."
13 //usage:#define makemime_full_usage "\n\n"
14 //usage: "Create multipart MIME-encoded message from FILEs\n"
15 /* //usage: "Transfer encoding is base64, disposition is inline (not attachment)\n" */
17 //usage: "\n -o FILE Output. Default: stdout"
18 //usage: "\n -a HDR Add header. Examples:"
19 //usage: "\n \"From: user@host.org\", \"Date: `date -R`\""
20 //usage: "\n -c CT Content type. Default: text/plain"
21 //usage: "\n -C CS Charset. Default: " CONFIG_FEATURE_MIME_CHARSET
22 /* //usage: "\n -e ENC Transfer encoding. Ignored. base64 is assumed" */
24 //usage: "\nOther options are silently ignored"
26 //usage:#define reformime_trivial_usage
27 //usage: "[OPTIONS] [FILE]..."
28 //usage:#define reformime_full_usage "\n\n"
29 //usage: "Parse MIME-encoded message\n"
31 //usage: "\n -x PREFIX Extract content of MIME sections to files"
32 //usage: "\n -X PROG ARGS Filter content of MIME sections through PROG"
33 //usage: "\n Must be the last option"
35 //usage: "\nOther options are silently ignored"
41 makemime -c type [-o file] [-e encoding] [-C charset] [-N name] \
42 [-a "Header: Contents"] file
43 -m [ type ] [-o file] [-e encoding] [-a "Header: Contents"] file
44 -j [-o file] file1 file2
47 file: filename - read or write from filename
48 - - read or write from stdin or stdout
49 &n - read or write from file descriptor n
50 \( opts \) - read from child process, that generates [ opts ]
54 -c type - create a new MIME section from "file" with this
55 Content-Type: (default is application/octet-stream).
56 -C charset - MIME charset of a new text/plain section.
57 -N name - MIME content name of the new mime section.
58 -m [ type ] - create a multipart mime section from "file" of this
59 Content-Type: (default is multipart/mixed).
60 -e encoding - use the given encoding (7bit, 8bit, quoted-printable,
61 or base64), instead of guessing. Omit "-e" and use
62 -c auto to set Content-Type: to text/plain or
63 application/octet-stream based on picked encoding.
64 -j file1 file2 - join mime section file2 to multipart section file1.
65 -o file - write the result to file, instead of stdout (not
66 allowed in child processes).
67 -a header - prepend an additional header to the output.
69 @file - read all of the above options from file, one option or
71 {which version of makemime is this? What do we support?}
75 /* In busybox 1.15.0.svn, makemime generates output like this
76 * (empty lines are shown exactly!):
77 {headers added with -a HDR}
79 Content-Type: multipart/mixed; boundary="24269534-2145583448-1655890676"
81 --24269534-2145583448-1655890676
82 Content-Type: {set by -c, e.g. text/plain}; charset={set by -C, e.g. us-ascii}
83 Content-Disposition: inline; filename="A"
84 Content-Transfer-Encoding: base64
87 --24269534-2145583448-1655890676
88 Content-Type: {set by -c, e.g. text/plain}; charset={set by -C, e.g. us-ascii}
89 Content-Disposition: inline; filename="B"
90 Content-Transfer-Encoding: base64
93 --24269534-2145583448-1655890676--
98 /* For reference: here is an example email to LKML which has
99 * 1st unnamed part (so it serves as an email body)
100 * and one attached file:
102 Content-Type: multipart/mixed; boundary="=-tOfTf3byOS0vZgxEWcX+"
108 --=-tOfTf3byOS0vZgxEWcX+
109 Content-Type: text/plain
110 Content-Transfer-Encoding: 7bit
116 --=-tOfTf3byOS0vZgxEWcX+
117 Content-Disposition: attachment; filename="xyz"
118 Content-Type: text/plain; name="xyz"; charset="UTF-8"
119 Content-Transfer-Encoding: 7bit
124 --=-tOfTf3byOS0vZgxEWcX+--
126 ...random junk added by mailing list robots and such...
131 * -c TYPE: create a (non-multipart) MIME section with Content-Type: TYPE
132 * makemime -c TYPE [-e ENCODING] [-o OUTFILE] [-C CHARSET] [-N NAME] [-a HEADER...] FILE
133 * The -C option sets the MIME charset attribute for text/plain content.
134 * The -N option sets the name attribute for Content-Type:
135 * Encoding must be one of the following: 7bit, 8bit, quoted-printable, or base64.
137 * -m multipart/TYPE: create a multipart MIME collection with Content-Type: multipart/TYPE
138 * makemime -m multipart/TYPE [-e ENCODING] [-o OUTFILE] [-a HEADER...] FILE
139 * Type must be either "multipart/mixed", "multipart/alternative", or some other MIME multipart content type.
140 * Additionally, encoding can only be "7bit" or "8bit", and will default to "8bit" if not specified.
141 * Finally, filename must be a MIME-formatted section, NOT a regular file.
142 * The -m option creates an initial multipart MIME collection, that contains only one MIME section, taken from filename.
143 * The collection is written to standard output, or the pipe or to outputfile.
145 * -j FILE1: add a section to a multipart MIME collection
146 * makemime -j FILE1 [-o OUTFILE] FILE2
147 * FILE1 must be a MIME collection that was previously created by the -m option.
148 * FILE2 must be a MIME section that was previously created by the -c option.
149 * The -j options adds the MIME section in FILE2 to the MIME collection in FILE1.
151 int makemime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
152 int makemime_main(int argc UNUSED_PARAM, char **argv)
154 llist_t *opt_headers = NULL, *l;
155 const char *opt_output;
156 #define boundary opt_output
159 OPT_c = 1 << 0, // create (non-multipart) section
160 OPT_e = 1 << 1, // Content-Transfer-Encoding. Ignored. Assumed base64
161 OPT_o = 1 << 2, // output to
162 OPT_C = 1 << 3, // charset
163 OPT_N = 1 << 4, // COMPAT
164 OPT_a = 1 << 5, // additional headers
165 //OPT_m = 1 << 6, // create mutipart section
166 //OPT_j = 1 << 7, // join section to multipart section
172 opt_complementary = "a::";
173 opts = getopt32(argv,
174 "c:e:o:C:N:a", //:m:j:",
175 &G.content_type, NULL, &opt_output, &G.opt_charset, NULL, &opt_headers //, NULL, NULL
182 freopen(opt_output, "w", stdout);
184 // no files given on command line? -> use stdin
186 *--argv = (char *)"-";
188 // put additional headers
189 for (l = opt_headers; l; l = l->link)
192 // make a random string -- it will delimit message parts
193 srand(monotonic_us());
194 boundary = xasprintf("%u-%u-%u",
195 (unsigned)rand(), (unsigned)rand(), (unsigned)rand());
197 // put multipart header
199 "Mime-Version: 1.0\n"
200 "Content-Type: multipart/mixed; boundary=\"%s\"\n"
208 "Content-Type: %s; charset=%s\n"
209 "Content-Disposition: inline; filename=\"%s\"\n"
210 "Content-Transfer-Encoding: base64\n"
214 , bb_get_last_path_component_strip(*argv)
216 encode_base64(*argv++, (const char *)stdin, "");
219 // put multipart footer
220 printf("\n--%s--\n" "\n", boundary);
226 static const char *find_token(const char *const string_array[], const char *key, const char *defvalue)
228 const char *r = NULL;
230 for (i = 0; string_array[i] != NULL; i++) {
231 if (strcasecmp(string_array[i], key) == 0) {
232 r = (char *)string_array[i+1];
236 return (r) ? r : defvalue;
239 static const char *xfind_token(const char *const string_array[], const char *key)
241 const char *r = find_token(string_array, key, NULL);
244 bb_error_msg_and_die("header: %s", key);
250 #if ENABLE_FEATURE_REFORMIME_COMPAT
264 static int parse(const char *boundary, char **argv)
268 int boundary_len = strlen(boundary);
269 const char *delims = " ;\"\t\r\n";
272 const char *tokens[32]; // 32 is enough
274 // prepare unique string pattern
275 uniq = xasprintf("%%llu.%u.%s", (unsigned)getpid(), safe_gethostname());
277 //bb_info_msg("PARSE[%s]", uniq);
279 while ((line = xmalloc_fgets_str(stdin, "\r\n\r\n")) != NULL) {
281 // seek to start of MIME section
282 // N.B. to avoid false positives let us seek to the _last_ occurance
285 while ((s = strcasestr(s, "Content-Type:")) != NULL)
289 //bb_info_msg("L[%s]", p);
292 // TODO: strip of comments which are of form: (comment-text)
294 tokens[ntokens] = NULL;
295 for (s = strtok(p, delims); s; s = strtok(NULL, delims)) {
297 if (ntokens < ARRAY_SIZE(tokens) - 1)
299 //bb_info_msg("L[%d][%s]", ntokens, s);
301 tokens[ntokens] = NULL;
302 //bb_info_msg("N[%d]", ntokens);
305 type = find_token(tokens, "Content-Type:", "text/plain");
306 //bb_info_msg("T[%s]", type);
307 if (0 == strncasecmp(type, "multipart/", 10)) {
308 if (0 == strcasecmp(type+10, "mixed")) {
309 parse(xfind_token(tokens, "boundary="), argv);
311 bb_error_msg_and_die("no support of content type '%s'", type);
317 const char *charset = find_token(tokens, "charset=", CONFIG_FEATURE_MIME_CHARSET);
319 const char *encoding = find_token(tokens, "Content-Transfer-Encoding:", "7bit");
320 // compose target filename
321 char *filename = (char *)find_token(tokens, "filename=", NULL);
323 filename = xasprintf(uniq, monotonic_us());
325 filename = bb_get_last_path_component_strip(xstrdup(filename));
327 // start external helper, if any
333 // child reads from fd[0]
335 xmove_fd(fd[0], STDIN_FILENO);
336 xsetenv("CONTENT_TYPE", type);
337 xsetenv("CHARSET", charset);
338 xsetenv("ENCODING", encoding);
339 xsetenv("FILENAME", filename);
340 BB_EXECVP_or_die(argv);
342 // parent dumps to fd[1]
344 fp = xfdopen_for_write(fd[1]);
345 signal(SIGPIPE, SIG_IGN); // ignore EPIPE
346 // or create a file for dump
348 char *fname = xasprintf("%s%s", *argv, filename);
349 fp = xfopen_for_write(fname);
357 if (0 == strcasecmp(encoding, "base64")) {
358 read_base64(stdin, fp, '-');
359 } else if (0 != strcasecmp(encoding, "7bit")
360 && 0 != strcasecmp(encoding, "8bit")
362 // quoted-printable, binary, user-defined are unsupported so far
363 bb_error_msg_and_die("no support of encoding '%s'", encoding);
365 // N.B. we have written redundant \n. so truncate the file
366 // The following weird 2-tacts reading technique is due to
367 // we have to not write extra \n at the end of the file
368 // In case of -x option we could truncate the resulting file as
369 // fseek(fp, -1, SEEK_END);
370 // if (ftruncate(fileno(fp), ftell(fp)))
371 // bb_perror_msg("ftruncate");
372 // But in case of -X we have to be much more careful. There is
373 // no means to truncate what we already have sent to the helper.
374 p = xmalloc_fgets_str(stdin, "\r\n");
376 s = xmalloc_fgets_str(stdin, "\r\n");
381 && 0 == strncmp(s+2, boundary, boundary_len)
390 while ((s = xmalloc_fgetline_str(stdin, "\r\n")) != NULL) {
391 if ('-' == s[0] && '-' == s[1]
392 && 0 == strncmp(s+2, boundary, boundary_len))
394 fprintf(fp, "%s\n", s);
396 // N.B. we have written redundant \n. so truncate the file
397 fseek(fp, -1, SEEK_END);
398 if (ftruncate(fileno(fp), ftell(fp)))
399 bb_perror_msg("ftruncate");
406 signal(SIGPIPE, SIG_DFL);
407 // exit if helper exited >0
408 rc = (wait4pid(pid) & 0xff);
413 // check multipart finalized
414 if (s && '-' == s[2+boundary_len] && '-' == s[2+boundary_len+1]) {
423 //bb_info_msg("ENDPARSE[%s]", boundary);
429 Usage: reformime [options]
430 -d - parse a delivery status notification.
431 -e - extract contents of MIME section.
432 -x - extract MIME section to a file.
433 -X - pipe MIME section to a program.
435 -s n.n.n.n - specify MIME section.
436 -r - rewrite message, filling in missing MIME headers.
437 -r7 - also convert 8bit/raw encoding to quoted-printable, if possible.
438 -r8 - also convert quoted-printable encoding to 8bit, if possible.
439 -c charset - default charset for rewriting, -o, and -O.
440 -m [file] [file]... - create a MIME message digest.
441 -h "header" - decode RFC 2047-encoded header.
442 -o "header" - encode unstructured header using RFC 2047.
443 -O "header" - encode address list header using RFC 2047.
446 int reformime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
447 int reformime_main(int argc UNUSED_PARAM, char **argv)
449 const char *opt_prefix = "";
454 // N.B. only -x and -X are supported so far
455 opt_complementary = "x--X:X--x" IF_FEATURE_REFORMIME_COMPAT(":m::");
456 opts = getopt32(argv,
457 "x:X" IF_FEATURE_REFORMIME_COMPAT("deis:r:c:m:h:o:O:"),
459 IF_FEATURE_REFORMIME_COMPAT(, NULL, NULL, &G.opt_charset, NULL, NULL, NULL, NULL)
464 return parse("", (opts & OPT_X) ? argv : (char **)&opt_prefix);