mime.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 tarball for details.
  9. */
  10. #include "libbb.h"
  11. #include "mail.h"
  12. /*
  13. makemime -c type [-o file] [-e encoding] [-C charset] [-N name] \
  14. [-a "Header: Contents"] file
  15. -m [ type ] [-o file] [-e encoding] [-a "Header: Contents"] file
  16. -j [-o file] file1 file2
  17. @file
  18. file: filename - read or write from filename
  19. - - read or write from stdin or stdout
  20. &n - read or write from file descriptor n
  21. \( opts \) - read from child process, that generates [ opts ]
  22. Options:
  23. -c type - create a new MIME section from "file" with this
  24. Content-Type: (default is application/octet-stream).
  25. -C charset - MIME charset of a new text/plain section.
  26. -N name - MIME content name of the new mime section.
  27. -m [ type ] - create a multipart mime section from "file" of this
  28. Content-Type: (default is multipart/mixed).
  29. -e encoding - use the given encoding (7bit, 8bit, quoted-printable,
  30. or base64), instead of guessing. Omit "-e" and use
  31. -c auto to set Content-Type: to text/plain or
  32. application/octet-stream based on picked encoding.
  33. -j file1 file2 - join mime section file2 to multipart section file1.
  34. -o file - write ther result to file, instead of stdout (not
  35. allowed in child processes).
  36. -a header - prepend an additional header to the output.
  37. @file - read all of the above options from file, one option or
  38. value on each line.
  39. */
  40. int makemime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  41. int makemime_main(int argc UNUSED_PARAM, char **argv)
  42. {
  43. llist_t *opt_headers = NULL, *l;
  44. const char *opt_output;
  45. #define boundary opt_output
  46. enum {
  47. OPT_c = 1 << 0, // Content-Type:
  48. OPT_e = 1 << 1, // Content-Transfer-Encoding. Ignored. Assumed base64
  49. OPT_o = 1 << 2, // output to
  50. OPT_C = 1 << 3, // charset
  51. OPT_N = 1 << 4, // COMPAT
  52. OPT_a = 1 << 5, // additional headers
  53. OPT_m = 1 << 6, // COMPAT
  54. OPT_j = 1 << 7, // COMPAT
  55. };
  56. INIT_G();
  57. // parse options
  58. opt_complementary = "a::";
  59. opts = getopt32(argv,
  60. "c:e:o:C:N:a:m:j:",
  61. &G.content_type, NULL, &opt_output, &G.opt_charset, NULL, &opt_headers, NULL, NULL
  62. );
  63. //argc -= optind;
  64. argv += optind;
  65. // respect -o output
  66. if (opts & OPT_o)
  67. freopen(opt_output, "w", stdout);
  68. // no files given on command line? -> use stdin
  69. if (!*argv)
  70. *--argv = (char *)"-";
  71. // put additional headers
  72. for (l = opt_headers; l; l = l->link)
  73. puts(l->data);
  74. // make a random string -- it will delimit message parts
  75. srand(monotonic_us());
  76. boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());
  77. // put multipart header
  78. printf(
  79. "Mime-Version: 1.0\n"
  80. "Content-Type: multipart/mixed; boundary=\"%s\"\n"
  81. , boundary
  82. );
  83. // put attachments
  84. while (*argv) {
  85. printf(
  86. "\n--%s\n"
  87. "Content-Type: %s; charset=%s\n"
  88. "Content-Disposition: inline; filename=\"%s\"\n"
  89. "Content-Transfer-Encoding: base64\n"
  90. , boundary
  91. , G.content_type
  92. , G.opt_charset
  93. , bb_get_last_path_component_strip(*argv)
  94. );
  95. encode_base64(*argv++, (const char *)stdin, "");
  96. }
  97. // put multipart footer
  98. printf("\n--%s--\n" "\n", boundary);
  99. return EXIT_SUCCESS;
  100. #undef boundary
  101. }
  102. static const char *find_token(const char *const string_array[], const char *key, const char *defvalue)
  103. {
  104. const char *r = NULL;
  105. for (int i = 0; string_array[i] != 0; i++) {
  106. if (strcasecmp(string_array[i], key) == 0) {
  107. r = (char *)string_array[i+1];
  108. break;
  109. }
  110. }
  111. return (r) ? r : defvalue;
  112. }
  113. static const char *xfind_token(const char *const string_array[], const char *key)
  114. {
  115. const char *r = find_token(string_array, key, NULL);
  116. if (r)
  117. return r;
  118. bb_error_msg_and_die("header: %s", key);
  119. }
  120. enum {
  121. OPT_x = 1 << 0,
  122. OPT_X = 1 << 1,
  123. #if ENABLE_FEATURE_REFORMIME_COMPAT
  124. OPT_d = 1 << 2,
  125. OPT_e = 1 << 3,
  126. OPT_i = 1 << 4,
  127. OPT_s = 1 << 5,
  128. OPT_r = 1 << 6,
  129. OPT_c = 1 << 7,
  130. OPT_m = 1 << 8,
  131. OPT_h = 1 << 9,
  132. OPT_o = 1 << 10,
  133. OPT_O = 1 << 11,
  134. #endif
  135. };
  136. static int parse(const char *boundary, char **argv)
  137. {
  138. char *line, *s, *p;
  139. const char *type;
  140. int boundary_len = strlen(boundary);
  141. const char *delims = " ;\"\t\r\n";
  142. const char *uniq;
  143. int ntokens;
  144. const char *tokens[32]; // 32 is enough
  145. // prepare unique string pattern
  146. uniq = xasprintf("%%llu.%u.%s", (unsigned)getpid(), safe_gethostname());
  147. //bb_info_msg("PARSE[%s]", terminator);
  148. while ((line = xmalloc_fgets_str(stdin, "\r\n\r\n")) != NULL) {
  149. // seek to start of MIME section
  150. // N.B. to avoid false positives let us seek to the _last_ occurance
  151. p = NULL;
  152. s = line;
  153. while ((s=strcasestr(s, "Content-Type:")) != NULL)
  154. p = s++;
  155. if (!p)
  156. goto next;
  157. //bb_info_msg("L[%s]", p);
  158. // split to tokens
  159. // TODO: strip of comments which are of form: (comment-text)
  160. ntokens = 0;
  161. tokens[ntokens] = NULL;
  162. for (s = strtok(p, delims); s; s = strtok(NULL, delims)) {
  163. tokens[ntokens] = s;
  164. if (ntokens < ARRAY_SIZE(tokens) - 1)
  165. ntokens++;
  166. //bb_info_msg("L[%d][%s]", ntokens, s);
  167. }
  168. tokens[ntokens] = NULL;
  169. //bb_info_msg("N[%d]", ntokens);
  170. // analyse tokens
  171. type = find_token(tokens, "Content-Type:", "text/plain");
  172. //bb_info_msg("T[%s]", type);
  173. if (0 == strncasecmp(type, "multipart/", 10)) {
  174. if (0 == strcasecmp(type+10, "mixed")) {
  175. parse(xfind_token(tokens, "boundary="), argv);
  176. } else
  177. bb_error_msg_and_die("no support of content type '%s'", type);
  178. } else {
  179. pid_t pid = pid;
  180. int rc;
  181. FILE *fp;
  182. // fetch charset
  183. const char *charset = find_token(tokens, "charset=", CONFIG_FEATURE_MIME_CHARSET);
  184. // fetch encoding
  185. const char *encoding = find_token(tokens, "Content-Transfer-Encoding:", "7bit");
  186. // compose target filename
  187. char *filename = (char *)find_token(tokens, "filename=", NULL);
  188. if (!filename)
  189. filename = xasprintf(uniq, monotonic_us());
  190. else
  191. filename = bb_get_last_path_component_strip(xstrdup(filename));
  192. // start external helper, if any
  193. if (opts & OPT_X) {
  194. int fd[2];
  195. xpipe(fd);
  196. pid = vfork();
  197. if (0 == pid) {
  198. // child reads from fd[0]
  199. xdup2(fd[0], STDIN_FILENO);
  200. close(fd[0]); close(fd[1]);
  201. xsetenv("CONTENT_TYPE", type);
  202. xsetenv("CHARSET", charset);
  203. xsetenv("ENCODING", encoding);
  204. xsetenv("FILENAME", filename);
  205. BB_EXECVP(*argv, argv);
  206. _exit(EXIT_FAILURE);
  207. }
  208. // parent dumps to fd[1]
  209. close(fd[0]);
  210. fp = fdopen(fd[1], "w");
  211. signal(SIGPIPE, SIG_IGN); // ignore EPIPE
  212. // or create a file for dump
  213. } else {
  214. char *fname = xasprintf("%s%s", *argv, filename);
  215. fp = xfopen_for_write(fname);
  216. free(fname);
  217. }
  218. // housekeeping
  219. free(filename);
  220. // dump to fp
  221. if (0 == strcasecmp(encoding, "base64")) {
  222. decode_base64(stdin, fp);
  223. } else if (0 != strcasecmp(encoding, "7bit")
  224. && 0 != strcasecmp(encoding, "8bit")) {
  225. // quoted-printable, binary, user-defined are unsupported so far
  226. bb_error_msg_and_die("no support of encoding '%s'", encoding);
  227. } else {
  228. // N.B. we have written redundant \n. so truncate the file
  229. // The following weird 2-tacts reading technique is due to
  230. // we have to not write extra \n at the end of the file
  231. // In case of -x option we could truncate the resulting file as
  232. // fseek(fp, -1, SEEK_END);
  233. // if (ftruncate(fileno(fp), ftell(fp)))
  234. // bb_perror_msg("ftruncate");
  235. // But in case of -X we have to be much more careful. There is
  236. // no means to truncate what we already have sent to the helper.
  237. p = xmalloc_fgets_str(stdin, "\r\n");
  238. while (p) {
  239. if ((s = xmalloc_fgets_str(stdin, "\r\n")) == NULL)
  240. break;
  241. if ('-' == s[0] && '-' == s[1]
  242. && 0 == strncmp(s+2, boundary, boundary_len))
  243. break;
  244. fputs(p, fp);
  245. p = s;
  246. }
  247. /*
  248. while ((s = xmalloc_fgetline_str(stdin, "\r\n")) != NULL) {
  249. if ('-' == s[0] && '-' == s[1]
  250. && 0 == strncmp(s+2, boundary, boundary_len))
  251. break;
  252. fprintf(fp, "%s\n", s);
  253. }
  254. // N.B. we have written redundant \n. so truncate the file
  255. fseek(fp, -1, SEEK_END);
  256. if (ftruncate(fileno(fp), ftell(fp)))
  257. bb_perror_msg("ftruncate");
  258. */
  259. }
  260. fclose(fp);
  261. // finalize helper
  262. if (opts & OPT_X) {
  263. signal(SIGPIPE, SIG_DFL);
  264. // exit if helper exited >0
  265. rc = wait4pid(pid);
  266. if (rc)
  267. return rc+20;
  268. }
  269. // check multipart finalized
  270. if (s && '-' == s[2+boundary_len] && '-' == s[2+boundary_len+1]) {
  271. free(line);
  272. break;
  273. }
  274. }
  275. next:
  276. free(line);
  277. }
  278. //bb_info_msg("ENDPARSE[%s]", boundary);
  279. return EXIT_SUCCESS;
  280. }
  281. /*
  282. Usage: reformime [options]
  283. -d - parse a delivery status notification.
  284. -e - extract contents of MIME section.
  285. -x - extract MIME section to a file.
  286. -X - pipe MIME section to a program.
  287. -i - show MIME info.
  288. -s n.n.n.n - specify MIME section.
  289. -r - rewrite message, filling in missing MIME headers.
  290. -r7 - also convert 8bit/raw encoding to quoted-printable, if possible.
  291. -r8 - also convert quoted-printable encoding to 8bit, if possible.
  292. -c charset - default charset for rewriting, -o, and -O.
  293. -m [file] [file]... - create a MIME message digest.
  294. -h "header" - decode RFC 2047-encoded header.
  295. -o "header" - encode unstructured header using RFC 2047.
  296. -O "header" - encode address list header using RFC 2047.
  297. */
  298. int reformime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  299. int reformime_main(int argc UNUSED_PARAM, char **argv)
  300. {
  301. const char *opt_prefix = "";
  302. INIT_G();
  303. // parse options
  304. // N.B. only -x and -X are supported so far
  305. opt_complementary = "x--X:X--x" USE_FEATURE_REFORMIME_COMPAT(":m::");
  306. opts = getopt32(argv,
  307. "x:X" USE_FEATURE_REFORMIME_COMPAT("deis:r:c:m:h:o:O:"),
  308. &opt_prefix
  309. USE_FEATURE_REFORMIME_COMPAT(, NULL, NULL, &G.opt_charset, NULL, NULL, NULL, NULL)
  310. );
  311. //argc -= optind;
  312. argv += optind;
  313. return parse("", (opts & OPT_X) ? argv : (char **)&opt_prefix);
  314. }