popmaildir.c 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 (10 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. char *answer = xmalloc_fgetline(stdin);
  67. if (answer && '+' == answer[0]) {
  68. free(msg);
  69. if (timeout)
  70. alarm(0);
  71. if (ret) {
  72. // skip "+OK "
  73. memmove(answer, answer + 4, strlen(answer) - 4);
  74. *ret = answer;
  75. } else
  76. free(answer);
  77. return;
  78. }
  79. bb_error_msg_and_die("%s failed, reply was: %s", msg, answer);
  80. }
  81. static void pop3_check(const char *fmt, const char *param)
  82. {
  83. pop3_checkr(fmt, param, NULL);
  84. }
  85. int popmaildir_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  86. int popmaildir_main(int argc UNUSED_PARAM, char **argv)
  87. {
  88. char *buf;
  89. unsigned nmsg;
  90. char *hostname;
  91. pid_t pid;
  92. const char *retr;
  93. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  94. const char *delivery;
  95. #endif
  96. unsigned opt_nlines = 0;
  97. enum {
  98. OPT_b = 1 << 0, // -b binary mode. Ignored
  99. OPT_d = 1 << 1, // -d,-dd,-ddd debug. Ignored
  100. OPT_m = 1 << 2, // -m show used memory. Ignored
  101. OPT_V = 1 << 3, // -V version. Ignored
  102. OPT_c = 1 << 4, // -c use tcpclient. Ignored
  103. OPT_a = 1 << 5, // -a use APOP protocol
  104. OPT_s = 1 << 6, // -s skip authorization
  105. OPT_T = 1 << 7, // -T get messages with TOP instead with RETR
  106. OPT_k = 1 << 8, // -k keep retrieved messages on the server
  107. OPT_t = 1 << 9, // -t90 set timeout to 90 sec
  108. OPT_R = 1 << 10, // -R20000 remove old messages on the server >= 20000 bytes (requires -k). Ignored
  109. OPT_Z = 1 << 11, // -Z11-23 remove messages from 11 to 23 (dangerous). Ignored
  110. OPT_L = 1 << 12, // -L50000 not retrieve new messages >= 50000 bytes. Ignored
  111. OPT_H = 1 << 13, // -H30 type first 30 lines of a message; (-L12000 -H30). Ignored
  112. OPT_M = 1 << 14, // -M\"program arg1 arg2 ...\"; deliver by program. Treated like -F
  113. OPT_F = 1 << 15, // -F\"program arg1 arg2 ...\"; filter by program. Treated like -M
  114. };
  115. // init global variables
  116. INIT_G();
  117. // parse options
  118. opts = getopt32(argv, "^"
  119. "bdmVcasTkt:+" "R:+Z:L:+H:+" IF_FEATURE_POPMAILDIR_DELIVERY("M:F:")
  120. "\0" "-1:dd",
  121. &timeout, NULL, NULL, NULL, &opt_nlines
  122. IF_FEATURE_POPMAILDIR_DELIVERY(, &delivery, &delivery) // we treat -M and -F the same
  123. );
  124. //argc -= optind;
  125. argv += optind;
  126. // get auth info
  127. if (!(opts & OPT_s))
  128. get_cred_or_die(STDIN_FILENO);
  129. // goto maildir
  130. xchdir(*argv++);
  131. // launch connect helper, if any
  132. if (*argv)
  133. launch_helper((const char **)argv);
  134. // get server greeting
  135. pop3_checkr(NULL, NULL, &buf);
  136. // authenticate (if no -s given)
  137. if (!(opts & OPT_s)) {
  138. // server supports APOP and we want it?
  139. if ('<' == buf[0] && (opts & OPT_a)) {
  140. union { // save a bit of stack
  141. md5_ctx_t ctx;
  142. char hex[16 * 2 + 1];
  143. } md5;
  144. uint32_t res[16 / 4];
  145. char *s = strchr(buf, '>');
  146. if (s)
  147. s[1] = '\0';
  148. // get md5 sum of "<stamp>password" string
  149. md5_begin(&md5.ctx);
  150. md5_hash(&md5.ctx, buf, strlen(buf));
  151. md5_hash(&md5.ctx, G.pass, strlen(G.pass));
  152. md5_end(&md5.ctx, res);
  153. *bin2hex(md5.hex, (char*)res, 16) = '\0';
  154. // APOP
  155. s = xasprintf("%s %s", G.user, md5.hex);
  156. pop3_check("APOP %s", s);
  157. free(s);
  158. free(buf);
  159. // server ignores APOP -> use simple text authentication
  160. } else {
  161. // USER
  162. pop3_check("USER %s", G.user);
  163. // PASS
  164. pop3_check("PASS %s", G.pass);
  165. }
  166. }
  167. // get mailbox statistics
  168. pop3_checkr("STAT", NULL, &buf);
  169. // prepare message filename suffix
  170. hostname = safe_gethostname();
  171. pid = getpid();
  172. // get messages counter
  173. // NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"
  174. // we only need nmsg and atoi is just exactly what we need
  175. // if atoi fails to convert buf into number it returns 0
  176. // in this case the following loop simply will not be executed
  177. nmsg = atoi(buf);
  178. free(buf);
  179. // loop through messages
  180. retr = (opts & OPT_T) ? xasprintf("TOP %%u %u", opt_nlines) : "RETR %u";
  181. for (; nmsg; nmsg--) {
  182. char *filename;
  183. char *target;
  184. char *answer;
  185. FILE *fp;
  186. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  187. int rc;
  188. #endif
  189. // generate unique filename
  190. filename = xasprintf("tmp/%llu.%u.%s",
  191. monotonic_us(), (unsigned)pid, hostname);
  192. // retrieve message in ./tmp/ unless filter is specified
  193. pop3_check(retr, (const char *)(ptrdiff_t)nmsg);
  194. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  195. // delivery helper ordered? -> setup pipe
  196. if (opts & (OPT_F|OPT_M)) {
  197. // helper will have $FILENAME set to filename
  198. xsetenv("FILENAME", filename);
  199. fp = popen(delivery, "w");
  200. unsetenv("FILENAME");
  201. if (!fp) {
  202. bb_perror_msg("delivery helper");
  203. break;
  204. }
  205. } else
  206. #endif
  207. // create and open file filename
  208. fp = xfopen_for_write(filename);
  209. // copy stdin to fp (either filename or delivery helper)
  210. while ((answer = xmalloc_fgets_str(stdin, "\r\n")) != NULL) {
  211. char *s = answer;
  212. if ('.' == answer[0]) {
  213. if ('.' == answer[1])
  214. s++;
  215. else if ('\r' == answer[1] && '\n' == answer[2] && '\0' == answer[3])
  216. break;
  217. }
  218. //*strchrnul(s, '\r') = '\n';
  219. fputs(s, fp);
  220. free(answer);
  221. }
  222. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  223. // analyse delivery status
  224. if (opts & (OPT_F|OPT_M)) {
  225. rc = pclose(fp);
  226. if (99 == rc) // 99 means bail out
  227. break;
  228. // if (rc) // !0 means skip to the next message
  229. goto skip;
  230. // // 0 means continue
  231. } else {
  232. // close filename
  233. fclose(fp);
  234. }
  235. #endif
  236. // delete message from server
  237. if (!(opts & OPT_k))
  238. pop3_check("DELE %u", (const char*)(ptrdiff_t)nmsg);
  239. // atomically move message to ./new/
  240. target = xstrdup(filename);
  241. memcpy(target, "new", 3);
  242. // ... or just stop receiving on failure
  243. if (rename_or_warn(filename, target))
  244. break;
  245. free(target);
  246. #if ENABLE_FEATURE_POPMAILDIR_DELIVERY
  247. skip:
  248. #endif
  249. free(filename);
  250. }
  251. // Bye
  252. pop3_check("QUIT", NULL);
  253. if (ENABLE_FEATURE_CLEAN_UP) {
  254. free(G.user);
  255. free(G.pass);
  256. }
  257. return EXIT_SUCCESS;
  258. }