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