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