3
0

reformime.c 7.1 KB

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