3
0

popmaildir.c 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * popmaildir: a simple yet powerful POP3 client
  4. * Delivers contents of remote mailboxes to local Maildir
  5. *
  6. * Inspired by original utility by Nikola Vladov
  7. *
  8. * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
  9. *
  10. * Licensed under GPLv2, see file LICENSE in this source tree.
  11. */
  12. //config:config POPMAILDIR
  13. //config: bool "popmaildir (11 kb)"
  14. //config: default y
  15. //config: help
  16. //config: Simple yet powerful POP3 mail popper. Delivers content
  17. //config: of remote mailboxes to local Maildir.
  18. //config:
  19. //config:config FEATURE_POPMAILDIR_DELIVERY
  20. //config: bool "Allow message filters and custom delivery program"
  21. //config: default y
  22. //config: depends on POPMAILDIR
  23. //config: help
  24. //config: Allow to use a custom program to filter the content
  25. //config: of the message before actual delivery (-F "prog [args...]").
  26. //config: Allow to use a custom program for message actual delivery
  27. //config: (-M "prog [args...]").
  28. //applet:IF_POPMAILDIR(APPLET(popmaildir, BB_DIR_USR_SBIN, BB_SUID_DROP))
  29. //kbuild:lib-$(CONFIG_POPMAILDIR) += popmaildir.o mail.o
  30. //usage:#define popmaildir_trivial_usage
  31. //usage: "[OPTIONS] MAILDIR [CONN_HELPER ARGS]"
  32. //usage:#define popmaildir_full_usage "\n\n"
  33. //usage: "Fetch content of remote mailbox to local maildir\n"
  34. /* //usage: "\n -b Binary mode. Ignored" */
  35. /* //usage: "\n -d Debug. Ignored" */
  36. /* //usage: "\n -m Show used memory. Ignored" */
  37. /* //usage: "\n -V Show version. Ignored" */
  38. /* //usage: "\n -c Use tcpclient. Ignored" */
  39. /* //usage: "\n -a Use APOP protocol. Implied. If server supports APOP -> use it" */
  40. //usage: "\n -s Skip authorization"
  41. //usage: "\n -T Get messages with TOP instead of RETR"
  42. //usage: "\n -k Keep retrieved messages on the server"
  43. //usage: "\n -t SEC Network timeout"
  44. //usage: IF_FEATURE_POPMAILDIR_DELIVERY(
  45. //usage: "\n -F 'PROG ARGS' Filter program (may be repeated)"
  46. //usage: "\n -M 'PROG ARGS' Delivery program"
  47. //usage: )
  48. //usage: "\n"
  49. //usage: "\nFetch from plain POP3 server:"
  50. //usage: "\npopmaildir -k DIR nc pop3.server.com 110 <user_and_pass.txt"
  51. //usage: "\nFetch from SSLed POP3 server and delete fetched emails:"
  52. //usage: "\npopmaildir DIR -- openssl s_client -quiet -connect pop3.server.com:995 <user_and_pass.txt"
  53. /* //usage: "\n -R BYTES Remove old messages on the server >= BYTES. Ignored" */
  54. /* //usage: "\n -Z N1-N2 Remove messages from N1 to N2 (dangerous). Ignored" */
  55. /* //usage: "\n -L BYTES Don't retrieve new messages >= BYTES. Ignored" */
  56. /* //usage: "\n -H LINES Type first LINES of a message. Ignored" */
  57. //usage:
  58. //usage:#define popmaildir_example_usage
  59. //usage: "$ popmaildir -k ~/Maildir -- nc pop.drvv.ru 110 [<password_file]\n"
  60. //usage: "$ popmaildir ~/Maildir -- openssl s_client -quiet -connect pop.gmail.com:995 [<password_file]\n"
  61. #include "libbb.h"
  62. #include "mail.h"
  63. static void pop3_checkr(const char *fmt, const char *param, char **ret)
  64. {
  65. char *msg = send_mail_command(fmt, param);
  66. //FIXME: limit max len!!!
  67. char *answer = xmalloc_fgetline(stdin);
  68. if (answer && '+' == answer[0]) {
  69. free(msg);
  70. if (G.timeout)
  71. alarm(0);
  72. if (ret) {
  73. // skip "+OK "
  74. memmove(answer, answer + 4, strlen(answer) - 4);
  75. *ret = answer;
  76. } else
  77. free(answer);
  78. return;
  79. }
  80. bb_error_msg_and_die("%s failed, reply was: %s", msg, answer);
  81. }
  82. static void pop3_check(const char *fmt, const char *param)
  83. {
  84. pop3_checkr(fmt, param, NULL);
  85. }
  86. int popmaildir_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  87. int popmaildir_main(int argc UNUSED_PARAM, char **argv)
  88. {
  89. unsigned opts;
  90. char *buf;
  91. unsigned nmsg;
  92. char *hostname;
  93. pid_t pid;
  94. const char *retr;
  95. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  96. const char *delivery;
  97. #endif
  98. unsigned opt_nlines = 0;
  99. enum {
  100. OPT_b = 1 << 0, // -b binary mode. Ignored
  101. OPT_d = 1 << 1, // -d,-dd,-ddd debug. Ignored
  102. OPT_m = 1 << 2, // -m show used memory. Ignored
  103. OPT_V = 1 << 3, // -V version. Ignored
  104. OPT_c = 1 << 4, // -c use tcpclient. Ignored
  105. OPT_a = 1 << 5, // -a use APOP protocol
  106. OPT_s = 1 << 6, // -s skip authorization
  107. OPT_T = 1 << 7, // -T get messages with TOP instead with RETR
  108. OPT_k = 1 << 8, // -k keep retrieved messages on the server
  109. OPT_t = 1 << 9, // -t90 set timeout to 90 sec
  110. OPT_R = 1 << 10, // -R20000 remove old messages on the server >= 20000 bytes (requires -k). Ignored
  111. OPT_Z = 1 << 11, // -Z11-23 remove messages from 11 to 23 (dangerous). Ignored
  112. OPT_L = 1 << 12, // -L50000 not retrieve new messages >= 50000 bytes. Ignored
  113. OPT_H = 1 << 13, // -H30 type first 30 lines of a message; (-L12000 -H30). Ignored
  114. OPT_M = 1 << 14, // -M\"program arg1 arg2 ...\"; deliver by program. Treated like -F
  115. OPT_F = 1 << 15, // -F\"program arg1 arg2 ...\"; filter by program. Treated like -M
  116. };
  117. // init global variables
  118. INIT_G();
  119. // parse options
  120. opts = getopt32(argv, "^"
  121. "bdmVcasTkt:+" "R:+Z:L:+H:+" IF_FEATURE_POPMAILDIR_DELIVERY("M:F:")
  122. "\0" "-1:dd",
  123. &G.timeout, NULL, NULL, NULL, &opt_nlines
  124. IF_FEATURE_POPMAILDIR_DELIVERY(, &delivery, &delivery) // we treat -M and -F the same
  125. );
  126. //argc -= optind;
  127. argv += optind;
  128. // get auth info
  129. if (!(opts & OPT_s))
  130. get_cred_or_die(STDIN_FILENO);
  131. // goto maildir
  132. xchdir(*argv++);
  133. // launch connect helper, if any
  134. if (*argv)
  135. launch_helper((const char **)argv);
  136. // get server greeting
  137. pop3_checkr(NULL, NULL, &buf);
  138. // authenticate (if no -s given)
  139. if (!(opts & OPT_s)) {
  140. // server supports APOP and we want it?
  141. if ('<' == buf[0] && (opts & OPT_a)) {
  142. union { // save a bit of stack
  143. md5_ctx_t ctx;
  144. char hex[16 * 2 + 1];
  145. } md5;
  146. uint32_t res[MD5_OUTSIZE / 4];
  147. char *s = strchr(buf, '>');
  148. if (s)
  149. s[1] = '\0';
  150. // get md5 sum of "<stamp>password" string
  151. md5_begin(&md5.ctx);
  152. md5_hash(&md5.ctx, buf, strlen(buf));
  153. md5_hash(&md5.ctx, G.pass, strlen(G.pass));
  154. md5_end(&md5.ctx, res);
  155. *bin2hex(md5.hex, (char*)res, 16) = '\0';
  156. // APOP
  157. s = xasprintf("%s %s", G.user, md5.hex);
  158. pop3_check("APOP %s", s);
  159. free(s);
  160. free(buf);
  161. // server ignores APOP -> use simple text authentication
  162. } else {
  163. // USER
  164. pop3_check("USER %s", G.user);
  165. // PASS
  166. pop3_check("PASS %s", G.pass);
  167. }
  168. }
  169. // get mailbox statistics
  170. pop3_checkr("STAT", NULL, &buf);
  171. // prepare message filename suffix
  172. hostname = safe_gethostname();
  173. pid = getpid();
  174. // get messages counter
  175. // NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"
  176. // we only need nmsg and atoi is just exactly what we need
  177. // if atoi fails to convert buf into number it returns 0
  178. // in this case the following loop simply will not be executed
  179. nmsg = atoi(buf);
  180. free(buf);
  181. // loop through messages
  182. retr = (opts & OPT_T) ? xasprintf("TOP %%u %u", opt_nlines) : "RETR %u";
  183. for (; nmsg; nmsg--) {
  184. char *filename;
  185. char *target;
  186. char *answer;
  187. FILE *fp;
  188. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  189. int rc;
  190. #endif
  191. // generate unique filename
  192. filename = xasprintf("tmp/%llu.%u.%s",
  193. monotonic_us(), (unsigned)pid, hostname);
  194. // retrieve message in ./tmp/ unless filter is specified
  195. pop3_check(retr, (const char *)(ptrdiff_t)nmsg);
  196. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  197. // delivery helper ordered? -> setup pipe
  198. if (opts & (OPT_F|OPT_M)) {
  199. // helper will have $FILENAME set to filename
  200. xsetenv("FILENAME", filename);
  201. fp = popen(delivery, "w");
  202. unsetenv("FILENAME");
  203. if (!fp) {
  204. bb_simple_perror_msg("delivery helper");
  205. break;
  206. }
  207. } else
  208. #endif
  209. // create and open file filename
  210. fp = xfopen_for_write(filename);
  211. // copy stdin to fp (either filename or delivery helper)
  212. while ((answer = xmalloc_fgets_str(stdin, "\r\n")) != NULL) {
  213. char *s = answer;
  214. if ('.' == answer[0]) {
  215. if ('.' == answer[1])
  216. s++;
  217. else if ('\r' == answer[1] && '\n' == answer[2] && '\0' == answer[3])
  218. break;
  219. }
  220. //*strchrnul(s, '\r') = '\n';
  221. fputs(s, fp);
  222. free(answer);
  223. }
  224. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  225. // analyse delivery status
  226. if (opts & (OPT_F|OPT_M)) {
  227. rc = pclose(fp);
  228. if (99 == rc) // 99 means bail out
  229. break;
  230. // if (rc) // !0 means skip to the next message
  231. goto skip;
  232. // // 0 means continue
  233. } else {
  234. // close filename
  235. fclose(fp);
  236. }
  237. #endif
  238. // delete message from server
  239. if (!(opts & OPT_k))
  240. pop3_check("DELE %u", (const char*)(ptrdiff_t)nmsg);
  241. // atomically move message to ./new/
  242. target = xstrdup(filename);
  243. memcpy(target, "new", 3);
  244. // ... or just stop receiving on failure
  245. if (rename_or_warn(filename, target))
  246. break;
  247. free(target);
  248. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  249. skip:
  250. #endif
  251. free(filename);
  252. }
  253. // Bye
  254. pop3_check("QUIT", NULL);
  255. if (ENABLE_FEATURE_CLEAN_UP) {
  256. free(G.user);
  257. free(G.pass);
  258. }
  259. return EXIT_SUCCESS;
  260. }