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));
71 // arguments for SSL connection helper
73 // arguments for postprocess helper
76 #define G (*ptr_to_globals)
77 #define helper_pid (G.helper_pid)
78 #define timeout (G.timeout )
79 #define xargs (G.xargs )
80 #define fargs (G.fargs )
81 #define INIT_G() do { \
82 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
83 xargs[0] = "openssl"; \
84 xargs[1] = "s_client"; \
85 xargs[2] = "-quiet"; \
86 xargs[3] = "-connect"; \
87 /*xargs[4] = "localhost";*/ \
89 xargs[6] = "-starttls"; \
94 #define opt_connect (xargs[4])
95 #define opt_after_connect (xargs[5])
96 #define opt_charset (fargs[0])
97 #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 bb_error_msg_and_die("child exited (%d)", WEXITSTATUS(err));
123 static void launch_helper(const char **argv)
125 // setup vanilla unidirectional pipes interchange
131 helper_pid = vfork();
133 bb_perror_msg_and_die("vfork");
134 idx = (!helper_pid) * 2;
135 xdup2(pipes[idx], STDIN_FILENO);
136 xdup2(pipes[3-idx], STDOUT_FILENO);
137 if (ENABLE_FEATURE_CLEAN_UP)
138 for (int i = 4; --i >= 0; )
139 if (pipes[i] > STDOUT_FILENO)
142 // child: try to execute connection helper
143 BB_EXECVP(*argv, (char **)argv);
146 // parent: check whether child is alive
151 signal_handler(SIGCHLD);
152 // child seems OK -> parent goes on
155 static const char *command(const char *fmt, const char *param)
157 const char *msg = fmt;
160 msg = xasprintf(fmt, param);
161 printf("%s\r\n", msg);
167 static int smtp_checkp(const char *fmt, const char *param, int code)
170 const char *msg = command(fmt, param);
172 // if the string has a form \d\d\d- -- read next string. E.g. EHLO response
173 // parse first bytes to a number
174 // if code = -1 then just return this number
175 // if code != -1 then checks whether the number equals the code
176 // if not equal -> die saying msg
177 while ((answer = xmalloc_fgetline(stdin)) != NULL)
178 if (strlen(answer) <= 3 || '-' != answer[3])
181 int n = atoi(answer);
183 if (ENABLE_FEATURE_CLEAN_UP) {
186 if (-1 == code || n == code) {
191 bb_error_msg_and_die("%s failed", msg);
194 static inline int smtp_check(const char *fmt, int code)
196 return smtp_checkp(fmt, NULL, code);
199 // strip argument of bad chars
200 static char *sane(char *str)
205 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
215 static void pop3_checkr(const char *fmt, const char *param, char **ret)
217 const char *msg = command(fmt, param);
218 char *answer = xmalloc_fgetline(stdin);
219 if (answer && '+' == *answer) {
222 *ret = answer+4; // skip "+OK "
223 else if (ENABLE_FEATURE_CLEAN_UP)
228 bb_error_msg_and_die("%s failed", msg);
231 static inline void pop3_check(const char *fmt, const char *param)
233 pop3_checkr(fmt, param, NULL);
236 static void pop3_message(const char *filename)
240 // create and open file filename
241 // read stdin, copy to created file
242 fd = xopen(filename, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL);
243 while ((answer = xmalloc_fgets_str(stdin, "\r\n")) != NULL) {
245 if ('.' == *answer) {
246 if ('.' == answer[1])
248 else if ('\r' == answer[1] && '\n' == answer[2] && '\0' == answer[3])
251 xwrite(fd, s, strlen(s));
258 static char *parse_url(char *url, char **user, char **pass)
260 // parse [user[:pass]@]host
262 char *s = strchr(url, '@');
263 *user = *pass = NULL;
268 s = strchr(*user, ':');
277 static void rcptto(const char *s)
279 smtp_checkp("RCPT TO:<%s>", s, 250);
282 int sendgetmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
283 int sendgetmail_main(int argc UNUSED_PARAM, char **argv)
285 llist_t *opt_attachments = NULL;
290 OPT_w = 1 << 0, // network timeout
291 OPT_H = 1 << 1, // [user:password@]server[:port]
292 OPT_S = 1 << 2, // connect using openssl s_client helper
294 OPTS_t = 1 << 3, // sendmail: read addresses from body
295 OPTF_t = 1 << 3, // fetchmail: use "TOP" not "RETR"
297 OPTS_s = 1 << 4, // sendmail: subject
298 OPTF_z = 1 << 4, // fetchmail: delete from server
300 OPTS_c = 1 << 5, // sendmail: assumed charset
301 OPTS_a = 1 << 6, // sendmail: attachment(s)
302 OPTS_i = 1 << 7, // sendmail: ignore lone dots in message body (implied)
304 OPTS_N = 1 << 8, // sendmail: request notification
305 OPTS_f = 1 << 9, // sendmail: sender address
310 // init global variables
313 // parse options, different option sets for sendmail and fetchmail
314 // N.B. opt_after_connect hereafter is NULL if we are called as fetchmail
315 // and is NOT NULL if we are called as sendmail
316 if (!ENABLE_FETCHMAIL || 's' == applet_name[0]) {
318 // save initial stdin since body is piped!
319 xdup2(STDIN_FILENO, INITIAL_STDIN_FILENO);
320 opt_complementary = "w+:a::";
321 options = "w:H:St" "s:c:a:iN:f:";
322 // body is pseudo attachment read from stdin
323 llist_add_to_end(&opt_attachments, (char *)"-");
326 opt_after_connect = NULL;
327 opt_complementary = "-1:w+";
328 options = "w:H:St" "z";
330 opts = getopt32(argv, options,
331 &timeout /* -w */, &opt_connect /* -H */,
332 &opt_subject, &opt_charset, &opt_attachments, NULL, &opt_from
338 // host[:port] not specified ? -> use $HOSTNAME. no $HOSTNAME ? -> use localhost
339 if (!(opts & OPT_H)) {
340 opt_connect = getenv("HOSTNAME");
342 opt_connect = "127.0.0.1";
344 // fetch username and password, if any
345 // NB: parse_url modifies opt_connect[] ONLY if '@' is there.
346 // Thus "127.0.0.1" won't be modified, an is ok that it is RO.
347 opt_connect = parse_url((char*)opt_connect, &opt_user, &opt_pass);
348 // bb_error_msg("H[%s] U[%s] P[%s]", opt_connect, opt_user, opt_pass);
350 // username must be defined!
352 // N.B. IMHO getenv("USER") can be way easily spoofed!
353 opt_user = bb_getpwuid(NULL, -1, getuid());
358 // ... use openssl helper
359 launch_helper(xargs);
360 // no SSL ordered? ->
362 // ... make plain connect
363 int fd = create_and_connect_stream_or_die(opt_connect, 25);
364 // make ourselves a simple IO filter
365 // from now we know nothing about network :)
366 xmove_fd(fd, STDIN_FILENO);
367 xdup2(STDIN_FILENO, STDOUT_FILENO);
371 if (!ENABLE_FETCHMAIL || opt_after_connect)
372 /***************************************************
374 ***************************************************/
382 llist_t *headers = NULL;
384 // got no sender address? -> use username as a resort
385 if (!(opts & OPTS_f)) {
386 char *domain = safe_getdomainname();
387 opt_from = xasprintf("%s@%s", opt_user, domain);
388 if (ENABLE_FEATURE_CLEAN_UP)
392 // introduce to server
394 // we didn't use SSL helper? ->
395 if (!(opts & OPT_S)) {
396 // ... wait for initial server OK
397 smtp_check(NULL, 220);
400 // we should start with modern EHLO
401 if (250 != smtp_checkp("EHLO %s", sane(opt_from), -1)) {
402 smtp_checkp("HELO %s", opt_from, 250);
406 // NOTE: if password has not been specified
407 // then no authentication is possible
408 code = (opt_pass) ? -1 : 250;
409 // first try softly without authentication
410 while (250 != smtp_checkp("MAIL FROM:<%s>", opt_from, code)) {
411 // MAIL FROM failed -> authentication needed
412 if (334 == smtp_check("AUTH LOGIN", -1)) {
413 uuencode(NULL, opt_user); // opt_user != NULL
415 uuencode(NULL, opt_pass);
418 // authenticated OK? -> retry to set sender
419 // but this time die on failure!
423 // recipients specified as arguments
425 // loose test on email address validity
426 if (strchr(sane(*argv), '@')) {
428 llist_add_to_end(&headers, xasprintf("To: %s", *argv));
433 // if -t specified or no recipients specified -> enter all-included mode
434 // i.e. scan stdin for To:, Cc:, Bcc:, and Subject: lines ...
435 // ... and then use the rest of stdin as message body
436 // N.B. subject read from body has priority
437 // over that specified on command line.
438 // recipients are merged
439 // N.B. other headers are collected and will be dumped verbatim
440 if (opts & OPTS_t || !headers) {
441 // fetch recipients and (optionally) subject
443 while ((s = xmalloc_reads(INITIAL_STDIN_FILENO, NULL, NULL)) != NULL) {
444 if (0 == strncasecmp("To: ", s, 4) || 0 == strncasecmp("Cc: ", s, 4)) {
446 llist_add_to_end(&headers, s);
447 } else if (0 == strncasecmp("Bcc: ", s, 5)) {
449 if (ENABLE_FEATURE_CLEAN_UP)
451 // N.B. Bcc vanishes from headers!
452 /* } else if (0 == strncmp("From: ", s, 6)) {
455 */ } else if (0 == strncmp("Subject: ", s, 9)) {
460 llist_add_to_end(&headers, s);
468 // enter "put message" mode
469 smtp_check("DATA", 354);
471 // put headers we could have preread with -t
472 for (l = headers; l; l = l->link) {
473 printf("%s\r\n", l->data);
474 if (ENABLE_FEATURE_CLEAN_UP)
478 // put address header
479 printf("From: %s\r\n", opt_from);
481 // put encoded subject
483 sane((char *)opt_charset);
485 printf("Subject: =?%s?B?", opt_charset);
486 uuencode(NULL, opt_subject);
492 printf("Disposition-Notification-To: %s\r\n", opt_from);
494 // make a random string -- it will delimit message parts
495 srand(monotonic_us());
496 boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());
498 // put common headers and body start
500 "Message-ID: <%s>\r\n"
501 "Mime-Version: 1.0\r\n"
502 "%smultipart/mixed; boundary=\"%s\"\r\n"
508 // put body + attachment(s)
509 // N.B. all these weird things just to be tiny
510 // by reusing string patterns!
513 "%stext/plain; charset=%s\r\n"
526 , "Content-Disposition: inline"
528 , "Content-Transfer-Encoding: base64\r\n"
533 "%sapplication/octet-stream%s\r\n"
534 "%s; filename=\"%s\"\r\n"
537 uuencode(l->data, NULL);
540 q = bb_get_last_path_component_strip(l->data);
543 // put message terminator
544 printf("\r\n--%s--\r\n" "\r\n", boundary);
546 // leave "put message" mode
547 smtp_check(".", 250);
548 // ... and say goodbye
549 smtp_check("QUIT", 221);
552 /***************************************************
554 ***************************************************/
561 // cache fetch command:
562 // TOP will return only the headers
563 // RETR will dump the whole message
564 const char *retr = (opts & OPTF_t) ? "TOP %u 0" : "RETR %u";
569 // cache postprocess program
574 // password is mandatory
576 bb_error_msg_and_die("no password");
579 // get server greeting
580 pop3_checkr(NULL, NULL, &buf);
582 // server supports APOP?
585 // yes! compose <stamp><password>
586 char *s = strchr(buf, '>');
588 strcpy(s+1, opt_pass);
590 // get md5 sum of <stamp><password>
592 md5_hash(s, strlen(s), &md5);
594 // NOTE: md5 struct contains enough space
595 // so we reuse md5 space instead of xzalloc(16*2+1)
596 #define md5_hex ((uint8_t *)&md5)
597 // uint8_t *md5_hex = (uint8_t *)&md5;
598 *bin2hex((char *)md5_hex, s, 16) = '\0';
600 s = xasprintf("%s %s", opt_user, md5_hex);
602 pop3_check("APOP %s", s);
603 if (ENABLE_FEATURE_CLEAN_UP) {
605 free(buf-4); // buf is "+OK " away from malloc'ed string
607 // server ignores APOP -> use simple text authentication
610 pop3_check("USER %s", opt_user);
612 pop3_check("PASS %s", opt_pass);
615 // get mailbox statistics
616 pop3_checkr("STAT", NULL, &buf);
618 // prepare message filename suffix
619 hostname = safe_gethostname();
622 // get messages counter
623 // NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"
624 // we only need nmsg and atoi is just exactly what we need
625 // if atoi fails to convert buf into number it returns 0
626 // in this case the following loop simply will not be executed
628 if (ENABLE_FEATURE_CLEAN_UP)
629 free(buf-4); // buf is "+OK " away from malloc'ed string
631 // loop through messages
632 for (; nmsg; nmsg--) {
634 // generate unique filename
635 char *filename = xasprintf("tmp/%llu.%u.%s",
636 monotonic_us(), (unsigned)pid, hostname);
640 // retrieve message in ./tmp/
641 pop3_check(retr, (const char *)(ptrdiff_t)nmsg);
642 pop3_message(filename);
643 // delete message from server
645 pop3_check("DELE %u", (const char*)(ptrdiff_t)nmsg);
647 // run postprocessing program
650 rc = wait4pid(spawn((char **)fargs));
657 // atomically move message to ./new/
658 target = xstrdup(filename);
659 strncpy(target, "new", 3);
660 // ... or just stop receiving on error
661 if (rename_or_warn(filename, target))
669 pop3_check("QUIT", NULL);
671 #endif // ENABLE_FETCHMAIL