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