1 /* vi: set sw=4 ts=4: */
3 * bare bones sendmail/fetchmail
5 * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
7 * Licensed under GPLv2, see file LICENSE in this tarball for details.
11 #define INITIAL_STDIN_FILENO 3
13 static void uuencode(char *fname, const char *text)
16 SRC_BUF_SIZE = 45, /* This *MUST* be a multiple of 3 */
17 DST_BUF_SIZE = 4 * ((SRC_BUF_SIZE + 2) / 3),
23 char dst_buf[DST_BUF_SIZE + 1];
26 fd = INITIAL_STDIN_FILENO;
27 if (NOT_LONE_DASH(fname))
28 fd = xopen(fname, O_RDONLY);
29 src_buf = bb_common_bufsiz1;
30 // N.B. strlen(NULL) segfaults!
32 // though we do not call uuencode(NULL, NULL) explicitly
33 // still we do not want to break things suddenly
38 fflush(stdout); // sync stdio and unistd output
42 size = full_read(fd, (char *)src_buf, SRC_BUF_SIZE);
43 if ((ssize_t)size < 0)
44 bb_perror_msg_and_die(bb_msg_read_error);
47 if (len > SRC_BUF_SIZE)
52 // encode the buffer we just read in
53 bb_uuencode(dst_buf, src_buf, size, bb_uuenc_tbl_base64);
55 xwrite(STDOUT_FILENO, "\r\n", 2);
60 xwrite(STDOUT_FILENO, dst_buf, 4 * ((size + 2) / 3));
66 static const char *const init_xargs[9] = {
67 "openssl", "s_client", "-quiet", "-connect",
68 NULL, "-tls1", "-starttls", "smtp"
74 // arguments for SSL connection helper
76 #if ENABLE_FEATURE_FETCHMAIL_FILTER
77 // arguments for postprocess helper
81 #define G (*ptr_to_globals)
82 #define helper_pid (G.helper_pid)
83 #define timeout (G.timeout )
84 #define xargs (G.xargs )
85 #define fargs (G.fargs )
86 #define INIT_G() do { \
87 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
88 memcpy(xargs, init_xargs, sizeof(init_xargs)); \
92 #define opt_connect (xargs[4])
93 #define opt_after_connect (xargs[5])
94 #if ENABLE_FEATURE_FETCHMAIL_FILTER
95 #define opt_charset (fargs[0])
96 #define opt_subject (fargs[1])
99 static void kill_helper(void)
101 // TODO!!!: is there more elegant way to terminate child on program failure?
103 kill(helper_pid, SIGTERM);
106 // generic signal handler
107 static void signal_handler(int signo)
111 if (SIGALRM == signo) {
113 bb_error_msg_and_die("timed out");
116 // SIGCHLD. reap zombies
117 if (wait_any_nohang(&err) > 0)
118 if (WIFEXITED(err) && WEXITSTATUS(err))
119 #if ENABLE_FEATURE_SENDMAIL_BLOATY
120 bb_error_msg_and_die("child exited (%d)", WEXITSTATUS(err));
122 bb_error_msg_and_die("child failed");
126 static void launch_helper(const char **argv)
128 // setup vanilla unidirectional pipes interchange
133 helper_pid = vfork();
135 bb_perror_msg_and_die("vfork");
136 idx = (!helper_pid)*2;
137 xdup2(pipes[idx], STDIN_FILENO);
138 xdup2(pipes[3-idx], STDOUT_FILENO);
139 if (ENABLE_FEATURE_CLEAN_UP)
140 for (int i = 4; --i >= 0; )
141 if (pipes[i] > STDOUT_FILENO)
144 // child - try to execute connection helper
145 // close(STDERR_FILENO);
146 BB_EXECVP(*argv, (char **)argv);
149 // parent - check whether child is alive
154 signal_handler(SIGCHLD);
155 // child seems OK -> parent goes on
158 static char *command(const char *fmt, const char *param)
160 char *msg = (char *)fmt;
164 msg = xasprintf(fmt, param);
165 printf("%s\r\n", msg);
171 static int smtp_checkp(const char *fmt, const char *param, int code)
174 char *msg = command(fmt, param);
176 // if the string has a form \d\d\d- -- read next string. E.g. EHLO response
177 // parse first bytes to a number
178 // if code = -1 then just return this number
179 // if code != -1 then checks whether the number equals the code
180 // if not equal -> die saying msg
181 #if ENABLE_FEATURE_SENDMAIL_EHLO
182 while ((answer = xmalloc_getline(stdin)) != NULL)
183 if (strlen(answer) <= 3 || '-' != answer[3])
186 answer = xmalloc_getline(stdin);
189 int n = atoi(answer);
191 if (ENABLE_FEATURE_CLEAN_UP) {
195 if (-1 == code || n == code) {
200 bb_error_msg_and_die("%s failed", msg);
203 static int smtp_check(const char *fmt, int code)
205 return smtp_checkp(fmt, NULL, code);
208 // strip argument of bad chars
209 static char *sane(char *str)
214 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
224 static void pop3_checkr(const char *fmt, const char *param, char **ret)
226 char *msg = command(fmt, param);
227 char *answer = xmalloc_getline(stdin);
228 if (answer && '+' == *answer) {
231 *ret = answer+4; // skip "+OK "
232 else if (ENABLE_FEATURE_CLEAN_UP)
237 bb_error_msg_and_die("%s failed", msg);
240 static void pop3_check(const char *fmt, const char *param)
242 pop3_checkr(fmt, param, NULL);
245 static void pop3_message(const char *filename)
249 // create and open file filename
250 // read stdin, copy to created file
251 fd = xopen(filename, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL);
252 while ((answer = xmalloc_fgets_str(stdin, "\r\n"))) {
254 if ('.' == *answer) {
255 if ('.' == answer[1])
257 else if ('\r' == answer[1] && '\n' == answer[2] && '\0' == answer[3])
260 xwrite(fd, s, strlen(s));
267 int sendgetmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
268 int sendgetmail_main(int argc, char **argv)
270 llist_t *opt_recipients = NULL;
271 #if !ENABLE_FEATURE_FETCHMAIL_FILTER
273 char *opt_charset = (char *)"utf-8";
276 const char *opt_user;
277 const char *opt_pass;
280 OPT_w = 1 << 0, // network timeout
281 OPT_U = 1 << 1, // user
282 OPT_P = 1 << 2, // password
283 OPT_X = 1 << 3, // connect using openssl s_client helper
285 OPTS_n = 1 << 4, // sendmail: request notification
286 OPTF_t = 1 << 4, // fetchmail: use "TOP" not "RETR"
288 OPTS_s = 1 << 5, // sendmail: subject
289 OPTF_z = 1 << 5, // fetchmail: delete from server
291 OPTS_c = 1 << 6, // sendmail: assumed charset
292 OPTS_t = 1 << 7, // sendmail: recipient(s)
300 if (!ENABLE_FETCHMAIL || 's' == applet_name[0]) {
302 // save initial stdin (body or attachements can be piped!)
303 xdup2(STDIN_FILENO, INITIAL_STDIN_FILENO);
304 opt_complementary = "-2:w+:t:t::"; // count(-t) > 0
305 options = "w:U:P:X" "ns:c:t:";
308 opt_after_connect = NULL;
309 opt_complementary = "-2:w+:P";
310 options = "w:U:P:X" "tz";
312 opts = getopt32(argv, options,
313 &timeout, &opt_user, &opt_pass,
314 &opt_subject, &opt_charset, &opt_recipients
320 // first argument is remote server[:port]
321 opt_connect = *argv++;
325 launch_helper(xargs);
327 // no connection helper provided -> make plain connect
328 int fd = create_and_connect_stream_or_die(opt_connect, 0);
329 xmove_fd(fd, STDIN_FILENO);
330 xdup2(STDIN_FILENO, STDOUT_FILENO);
334 if (opt_after_connect)
345 // wait for initial OK on plain connect
347 smtp_check(NULL, 220);
349 // get specified sender
350 opt_from = sane(*argv++);
352 // introduce to server
353 // should we respect modern (but useless here) EHLO?
354 // or should they respect we wanna be tiny?!
355 if (!ENABLE_FEATURE_SENDMAIL_EHLO || 250 != smtp_checkp("EHLO %s", opt_from, -1)) {
356 smtp_checkp("HELO %s", opt_from, 250);
360 // NOTE: if password has not been specified ->
361 // no authentication is possible
362 code = (opts & OPT_P) ? -1 : 250;
363 // first try softly without authentication
364 while (250 != smtp_checkp("MAIL FROM:<%s>", opt_from, code)) {
365 // MAIL FROM failed -> authentication needed
366 // do we have username?
367 if (!(opts & OPT_U)) {
368 // no! fetch it from "from" option
370 opt_user = xstrdup(opt_from);
371 *strchrnul(opt_user, '@') = '\0';
373 // now it seems we have username
374 // try to authenticate
375 if (334 == smtp_check("AUTH LOGIN", -1)) {
376 uuencode(NULL, opt_user);
378 uuencode(NULL, opt_pass);
381 // authenticated -> retry set sender
382 // but now die on failure
387 for (llist_t *to = opt_recipients; to; to = to->link) {
388 smtp_checkp("RCPT TO:<%s>", sane(to->data), 250);
392 smtp_check("DATA", 354);
393 // put address headers
394 printf("From: %s\r\n", opt_from);
395 for (llist_t *to = opt_recipients; to; to = to->link) {
396 printf("To: %s\r\n", to->data);
398 // put encoded subject
400 sane((char *)opt_charset);
402 printf("Subject: =?%s?B?", opt_charset);
403 uuencode(NULL, opt_subject);
408 printf("Disposition-Notification-To: %s\r\n", opt_from);
409 // put common headers and body start
411 #if ENABLE_FEATURE_SENDMAIL_BLOATY
414 boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());
416 USE_FEATURE_SENDMAIL_BLOATY("X-Mailer: busybox " BB_VER " sendmail\r\n")
417 "Message-ID: <%s>\r\n"
418 "Mime-Version: 1.0\r\n"
419 "%smultipart/mixed; boundary=\"%s\"\r\n"
424 // put body + attachment(s)
428 "%stext/plain; charset=%s\r\n"
440 , "Content-Disposition: inline"
442 , "Content-Transfer-Encoding: base64\r\n"
447 "%sapplication/octet-stream%s\r\n"
448 "%s; filename=\"%s\"\r\n"
451 uuencode(*argv, NULL);
453 q = bb_get_last_path_component_strip(*argv);
457 printf("\r\n--%s--\r\n" "\r\n", boundary);
458 if (ENABLE_FEATURE_CLEAN_UP)
461 // end message and say goodbye
462 smtp_check(".", 250);
463 smtp_check("QUIT", 221);
472 // cache fetch command
473 const char *retr = (opts & OPTF_t) ? "TOP %u 0" : "RETR %u";
478 #if ENABLE_FEATURE_FETCHMAIL_FILTER
479 // cache postprocess program
484 if (!(opts & OPT_U)) {
486 opt_user = getenv("USER");
488 #if ENABLE_FEATURE_FETCHMAIL_APOP
489 pop3_checkr(NULL, NULL, &buf);
490 // server supports APOP?
493 // yes. compose <stamp><password>
494 char *s = strchr(buf, '>');
496 strcpy(s+1, opt_pass);
498 // get md5 sum of <stamp><password>
500 md5_hash(s, strlen(s), &md5);
502 // NOTE: md5 struct contains enough space
503 // so we reuse md5 space instead of xzalloc(16*2+1)
504 #define md5_hex ((uint8_t *)&md5)
505 // uint8_t *md5_hex = (uint8_t *)&md5;
506 *bin2hex(md5_hex, s, 16) = '\0';
508 s = xasprintf("%s %s", opt_user, md5_hex);
510 pop3_check("APOP %s", s);
511 if (ENABLE_FEATURE_CLEAN_UP) {
513 free(buf-4); // buf is "+OK " away from malloc'ed string
518 pop3_check(NULL, NULL);
521 pop3_check("USER %s", opt_user);
523 pop3_check("PASS %s", opt_pass);
527 pop3_checkr("STAT", NULL, &buf);
529 // prepare message filename suffix
530 hostname = xzalloc(MAXHOSTNAMELEN+1);
531 gethostname(hostname, MAXHOSTNAMELEN);
534 // get number of messages
535 // NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"
536 // we only need nmsg and atoi is just exactly what we need
537 // if atoi fails to convert buf into number it returns 0
538 // in this case the following loop simply will not be executed
540 if (ENABLE_FEATURE_CLEAN_UP)
541 free(buf-4); // buf is "+OK " away from malloc'ed string
543 // loop through messages
544 for (; nmsg; nmsg--) {
545 char *filename = xasprintf("tmp/%llu.%u.%s", monotonic_us(), pid, hostname);
547 #if ENABLE_FEATURE_FETCHMAIL_FILTER
550 // retrieve message in ./tmp
551 pop3_check(retr, (const char *)nmsg);
552 pop3_message(filename);
553 // delete message from server
555 pop3_check("DELE %u", (const char*)nmsg);
557 #if ENABLE_FEATURE_FETCHMAIL_FILTER
558 // run postprocessing program
561 rc = wait4pid(spawn((char **)fargs));
568 // atomically move message to ./new
569 target = xstrdup(filename);
570 strncpy(target, "new", 3);
571 // ... or just stop receiving on error
572 if (rename_or_warn(filename, target))
575 #if ENABLE_FEATURE_FETCHMAIL_FILTER
581 if (ENABLE_FEATURE_CLEAN_UP)
585 pop3_check("QUIT", NULL);
586 #endif // ENABLE_FETCHMAIL