reformime.c 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * reformime: parse MIME-encoded message
  4. *
  5. * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. //config:config REFORMIME
  10. //config: bool "reformime (7.5 kb)"
  11. //config: default y
  12. //config: help
  13. //config: Parse MIME-formatted messages.
  14. //config:
  15. //config:config FEATURE_REFORMIME_COMPAT
  16. //config: bool "Accept and ignore options other than -x and -X"
  17. //config: default y
  18. //config: depends on REFORMIME
  19. //config: help
  20. //config: Accept (for compatibility only) and ignore options
  21. //config: other than -x and -X.
  22. //applet:IF_REFORMIME(APPLET(reformime, BB_DIR_BIN, BB_SUID_DROP))
  23. //kbuild:lib-$(CONFIG_REFORMIME) += reformime.o mail.o
  24. #include "libbb.h"
  25. #include "mail.h"
  26. #if 0
  27. # define dbg_error_msg(...) bb_error_msg(__VA_ARGS__)
  28. #else
  29. # define dbg_error_msg(...) ((void)0)
  30. #endif
  31. static const char *find_token(const char *const string_array[], const char *key, const char *defvalue)
  32. {
  33. const char *r = NULL;
  34. int i;
  35. for (i = 0; string_array[i] != NULL; i++) {
  36. if (strcasecmp(string_array[i], key) == 0) {
  37. r = (char *)string_array[i+1];
  38. break;
  39. }
  40. }
  41. return (r) ? r : defvalue;
  42. }
  43. static const char *xfind_token(const char *const string_array[], const char *key)
  44. {
  45. const char *r = find_token(string_array, key, NULL);
  46. if (r)
  47. return r;
  48. bb_error_msg_and_die("not found: '%s'", key);
  49. }
  50. enum {
  51. OPT_x = 1 << 0,
  52. OPT_X = 1 << 1,
  53. #if ENABLE_FEATURE_REFORMIME_COMPAT
  54. OPT_d = 1 << 2,
  55. OPT_e = 1 << 3,
  56. OPT_i = 1 << 4,
  57. OPT_s = 1 << 5,
  58. OPT_r = 1 << 6,
  59. OPT_c = 1 << 7,
  60. OPT_m = 1 << 8,
  61. OPT_h = 1 << 9,
  62. OPT_o = 1 << 10,
  63. OPT_O = 1 << 11,
  64. #endif
  65. };
  66. static int parse(const char *boundary, char **argv)
  67. {
  68. int boundary_len = strlen(boundary);
  69. char uniq[sizeof("%%llu.%u") + sizeof(int)*3];
  70. dbg_error_msg("BOUNDARY[%s]", boundary);
  71. // prepare unique string pattern
  72. sprintf(uniq, "%%llu.%u", (unsigned)getpid());
  73. dbg_error_msg("UNIQ[%s]", uniq);
  74. while (1) {
  75. char *header;
  76. const char *tokens[32]; /* 32 is enough */
  77. const char *type;
  78. /* Read the header (everything up to two \n) */
  79. {
  80. unsigned header_idx = 0;
  81. int last_ch = 0;
  82. header = NULL;
  83. while (1) {
  84. int ch = fgetc(stdin);
  85. if (ch == '\r') /* Support both line endings */
  86. continue;
  87. if (ch == EOF)
  88. break;
  89. if (ch == '\n' && last_ch == ch)
  90. break;
  91. if (!(header_idx & 0xff))
  92. header = xrealloc(header, header_idx + 0x101);
  93. header[header_idx++] = last_ch = ch;
  94. }
  95. if (!header) {
  96. dbg_error_msg("EOF");
  97. break;
  98. }
  99. header[header_idx] = '\0';
  100. dbg_error_msg("H:'%s'", p);
  101. }
  102. /* Split to tokens */
  103. {
  104. char *s, *p;
  105. unsigned ntokens;
  106. const char *delims = ";=\" \t\n";
  107. /* Skip to last Content-Type: */
  108. s = p = header;
  109. while ((p = strchr(p, '\n')) != NULL) {
  110. p++;
  111. if (strncasecmp(p, "Content-Type:", sizeof("Content-Type:")-1) == 0)
  112. s = p;
  113. }
  114. dbg_error_msg("L:'%s'", p);
  115. ntokens = 0;
  116. s = strtok(s, delims);
  117. while (s) {
  118. tokens[ntokens] = s;
  119. if (ntokens < ARRAY_SIZE(tokens) - 1)
  120. ntokens++;
  121. dbg_error_msg("L[%d]='%s'", ntokens, s);
  122. s = strtok(NULL, delims);
  123. }
  124. tokens[ntokens] = NULL;
  125. dbg_error_msg("EMPTYLINE, ntokens:%d", ntokens);
  126. if (ntokens == 0)
  127. break;
  128. }
  129. /* Is it multipart? */
  130. type = find_token(tokens, "Content-Type:", "text/plain");
  131. dbg_error_msg("TYPE:'%s'", type);
  132. if (0 == strncasecmp(type, "multipart/", 10)) {
  133. /* Yes, recurse */
  134. if (strcasecmp(type + 10, "mixed") != 0)
  135. bb_error_msg_and_die("no support of content type '%s'", type);
  136. parse(xfind_token(tokens, "boundary"), argv);
  137. } else {
  138. /* No, process one non-multipart section */
  139. char *end;
  140. pid_t pid = pid;
  141. FILE *fp;
  142. const char *charset = find_token(tokens, "charset", CONFIG_FEATURE_MIME_CHARSET);
  143. const char *encoding = find_token(tokens, "Content-Transfer-Encoding:", "7bit");
  144. /* Compose target filename */
  145. char *filename = (char *)find_token(tokens, "filename", NULL);
  146. if (!filename)
  147. filename = xasprintf(uniq, monotonic_us());
  148. else
  149. filename = bb_get_last_path_component_strip(xstrdup(filename));
  150. if (opts & OPT_X) {
  151. int fd[2];
  152. /* start external helper */
  153. xpipe(fd);
  154. pid = vfork();
  155. if (0 == pid) {
  156. /* child reads from fd[0] */
  157. close(fd[1]);
  158. xmove_fd(fd[0], STDIN_FILENO);
  159. xsetenv("CONTENT_TYPE", type);
  160. xsetenv("CHARSET", charset);
  161. xsetenv("ENCODING", encoding);
  162. xsetenv("FILENAME", filename);
  163. BB_EXECVP_or_die(argv);
  164. }
  165. /* parent will write to fd[1] */
  166. close(fd[0]);
  167. fp = xfdopen_for_write(fd[1]);
  168. signal(SIGPIPE, SIG_IGN);
  169. } else {
  170. /* write to file */
  171. char *fname = xasprintf("%s%s", *argv, filename);
  172. fp = xfopen_for_write(fname);
  173. free(fname);
  174. }
  175. free(filename);
  176. /* write to fp */
  177. end = NULL;
  178. if (0 == strcasecmp(encoding, "base64")) {
  179. read_base64(stdin, fp, '-');
  180. } else
  181. if (0 != strcasecmp(encoding, "7bit")
  182. && 0 != strcasecmp(encoding, "8bit")
  183. ) {
  184. /* quoted-printable, binary, user-defined are unsupported so far */
  185. bb_error_msg_and_die("encoding '%s' not supported", encoding);
  186. } else {
  187. /* plain 7bit or 8bit */
  188. while ((end = xmalloc_fgets(stdin)) != NULL) {
  189. if ('-' == end[0]
  190. && '-' == end[1]
  191. && strncmp(end + 2, boundary, boundary_len) == 0
  192. ) {
  193. break;
  194. }
  195. fputs(end, fp);
  196. }
  197. }
  198. fclose(fp);
  199. /* Wait for child */
  200. if (opts & OPT_X) {
  201. int rc;
  202. signal(SIGPIPE, SIG_DFL);
  203. rc = (wait4pid(pid) & 0xff);
  204. if (rc != 0)
  205. return rc + 20;
  206. }
  207. /* Multipart ended? */
  208. if (end && '-' == end[2 + boundary_len] && '-' == end[2 + boundary_len + 1]) {
  209. dbg_error_msg("FINISHED MPART:'%s'", end);
  210. break;
  211. }
  212. dbg_error_msg("FINISHED:'%s'", end);
  213. free(end);
  214. } /* end of "handle one non-multipart block" */
  215. free(header);
  216. } /* while (1) */
  217. dbg_error_msg("ENDPARSE[%s]", boundary);
  218. return EXIT_SUCCESS;
  219. }
  220. //usage:#define reformime_trivial_usage
  221. //usage: "[OPTIONS]"
  222. //usage:#define reformime_full_usage "\n\n"
  223. //usage: "Parse MIME-encoded message on stdin\n"
  224. //usage: "\n -x PREFIX Extract content of MIME sections to files"
  225. //usage: "\n -X PROG ARGS Filter content of MIME sections through PROG"
  226. //usage: "\n Must be the last option"
  227. //usage: "\n"
  228. //usage: "\nOther options are silently ignored"
  229. /*
  230. Usage: reformime [options]
  231. -d - parse a delivery status notification.
  232. -e - extract contents of MIME section.
  233. -x - extract MIME section to a file.
  234. -X - pipe MIME section to a program.
  235. -i - show MIME info.
  236. -s n.n.n.n - specify MIME section.
  237. -r - rewrite message, filling in missing MIME headers.
  238. -r7 - also convert 8bit/raw encoding to quoted-printable, if possible.
  239. -r8 - also convert quoted-printable encoding to 8bit, if possible.
  240. -c charset - default charset for rewriting, -o, and -O.
  241. -m [file] [file]... - create a MIME message digest.
  242. -h "header" - decode RFC 2047-encoded header.
  243. -o "header" - encode unstructured header using RFC 2047.
  244. -O "header" - encode address list header using RFC 2047.
  245. */
  246. int reformime_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  247. int reformime_main(int argc UNUSED_PARAM, char **argv)
  248. {
  249. const char *opt_prefix = "";
  250. INIT_G();
  251. // parse options
  252. // N.B. only -x and -X are supported so far
  253. opts = getopt32(argv, "^"
  254. "x:X" IF_FEATURE_REFORMIME_COMPAT("deis:r:c:m:*h:o:O:")
  255. "\0" "x--X:X--x",
  256. &opt_prefix
  257. IF_FEATURE_REFORMIME_COMPAT(, NULL, NULL, &G.opt_charset, NULL, NULL, NULL, NULL)
  258. );
  259. argv += optind;
  260. return parse("", (opts & OPT_X) ? argv : (char **)&opt_prefix);
  261. }