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));
69 // arguments for SSL connection helper
71 // arguments for postprocess helper
74 #define G (*ptr_to_globals)
75 #define helper_pid (G.helper_pid)
76 #define timeout (G.timeout )
77 #define xargs (G.xargs )
78 #define fargs (G.fargs )
79 #define INIT_G() do { \
80 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
81 xargs[0] = "openssl"; \
82 xargs[1] = "s_client"; \
83 xargs[2] = "-quiet"; \
84 xargs[3] = "-connect"; \
85 /*xargs[4] = "server[:port]";*/ \
87 xargs[6] = "-starttls"; \
92 #define opt_connect (xargs[4])
93 #define opt_after_connect (xargs[5])
94 #define opt_charset (fargs[0])
95 #define opt_subject (fargs[1])
97 static void kill_helper(void)
99 // TODO!!!: is there more elegant way to terminate child on program failure?
101 kill(helper_pid, SIGTERM);
104 // generic signal handler
105 static void signal_handler(int signo)
109 if (SIGALRM == signo) {
111 bb_error_msg_and_die("timed out");
114 // SIGCHLD. reap zombies
115 if (wait_any_nohang(&err) > 0)
116 if (WIFEXITED(err) && WEXITSTATUS(err))
117 bb_error_msg_and_die("child exited (%d)", WEXITSTATUS(err));
120 static void launch_helper(const char **argv)
122 // setup vanilla unidirectional pipes interchange
127 helper_pid = vfork();
129 bb_perror_msg_and_die("vfork");
130 idx = (!helper_pid)*2;
131 xdup2(pipes[idx], STDIN_FILENO);
132 xdup2(pipes[3-idx], STDOUT_FILENO);
133 if (ENABLE_FEATURE_CLEAN_UP)
134 for (int i = 4; --i >= 0; )
135 if (pipes[i] > STDOUT_FILENO)
138 // child: try to execute connection helper
139 BB_EXECVP(*argv, (char **)argv);
142 // parent: check whether child is alive
147 signal_handler(SIGCHLD);
148 // child seems OK -> parent goes on
151 static const char *command(const char *fmt, const char *param)
153 const char *msg = fmt;
156 msg = xasprintf(fmt, param);
157 printf("%s\r\n", msg);
163 static int smtp_checkp(const char *fmt, const char *param, int code)
166 const char *msg = command(fmt, param);
168 // if the string has a form \d\d\d- -- read next string. E.g. EHLO response
169 // parse first bytes to a number
170 // if code = -1 then just return this number
171 // if code != -1 then checks whether the number equals the code
172 // if not equal -> die saying msg
173 while ((answer = xmalloc_fgetline(stdin)) != NULL)
174 if (strlen(answer) <= 3 || '-' != answer[3])
177 int n = atoi(answer);
179 if (ENABLE_FEATURE_CLEAN_UP) {
182 if (-1 == code || n == code) {
187 bb_error_msg_and_die("%s failed", msg);
190 static int inline smtp_check(const char *fmt, int code)
192 return smtp_checkp(fmt, NULL, code);
195 // strip argument of bad chars
196 static char *sane(char *str)
201 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
211 static void pop3_checkr(const char *fmt, const char *param, char **ret)
213 const char *msg = command(fmt, param);
214 char *answer = xmalloc_fgetline(stdin);
215 if (answer && '+' == *answer) {
218 *ret = answer+4; // skip "+OK "
219 else if (ENABLE_FEATURE_CLEAN_UP)
224 bb_error_msg_and_die("%s failed", msg);
227 static void inline pop3_check(const char *fmt, const char *param)
229 pop3_checkr(fmt, param, NULL);
232 static void pop3_message(const char *filename)
236 // create and open file filename
237 // read stdin, copy to created file
238 fd = xopen(filename, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL);
239 while ((answer = xmalloc_fgets_str(stdin, "\r\n")) != NULL) {
241 if ('.' == *answer) {
242 if ('.' == answer[1])
244 else if ('\r' == answer[1] && '\n' == answer[2] && '\0' == answer[3])
247 xwrite(fd, s, strlen(s));
254 int sendgetmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
255 int sendgetmail_main(int argc ATTRIBUTE_UNUSED, char **argv)
257 llist_t *opt_recipients = NULL;
259 const char *opt_user;
260 const char *opt_pass;
263 OPT_w = 1 << 0, // network timeout
264 OPT_U = 1 << 1, // user
265 OPT_P = 1 << 2, // password
266 OPT_X = 1 << 3, // connect using openssl s_client helper
268 OPTS_n = 1 << 4, // sendmail: request notification
269 OPTF_t = 1 << 4, // fetchmail: use "TOP" not "RETR"
271 OPTS_s = 1 << 5, // sendmail: subject
272 OPTF_z = 1 << 5, // fetchmail: delete from server
274 OPTS_c = 1 << 6, // sendmail: assumed charset
275 OPTS_t = 1 << 7, // sendmail: recipient(s)
276 OPTS_i = 1 << 8, // sendmail: ignore lone dots in message body (implied)
282 // init global variables
285 // parse options, different option sets for sendmail and fetchmail
286 // N.B. opt_after_connect hereafter is NULL if we are called as fetchmail
287 // and is NOT NULL if we are called as sendmail
288 if (!ENABLE_FETCHMAIL || 's' == applet_name[0]) {
290 // save initial stdin (body or attachements can be piped!)
291 xdup2(STDIN_FILENO, INITIAL_STDIN_FILENO);
292 opt_complementary = "-2:w+:t::";
293 options = "w:U:P:X" "ns:c:t:i";
296 opt_after_connect = NULL;
297 opt_complementary = "-2:w+:P";
298 options = "w:U:P:X" "tz";
300 opts = getopt32(argv, options,
301 &timeout, &opt_user, &opt_pass,
302 &opt_subject, &opt_charset, &opt_recipients
307 // first argument is remote server[:port]
308 opt_connect = *argv++;
313 // ... use openssl helper
314 launch_helper(xargs);
315 // no SSL ordered? ->
317 // ... make plain connect
318 int fd = create_and_connect_stream_or_die(opt_connect, 25);
319 // make ourselves a simple IO filter
320 // from now we know nothing about network :)
321 xmove_fd(fd, STDIN_FILENO);
322 xdup2(STDIN_FILENO, STDOUT_FILENO);
327 if (opt_after_connect)
330 /***************************************************
332 ***************************************************/
341 // we didn't use SSL helper? ->
342 if (!(opts & OPT_X)) {
343 // ... wait for initial server OK
344 smtp_check(NULL, 220);
348 opt_from = sane(*argv++);
350 // if no recipients _and_ no body files specified -> enter all-included mode
351 // i.e. scan stdin for To: and Subject: lines ...
352 // ... and then use the rest of stdin as message body
353 if (!opt_recipients && !*argv) {
354 // fetch recipients and (optionally) subject
356 while ((s = xmalloc_reads(INITIAL_STDIN_FILENO, NULL, NULL)) != NULL) {
357 if (0 == strncmp("To: ", s, 4)) {
358 llist_add_to_end(&opt_recipients, s+4);
359 } else if (0 == strncmp("Subject: ", s, 9)) {
369 // order to read body from stdin
370 *--argv = (char *)"-";
373 // introduce to server
374 // we should start with modern EHLO
375 if (250 != smtp_checkp("EHLO %s", opt_from, -1)) {
376 smtp_checkp("HELO %s", opt_from, 250);
380 // NOTE: if password has not been specified
381 // then no authentication is possible
382 code = (opts & OPT_P) ? -1 : 250;
383 // first try softly without authentication
384 while (250 != smtp_checkp("MAIL FROM:<%s>", opt_from, code)) {
385 // MAIL FROM failed -> authentication needed
386 // have we got username?
387 if (!(opts & OPT_U)) {
388 // no! fetch it from "from" option
390 opt_user = xstrdup(opt_from);
391 *strchrnul(opt_user, '@') = '\0';
393 // now we've got username
394 // so try to authenticate
395 if (334 == smtp_check("AUTH LOGIN", -1)) {
396 uuencode(NULL, opt_user);
398 uuencode(NULL, opt_pass);
401 // authenticated OK? -> retry to set sender
402 // but this time die on failure!
407 for (llist_t *to = opt_recipients; to; to = to->link) {
408 smtp_checkp("RCPT TO:<%s>", sane(to->data), 250);
411 // enter "put message" mode
412 smtp_check("DATA", 354);
414 // put address headers
415 printf("From: %s\r\n", opt_from);
416 for (llist_t *to = opt_recipients; to; to = to->link) {
417 printf("To: %s\r\n", to->data);
420 // put encoded subject
422 sane((char *)opt_charset);
424 printf("Subject: =?%s?B?", opt_charset);
425 uuencode(NULL, opt_subject);
431 printf("Disposition-Notification-To: %s\r\n", opt_from);
433 // make a random string -- it will delimit message parts
434 srand(monotonic_us());
435 boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());
437 // put common headers and body start
439 "Message-ID: <%s>\r\n"
440 "Mime-Version: 1.0\r\n"
441 "%smultipart/mixed; boundary=\"%s\"\r\n"
447 // put body + attachment(s)
448 // N.B. all these weird things just to be tiny
449 // by reusing string patterns!
452 "%stext/plain; charset=%s\r\n"
464 , "Content-Disposition: inline"
466 , "Content-Transfer-Encoding: base64\r\n"
471 "%sapplication/octet-stream%s\r\n"
472 "%s; filename=\"%s\"\r\n"
475 uuencode(*argv, NULL);
477 q = bb_get_last_path_component_strip(*argv);
480 // put message terminator
481 printf("\r\n--%s--\r\n" "\r\n", boundary);
483 // leave "put message" mode
484 smtp_check(".", 250);
485 // ... and say goodbye
486 smtp_check("QUIT", 221);
490 /***************************************************
492 ***************************************************/
499 // cache fetch command:
500 // TOP will return only the headers
501 // RETR will dump the whole message
502 const char *retr = (opts & OPTF_t) ? "TOP %u 0" : "RETR %u";
507 // cache postprocess program
511 if (!(opts & OPT_U)) {
513 // N.B. IMHO getenv("USER") can be way easily spoofed!
514 opt_user = bb_getpwuid(NULL, -1, getuid());
517 // get server greeting
518 pop3_checkr(NULL, NULL, &buf);
520 // server supports APOP?
523 // yes! compose <stamp><password>
524 char *s = strchr(buf, '>');
526 strcpy(s+1, opt_pass);
528 // get md5 sum of <stamp><password>
530 md5_hash(s, strlen(s), &md5);
532 // NOTE: md5 struct contains enough space
533 // so we reuse md5 space instead of xzalloc(16*2+1)
534 #define md5_hex ((uint8_t *)&md5)
535 // uint8_t *md5_hex = (uint8_t *)&md5;
536 *bin2hex(md5_hex, s, 16) = '\0';
538 s = xasprintf("%s %s", opt_user, md5_hex);
540 pop3_check("APOP %s", s);
541 if (ENABLE_FEATURE_CLEAN_UP) {
543 free(buf-4); // buf is "+OK " away from malloc'ed string
545 // server ignores APOP -> use simple text authentication
548 pop3_check("USER %s", opt_user);
550 pop3_check("PASS %s", opt_pass);
553 // get mailbox statistics
554 pop3_checkr("STAT", NULL, &buf);
556 // prepare message filename suffix
557 hostname = safe_gethostname();
560 // get messages counter
561 // NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"
562 // we only need nmsg and atoi is just exactly what we need
563 // if atoi fails to convert buf into number it returns 0
564 // in this case the following loop simply will not be executed
566 if (ENABLE_FEATURE_CLEAN_UP)
567 free(buf-4); // buf is "+OK " away from malloc'ed string
569 // loop through messages
570 for (; nmsg; nmsg--) {
572 // generate unique filename
573 char *filename = xasprintf("tmp/%llu.%u.%s", monotonic_us(), pid, hostname);
577 // retrieve message in ./tmp/
578 pop3_check(retr, (const char *)(ptrdiff_t)nmsg);
579 pop3_message(filename);
580 // delete message from server
582 pop3_check("DELE %u", (const char*)(ptrdiff_t)nmsg);
584 // run postprocessing program
587 rc = wait4pid(spawn((char **)fargs));
594 // atomically move message to ./new/
595 target = xstrdup(filename);
596 strncpy(target, "new", 3);
597 // ... or just stop receiving on error
598 if (rename_or_warn(filename, target))
606 pop3_check("QUIT", NULL);
607 #endif // ENABLE_FETCHMAIL