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