*: introduce and use xfork()
[oweals/busybox.git] / networking / sendmail.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * bare bones sendmail/fetchmail
4  *
5  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6  *
7  * Licensed under GPLv2, see file LICENSE in this tarball for details.
8  */
9 #include "libbb.h"
10
11 #define INITIAL_STDIN_FILENO 3
12
13 static void uuencode(char *fname, const char *text)
14 {
15         enum {
16                 SRC_BUF_SIZE = 45,  /* This *MUST* be a multiple of 3 */
17                 DST_BUF_SIZE = 4 * ((SRC_BUF_SIZE + 2) / 3),
18         };
19
20 #define src_buf text
21         int fd;
22 #define len fd
23         char dst_buf[DST_BUF_SIZE + 1];
24
25         if (fname) {
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!
31         } else if (text) {
32                 // though we do not call uuencode(NULL, NULL) explicitly
33                 // still we do not want to break things suddenly
34                 len = strlen(text);
35         } else
36                 return;
37
38         fflush(stdout); // sync stdio and unistd output
39         while (1) {
40                 size_t size;
41                 if (fname) {
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);
45                 } else {
46                         size = len;
47                         if (len > SRC_BUF_SIZE)
48                                 size = SRC_BUF_SIZE;
49                 }
50                 if (!size)
51                         break;
52                 // encode the buffer we just read in
53                 bb_uuencode(dst_buf, src_buf, size, bb_uuenc_tbl_base64);
54                 if (fname) {
55                         xwrite(STDOUT_FILENO, "\r\n", 2);
56                 } else {
57                         src_buf += size;
58                         len -= size;
59                 }
60                 xwrite(STDOUT_FILENO, dst_buf, 4 * ((size + 2) / 3));
61         }
62         if (fname)
63                 close(fd);
64 #undef src_buf
65 #undef len
66 }
67
68 struct globals {
69         pid_t helper_pid;
70         unsigned timeout;
71         // arguments for SSL connection helper
72         const char *xargs[9];
73         // arguments for postprocess helper
74         const char *fargs[3];
75 };
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";*/ \
88         xargs[5] = "-tls1"; \
89         xargs[6] = "-starttls"; \
90         xargs[7] = "smtp"; \
91         fargs[0] = "utf-8"; \
92 } while (0)
93
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])
98
99 static void kill_helper(void)
100 {
101         // TODO!!!: is there more elegant way to terminate child on program failure?
102         if (helper_pid > 0)
103                 kill(helper_pid, SIGTERM);
104 }
105
106 // generic signal handler
107 static void signal_handler(int signo)
108 {
109 #define err signo
110
111         if (SIGALRM == signo) {
112                 kill_helper();
113                 bb_error_msg_and_die("timed out");
114         }
115
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));
120 #undef err
121 }
122
123 static void launch_helper(const char **argv)
124 {
125         // setup vanilla unidirectional pipes interchange
126         int idx;
127         int pipes[4];
128
129         xpipe(pipes);
130         xpipe(pipes+2);
131         helper_pid = xvfork();
132         idx = (!helper_pid) * 2;
133         xdup2(pipes[idx], STDIN_FILENO);
134         xdup2(pipes[3-idx], STDOUT_FILENO);
135         if (ENABLE_FEATURE_CLEAN_UP)
136                 for (int i = 4; --i >= 0; )
137                         if (pipes[i] > STDOUT_FILENO)
138                                 close(pipes[i]);
139         if (!helper_pid) {
140                 // child: try to execute connection helper
141                 BB_EXECVP(*argv, (char **)argv);
142                 _exit(127);
143         }
144         // parent: check whether child is alive
145         bb_signals(0
146                 + (1 << SIGCHLD)
147                 + (1 << SIGALRM)
148                 , signal_handler);
149         signal_handler(SIGCHLD);
150         // child seems OK -> parent goes on
151 }
152
153 static const char *command(const char *fmt, const char *param)
154 {
155         const char *msg = fmt;
156         alarm(timeout);
157         if (msg) {
158                 msg = xasprintf(fmt, param);
159                 printf("%s\r\n", msg);
160         }
161         fflush(stdout);
162         return msg;
163 }
164
165 static int smtp_checkp(const char *fmt, const char *param, int code)
166 {
167         char *answer;
168         const char *msg = command(fmt, param);
169         // read stdin
170         // if the string has a form \d\d\d- -- read next string. E.g. EHLO response
171         // parse first bytes to a number
172         // if code = -1 then just return this number
173         // if code != -1 then checks whether the number equals the code
174         // if not equal -> die saying msg
175         while ((answer = xmalloc_fgetline(stdin)) != NULL)
176                 if (strlen(answer) <= 3 || '-' != answer[3])
177                         break;
178         if (answer) {
179                 int n = atoi(answer);
180                 alarm(0);
181                 if (ENABLE_FEATURE_CLEAN_UP) {
182                         free(answer);
183                 }
184                 if (-1 == code || n == code) {
185                         return n;
186                 }
187         }
188         kill_helper();
189         bb_error_msg_and_die("%s failed", msg);
190 }
191
192 static inline int smtp_check(const char *fmt, int code)
193 {
194         return smtp_checkp(fmt, NULL, code);
195 }
196
197 // strip argument of bad chars
198 static char *sane(char *str)
199 {
200         char *s = str;
201         char *p = s;
202         while (*s) {
203                 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
204                         *p++ = *s;
205                 }
206                 s++;
207         }
208         *p = '\0';
209         return str;
210 }
211
212 #if ENABLE_FETCHMAIL
213 static void pop3_checkr(const char *fmt, const char *param, char **ret)
214 {
215         const char *msg = command(fmt, param);
216         char *answer = xmalloc_fgetline(stdin);
217         if (answer && '+' == *answer) {
218                 alarm(0);
219                 if (ret)
220                         *ret = answer+4; // skip "+OK "
221                 else if (ENABLE_FEATURE_CLEAN_UP)
222                         free(answer);
223                 return;
224         }
225         kill_helper();
226         bb_error_msg_and_die("%s failed", msg);
227 }
228
229 static inline void pop3_check(const char *fmt, const char *param)
230 {
231         pop3_checkr(fmt, param, NULL);
232 }
233
234 static void pop3_message(const char *filename)
235 {
236         int fd;
237         char *answer;
238         // create and open file filename
239         // read stdin, copy to created file
240         fd = xopen(filename, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL);
241         while ((answer = xmalloc_fgets_str(stdin, "\r\n")) != NULL) {
242                 char *s = answer;
243                 if ('.' == *answer) {
244                         if ('.' == answer[1])
245                                 s++;
246                         else if ('\r' == answer[1] && '\n' == answer[2] && '\0' == answer[3])
247                                 break;
248                 }
249                 xwrite(fd, s, strlen(s));
250                 free(answer);
251         }
252         close(fd);
253 }
254 #endif
255
256 static char *parse_url(char *url, char **user, char **pass)
257 {
258         // parse [user[:pass]@]host
259         // return host
260         char *s = strchr(url, '@');
261         *user = *pass = NULL;
262         if (s) {
263                 *s++ = '\0';
264                 *user = url;
265                 url = s;
266                 s = strchr(*user, ':');
267                 if (s) {
268                         *s++ = '\0';
269                         *pass = s;
270                 }
271         }
272         return url;
273 }
274
275 int sendgetmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
276 int sendgetmail_main(int argc ATTRIBUTE_UNUSED, char **argv)
277 {
278         llist_t *opt_recipients = NULL;
279         llist_t *opt_attachments = NULL;
280         char *opt_from;
281         char *opt_user;
282         char *opt_pass;
283         enum {
284                 OPT_w = 1 << 0,         // network timeout
285                 OPT_H = 1 << 1,         // [user:password@]server[:port]
286                 OPT_S = 1 << 2,         // connect using openssl s_client helper
287
288                 OPTS_t = 1 << 3,        // sendmail: read addresses from body
289                 OPTF_t = 1 << 3,        // fetchmail: use "TOP" not "RETR"
290
291                 OPTS_s = 1 << 4,        // sendmail: subject
292                 OPTF_z = 1 << 4,        // fetchmail: delete from server
293
294                 OPTS_c = 1 << 5,        // sendmail: assumed charset
295                 OPTS_a = 1 << 6,        // sendmail: attachment(s)
296                 OPTS_i = 1 << 7,        // sendmail: ignore lone dots in message body (implied)
297
298                 OPTS_N = 1 << 8,        // sendmail: request notification
299                 OPTS_f = 1 << 9,        // sendmail: sender address
300         };
301         const char *options;
302         int opts;
303
304         // init global variables
305         INIT_G();
306
307         // parse options, different option sets for sendmail and fetchmail
308         // N.B. opt_after_connect hereafter is NULL if we are called as fetchmail
309         // and is NOT NULL if we are called as sendmail
310         if (!ENABLE_FETCHMAIL || 's' == applet_name[0]) {
311                 // SENDMAIL
312                 // save initial stdin since body is piped!
313                 xdup2(STDIN_FILENO, INITIAL_STDIN_FILENO);
314                 opt_complementary = "w+:a::";
315                 options = "w:H:St" "s:c:a:iN:f:";
316                 // body is pseudo attachment read from stdin
317                 llist_add_to_end(&opt_attachments, (char *)"-");
318         } else {
319                 // FETCHMAIL
320                 opt_after_connect = NULL;
321                 opt_complementary = "-1:w+";
322                 options = "w:H:St" "z";
323         }
324         opts = getopt32(argv, options,
325                 &timeout /* -w */, &opt_connect /* -H */,
326                 &opt_subject, &opt_charset, &opt_attachments, NULL, &opt_from
327         );
328         //argc -= optind;
329         argv += optind;
330
331         // connect to server
332         // host[:port] not specified ? -> use $HOSTNAME. no $HOSTNAME ? -> use localhost
333         if (!(opts & OPT_H)) {
334                 opt_connect = getenv("HOSTNAME");
335                 if (!opt_connect)
336                         opt_connect = "127.0.0.1";
337         }
338         // fetch username and password, if any
339         // NB: parse_url modifies opt_connect[] ONLY if '@' is there.
340         // Thus "127.0.0.1" won't be modified, an is ok that it is RO.
341         opt_connect = parse_url((char*)opt_connect, &opt_user, &opt_pass);
342 //      bb_error_msg("H[%s] U[%s] P[%s]", opt_connect, opt_user, opt_pass);
343
344         // username must be defined!
345         if (!opt_user) {
346                 // N.B. IMHO getenv("USER") can be way easily spoofed!
347                 opt_user = bb_getpwuid(NULL, -1, getuid());
348         }
349
350         // SSL ordered? ->
351         if (opts & OPT_S) {
352                 // ... use openssl helper
353                 launch_helper(xargs);
354         // no SSL ordered? ->
355         } else {
356                 // ... make plain connect
357                 int fd = create_and_connect_stream_or_die(opt_connect, 25);
358                 // make ourselves a simple IO filter
359                 // from now we know nothing about network :)
360                 xmove_fd(fd, STDIN_FILENO);
361                 xdup2(STDIN_FILENO, STDOUT_FILENO);
362         }
363
364         // are we sendmail?
365         if (!ENABLE_FETCHMAIL || opt_after_connect)
366 /***************************************************
367  * SENDMAIL
368  ***************************************************/
369         {
370                 int code;
371                 char *boundary;
372                 const char *fmt;
373                 const char *p;
374                 char *q;
375                 llist_t *l;
376
377                 // recipients specified as arguments
378                 while (*argv) {
379                         // loose test on email address validity
380                         if (strchr(sane(*argv), '@'))
381                                 llist_add_to_end(&opt_recipients, *argv);
382                         argv++;
383                 }
384
385                 // if -t specified or no recipients specified -> enter all-included mode
386                 // i.e. scan stdin for To: and Subject: lines ...
387                 // ... and then use the rest of stdin as message body
388                 // N.B. subject read from body has priority
389                 // over that specified on command line.
390                 // recipients are merged
391                 if (opts & OPTS_t || !opt_recipients) {
392                         // fetch recipients and (optionally) subject
393                         char *s;
394                         while ((s = xmalloc_reads(INITIAL_STDIN_FILENO, NULL, NULL)) != NULL) {
395                                 if (0 == strncmp("To: ", s, 4)) {
396                                         llist_add_to_end(&opt_recipients, s+4);
397 /*                              } else if (0 == strncmp("From: ", s, 6)) {
398                                         opt_from = s+6;
399                                         opts |= OPTS_f;
400 */                              } else if (0 == strncmp("Subject: ", s, 9)) {
401                                         opt_subject = s+9;
402                                         opts |= OPTS_s;
403                                 } else {
404                                         char first = s[0];
405                                         free(s);
406                                         if (!first)
407                                                 break; // empty line
408                                 }
409                         }
410                 }
411
412                 // got no sender address? -> use username as a resort
413                 if (!(opts & OPTS_f)) {
414                         char *domain = safe_getdomainname();
415                         opt_from = xasprintf("%s@%s", opt_user, domain);
416                         free(domain);
417                 }
418
419                 // introduce to server
420
421                 // we didn't use SSL helper? ->
422                 if (!(opts & OPT_S)) {
423                         // ... wait for initial server OK
424                         smtp_check(NULL, 220);
425                 }
426
427                 // we should start with modern EHLO
428                 if (250 != smtp_checkp("EHLO %s", sane(opt_from), -1)) {
429                         smtp_checkp("HELO %s", opt_from, 250);
430                 }
431
432                 // set sender
433                 // NOTE: if password has not been specified
434                 // then no authentication is possible
435                 code = (opt_pass) ? -1 : 250;
436                 // first try softly without authentication
437                 while (250 != smtp_checkp("MAIL FROM:<%s>", opt_from, code)) {
438                         // MAIL FROM failed -> authentication needed
439                         if (334 == smtp_check("AUTH LOGIN", -1)) {
440                                 uuencode(NULL, opt_user); // opt_user != NULL
441                                 smtp_check("", 334);
442                                 uuencode(NULL, opt_pass);
443                                 smtp_check("", 235);
444                         }
445                         // authenticated OK? -> retry to set sender
446                         // but this time die on failure!
447                         code = 250;
448                 }
449
450                 // set recipients
451                 for (l = opt_recipients; l; l = l->link) {
452                         smtp_checkp("RCPT TO:<%s>", sane(l->data), 250);
453                 }
454
455                 // enter "put message" mode
456                 smtp_check("DATA", 354);
457
458                 // put address headers
459                 printf("From: %s\r\n", opt_from);
460                 for (l = opt_recipients; l; l = l->link) {
461                         printf("To: %s\r\n", l->data);
462                 }
463
464                 // put encoded subject
465                 if (opts & OPTS_c)
466                         sane((char *)opt_charset);
467                 if (opts & OPTS_s) {
468                         printf("Subject: =?%s?B?", opt_charset);
469                         uuencode(NULL, opt_subject);
470                         printf("?=\r\n");
471                 }
472
473                 // put notification
474                 if (opts & OPTS_N)
475                         printf("Disposition-Notification-To: %s\r\n", opt_from);
476
477                 // make a random string -- it will delimit message parts
478                 srand(monotonic_us());
479                 boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());
480
481                 // put common headers and body start
482                 printf(
483                         "Message-ID: <%s>\r\n"
484                         "Mime-Version: 1.0\r\n"
485                         "%smultipart/mixed; boundary=\"%s\"\r\n"
486                         , boundary
487                         , "Content-Type: "
488                         , boundary
489                 );
490
491                 // put body + attachment(s)
492                 // N.B. all these weird things just to be tiny
493                 // by reusing string patterns!
494                 fmt =
495                         "\r\n--%s\r\n"
496                         "%stext/plain; charset=%s\r\n"
497                         "%s%s\r\n"
498                         "%s"
499                 ;
500                 p = opt_charset;
501                 q = (char *)"";
502                 l = opt_attachments;
503                 while (l) {
504                         printf(
505                                 fmt
506                                 , boundary
507                                 , "Content-Type: "
508                                 , p
509                                 , "Content-Disposition: inline"
510                                 , q
511                                 , "Content-Transfer-Encoding: base64\r\n"
512                         );
513                         p = "";
514                         fmt =
515                                 "\r\n--%s\r\n"
516                                 "%sapplication/octet-stream%s\r\n"
517                                 "%s; filename=\"%s\"\r\n"
518                                 "%s"
519                         ;
520                         uuencode(l->data, NULL);
521                         l = l->link;
522                         if (l)
523                                 q = bb_get_last_path_component_strip(l->data);
524                 }
525
526                 // put message terminator
527                 printf("\r\n--%s--\r\n" "\r\n", boundary);
528
529                 // leave "put message" mode
530                 smtp_check(".", 250);
531                 // ... and say goodbye
532                 smtp_check("QUIT", 221);
533         }
534 #if ENABLE_FETCHMAIL
535 /***************************************************
536  * FETCHMAIL
537  ***************************************************/
538         else {
539                 char *buf;
540                 unsigned nmsg;
541                 char *hostname;
542                 pid_t pid;
543
544                 // cache fetch command:
545                 // TOP will return only the headers
546                 // RETR will dump the whole message
547                 const char *retr = (opts & OPTF_t) ? "TOP %u 0" : "RETR %u";
548
549                 // goto maildir
550                 xchdir(*argv++);
551
552                 // cache postprocess program
553                 *fargs = *argv;
554
555                 // authenticate
556
557                 // password is mandatory
558                 if (!opt_pass) {
559                         bb_error_msg_and_die("no password");
560                 }
561
562                 // get server greeting
563                 pop3_checkr(NULL, NULL, &buf);
564
565                 // server supports APOP?
566                 if ('<' == *buf) {
567                         md5_ctx_t md5;
568                         // yes! compose <stamp><password>
569                         char *s = strchr(buf, '>');
570                         if (s)
571                                 strcpy(s+1, opt_pass);
572                         s = buf;
573                         // get md5 sum of <stamp><password>
574                         md5_begin(&md5);
575                         md5_hash(s, strlen(s), &md5);
576                         md5_end(s, &md5);
577                         // NOTE: md5 struct contains enough space
578                         // so we reuse md5 space instead of xzalloc(16*2+1)
579 #define md5_hex ((uint8_t *)&md5)
580 //                      uint8_t *md5_hex = (uint8_t *)&md5;
581                         *bin2hex((char *)md5_hex, s, 16) = '\0';
582                         // APOP
583                         s = xasprintf("%s %s", opt_user, md5_hex);
584 #undef md5_hex
585                         pop3_check("APOP %s", s);
586                         if (ENABLE_FEATURE_CLEAN_UP) {
587                                 free(s);
588                                 free(buf-4); // buf is "+OK " away from malloc'ed string
589                         }
590                 // server ignores APOP -> use simple text authentication
591                 } else {
592                         // USER
593                         pop3_check("USER %s", opt_user);
594                         // PASS
595                         pop3_check("PASS %s", opt_pass);
596                 }
597
598                 // get mailbox statistics
599                 pop3_checkr("STAT", NULL, &buf);
600
601                 // prepare message filename suffix
602                 hostname = safe_gethostname();
603                 pid = getpid();
604
605                 // get messages counter
606                 // NOTE: we don't use xatou(buf) since buf is "nmsg nbytes"
607                 // we only need nmsg and atoi is just exactly what we need
608                 // if atoi fails to convert buf into number it returns 0
609                 // in this case the following loop simply will not be executed
610                 nmsg = atoi(buf);
611                 if (ENABLE_FEATURE_CLEAN_UP)
612                         free(buf-4); // buf is "+OK " away from malloc'ed string
613
614                 // loop through messages
615                 for (; nmsg; nmsg--) {
616
617                         // generate unique filename
618                         char *filename = xasprintf("tmp/%llu.%u.%s",
619                                         monotonic_us(), (unsigned)pid, hostname);
620                         char *target;
621                         int rc;
622
623                         // retrieve message in ./tmp/
624                         pop3_check(retr, (const char *)(ptrdiff_t)nmsg);
625                         pop3_message(filename);
626                         // delete message from server
627                         if (opts & OPTF_z)
628                                 pop3_check("DELE %u", (const char*)(ptrdiff_t)nmsg);
629
630                         // run postprocessing program
631                         if (*fargs) {
632                                 fargs[1] = filename;
633                                 rc = wait4pid(spawn((char **)fargs));
634                                 if (99 == rc)
635                                         break;
636                                 if (1 == rc)
637                                         goto skip;
638                         }
639
640                         // atomically move message to ./new/
641                         target = xstrdup(filename);
642                         strncpy(target, "new", 3);
643                         // ... or just stop receiving on error
644                         if (rename_or_warn(filename, target))
645                                 break;
646                         free(target);
647  skip:
648                         free(filename);
649                 }
650
651                 // Bye
652                 pop3_check("QUIT", NULL);
653         }
654 #endif // ENABLE_FETCHMAIL
655
656         return 0;
657 }