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