ipcrm,ipcs: make them NOEXEC
[oweals/busybox.git] / mailutils / sendmail.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * bare bones sendmail
4  *
5  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6  *
7  * Licensed under GPLv2, see file LICENSE in this source tree.
8  */
9 //config:config SENDMAIL
10 //config:       bool "sendmail (14 kb)"
11 //config:       default y
12 //config:       help
13 //config:       Barebones sendmail.
14
15 //applet:IF_SENDMAIL(APPLET(sendmail, BB_DIR_USR_SBIN, BB_SUID_DROP))
16
17 //kbuild:lib-$(CONFIG_SENDMAIL) += sendmail.o mail.o
18
19 //usage:#define sendmail_trivial_usage
20 //usage:       "[-tv] [-f SENDER] [-amLOGIN 4<user_pass.txt | -auUSER -apPASS]"
21 //usage:     "\n                [-w SECS] [-H 'PROG ARGS' | -S HOST] [RECIPIENT_EMAIL]..."
22 //usage:#define sendmail_full_usage "\n\n"
23 //usage:       "Read email from stdin and send it\n"
24 //usage:     "\nStandard options:"
25 //usage:     "\n        -t              Read additional recipients from message body"
26 //usage:     "\n        -f SENDER       For use in MAIL FROM:<sender>. Can be empty string"
27 //usage:     "\n                        Default: -auUSER, or username of current UID"
28 //usage:     "\n        -o OPTIONS      Various options. -oi implied, others are ignored"
29 //usage:     "\n        -i              -oi synonym, implied and ignored"
30 //usage:     "\n"
31 //usage:     "\nBusybox specific options:"
32 //usage:     "\n        -v              Verbose"
33 //usage:     "\n        -w SECS         Network timeout"
34 //usage:     "\n        -H 'PROG ARGS'  Run connection helper. Examples:"
35 //usage:     "\n                openssl s_client -quiet -tls1 -starttls smtp -connect smtp.gmail.com:25"
36 //usage:     "\n                openssl s_client -quiet -tls1 -connect smtp.gmail.com:465"
37 //usage:     "\n                        $SMTP_ANTISPAM_DELAY: seconds to wait after helper connect"
38 //usage:     "\n        -S HOST[:PORT]  Server (default $SMTPHOST or 127.0.0.1)"
39 //usage:     "\n        -amLOGIN        Log in using AUTH LOGIN (-amCRAM-MD5 not supported)"
40 //usage:     "\n        -auUSER         Username for AUTH"
41 //usage:     "\n        -apPASS         Password for AUTH"
42 //usage:     "\n"
43 //usage:     "\nIf no -a options are given, authentication is not done."
44 //usage:     "\nIf -amLOGIN is given but no -au/-ap, user/password is read from fd #4."
45 //usage:     "\nOther options are silently ignored; -oi is implied."
46 //usage:        IF_MAKEMIME(
47 //usage:     "\nUse makemime to create emails with attachments."
48 //usage:        )
49
50 /* Currently we don't sanitize or escape user-supplied SENDER and RECIPIENT_EMAILs.
51  * We may need to do so. For one, '.' in usernames seems to require escaping!
52  *
53  * From http://cr.yp.to/smtp/address.html:
54  *
55  * SMTP offers three ways to encode a character inside an address:
56  *
57  * "safe": the character, if it is not <>()[].,;:@, backslash,
58  *  double-quote, space, or an ASCII control character;
59  * "quoted": the character, if it is not \012, \015, backslash,
60  *   or double-quote; or
61  * "slashed": backslash followed by the character.
62  *
63  * An encoded box part is either (1) a sequence of one or more slashed
64  * or safe characters or (2) a double quote, a sequence of zero or more
65  * slashed or quoted characters, and a double quote. It represents
66  * the concatenation of the characters encoded inside it.
67  *
68  * For example, the encoded box parts
69  *      angels
70  *      \a\n\g\e\l\s
71  *      "\a\n\g\e\l\s"
72  *      "angels"
73  *      "ang\els"
74  * all represent the 6-byte string "angels", and the encoded box parts
75  *      a\,comma
76  *      \a\,\c\o\m\m\a
77  *      "a,comma"
78  * all represent the 7-byte string "a,comma".
79  *
80  * An encoded address contains
81  *      the byte <;
82  *      optionally, a route followed by a colon;
83  *      an encoded box part, the byte @, and a domain; and
84  *      the byte >.
85  *
86  * It represents an Internet mail address, given by concatenating
87  * the string represented by the encoded box part, the byte @,
88  * and the domain. For example, the encoded addresses
89  *     <God@heaven.af.mil>
90  *     <\God@heaven.af.mil>
91  *     <"God"@heaven.af.mil>
92  *     <@gateway.af.mil,@uucp.local:"\G\o\d"@heaven.af.mil>
93  * all represent the Internet mail address "God@heaven.af.mil".
94  */
95
96 #include "libbb.h"
97 #include "mail.h"
98
99 // limit maximum allowed number of headers to prevent overflows.
100 // set to 0 to not limit
101 #define MAX_HEADERS 256
102
103 static void send_r_n(const char *s)
104 {
105         if (verbose)
106                 bb_error_msg("send:'%s'", s);
107         printf("%s\r\n", s);
108 }
109
110 static int smtp_checkp(const char *fmt, const char *param, int code)
111 {
112         char *answer;
113         char *msg = send_mail_command(fmt, param);
114         // read stdin
115         // if the string has a form NNN- -- read next string. E.g. EHLO response
116         // parse first bytes to a number
117         // if code = -1 then just return this number
118         // if code != -1 then checks whether the number equals the code
119         // if not equal -> die saying msg
120         while ((answer = xmalloc_fgetline(stdin)) != NULL) {
121                 if (verbose)
122                         bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
123                 if (strlen(answer) <= 3 || '-' != answer[3])
124                         break;
125                 free(answer);
126         }
127         if (answer) {
128                 int n = atoi(answer);
129                 if (timeout)
130                         alarm(0);
131                 free(answer);
132                 if (-1 == code || n == code) {
133                         free(msg);
134                         return n;
135                 }
136         }
137         bb_error_msg_and_die("%s failed", msg);
138 }
139
140 static int smtp_check(const char *fmt, int code)
141 {
142         return smtp_checkp(fmt, NULL, code);
143 }
144
145 // strip argument of bad chars
146 static char *sane_address(char *str)
147 {
148         char *s;
149
150         trim(str);
151         s = str;
152         while (*s) {
153                 if (!isalnum(*s) && !strchr("+_-.@", *s)) {
154                         bb_error_msg("bad address '%s'", str);
155                         /* returning "": */
156                         str[0] = '\0';
157                         return str;
158                 }
159                 s++;
160         }
161         return str;
162 }
163
164 // check for an address inside angle brackets, if not found fall back to normal
165 static char *angle_address(char *str)
166 {
167         char *s, *e;
168
169         e = trim(str);
170         if (e != str && e[-1] == '>') {
171                 s = strrchr(str, '<');
172                 if (s) {
173                         *e = '\0';
174                         str = s + 1;
175                 }
176         }
177         return sane_address(str);
178 }
179
180 static void rcptto(const char *s)
181 {
182         if (!*s)
183                 return;
184         // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
185         if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
186                 bb_error_msg("Bad recipient: <%s>", s);
187 }
188
189 // send to a list of comma separated addresses
190 static void rcptto_list(const char *list)
191 {
192         char *str = xstrdup(list);
193         char *s = str;
194         char prev = 0;
195         int in_quote = 0;
196
197         while (*s) {
198                 char ch = *s++;
199
200                 if (ch == '"' && prev != '\\') {
201                         in_quote = !in_quote;
202                 } else if (!in_quote && ch == ',') {
203                         s[-1] = '\0';
204                         rcptto(angle_address(str));
205                         str = s;
206                 }
207                 prev = ch;
208         }
209         if (prev != ',')
210                 rcptto(angle_address(str));
211         free(str);
212 }
213
214 int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
215 int sendmail_main(int argc UNUSED_PARAM, char **argv)
216 {
217         char *opt_connect;
218         char *opt_from = NULL;
219         char *s;
220         llist_t *list = NULL;
221         char *host = sane_address(safe_gethostname());
222         unsigned nheaders = 0;
223         int code;
224         enum {
225                 HDR_OTHER = 0,
226                 HDR_TOCC,
227                 HDR_BCC,
228         } last_hdr = 0;
229         int check_hdr;
230         int has_to = 0;
231
232         enum {
233         //--- standard options
234                 OPT_t = 1 << 0,         // read message for recipients, append them to those on cmdline
235                 OPT_f = 1 << 1,         // sender address
236                 OPT_o = 1 << 2,         // various options. -oi IMPLIED! others are IGNORED!
237                 OPT_i = 1 << 3,         // IMPLIED!
238         //--- BB specific options
239                 OPT_w = 1 << 4,         // network timeout
240                 OPT_H = 1 << 5,         // use external connection helper
241                 OPT_S = 1 << 6,         // specify connection string
242                 OPT_a = 1 << 7,         // authentication tokens
243                 OPT_v = 1 << 8,         // verbosity
244         };
245
246         // init global variables
247         INIT_G();
248
249         // default HOST[:PORT] is $SMTPHOST, or localhost
250         opt_connect = getenv("SMTPHOST");
251         if (!opt_connect)
252                 opt_connect = (char *)"127.0.0.1";
253
254         // save initial stdin since body is piped!
255         xdup2(STDIN_FILENO, 3);
256         G.fp0 = xfdopen_for_read(3);
257
258         // parse options
259         // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
260         // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
261         // it is still under development.
262         opts = getopt32(argv, "^"
263                         "tf:o:iw:+H:S:a:*:v"
264                         "\0"
265                         // -v is a counter, -H and -S are mutually exclusive, -a is a list
266                         "vv:H--S:S--H",
267                         &opt_from, NULL,
268                         &timeout, &opt_connect, &opt_connect, &list, &verbose
269         );
270         //argc -= optind;
271         argv += optind;
272
273         // process -a[upm]<token> options
274         if ((opts & OPT_a) && !list)
275                 bb_show_usage();
276         while (list) {
277                 char *a = (char *) llist_pop(&list);
278                 if ('u' == a[0])
279                         G.user = xstrdup(a+1);
280                 if ('p' == a[0])
281                         G.pass = xstrdup(a+1);
282                 // N.B. we support only AUTH LOGIN so far
283                 //if ('m' == a[0])
284                 //      G.method = xstrdup(a+1);
285         }
286         // N.B. list == NULL here
287         //bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
288
289         // connect to server
290
291         // connection helper ordered? ->
292         if (opts & OPT_H) {
293                 const char *delay;
294                 const char *args[] = { "sh", "-c", opt_connect, NULL };
295                 // plug it in
296                 launch_helper(args);
297                 // Now:
298                 // our stdout will go to helper's stdin,
299                 // helper's stdout will be available on our stdin.
300
301                 // Wait for initial server message.
302                 // If helper (such as openssl) invokes STARTTLS, the initial 220
303                 // is swallowed by helper (and not repeated after TLS is initiated).
304                 // We will send NOOP cmd to server and check the response.
305                 // We should get 220+250 on plain connection, 250 on STARTTLSed session.
306                 //
307                 // The problem here is some servers delay initial 220 message,
308                 // and consider client to be a spammer if it starts sending cmds
309                 // before 220 reached it. The code below is unsafe in this regard:
310                 // in non-STARTTLSed case, we potentially send NOOP before 220
311                 // is sent by server.
312                 //
313                 // If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
314                 //
315                 delay = getenv("SMTP_ANTISPAM_DELAY");
316                 if (delay)
317                         sleep(atoi(delay));
318                 code = smtp_check("NOOP", -1);
319                 if (code == 220)
320                         // we got 220 - this is not STARTTLSed connection,
321                         // eat 250 response to our NOOP
322                         smtp_check(NULL, 250);
323                 else
324                 if (code != 250)
325                         bb_error_msg_and_die("SMTP init failed");
326         } else {
327                 // vanilla connection
328                 int fd;
329                 fd = create_and_connect_stream_or_die(opt_connect, 25);
330                 // and make ourselves a simple IO filter
331                 xmove_fd(fd, STDIN_FILENO);
332                 xdup2(STDIN_FILENO, STDOUT_FILENO);
333
334                 // Wait for initial server 220 message
335                 smtp_check(NULL, 220);
336         }
337
338         // we should start with modern EHLO
339         if (250 != smtp_checkp("EHLO %s", host, -1))
340                 smtp_checkp("HELO %s", host, 250);
341
342         // perform authentication
343         if (opts & OPT_a) {
344                 smtp_check("AUTH LOGIN", 334);
345                 // we must read credentials unless they are given via -a[up] options
346                 if (!G.user || !G.pass)
347                         get_cred_or_die(4);
348                 encode_base64(NULL, G.user, NULL);
349                 smtp_check("", 334);
350                 encode_base64(NULL, G.pass, NULL);
351                 smtp_check("", 235);
352         }
353
354         // set sender
355         // N.B. we have here a very loosely defined algorythm
356         // since sendmail historically offers no means to specify secrets on cmdline.
357         // 1) server can require no authentication ->
358         //      we must just provide a (possibly fake) reply address.
359         // 2) server can require AUTH ->
360         //      we must provide valid username and password along with a (possibly fake) reply address.
361         //      For the sake of security username and password are to be read either from console or from a secured file.
362         //      Since reading from console may defeat usability, the solution is either to read from a predefined
363         //      file descriptor (e.g. 4), or again from a secured file.
364
365         // got no sender address? use auth name, then UID username as a last resort
366         if (!opt_from) {
367                 opt_from = xasprintf("%s@%s",
368                                      G.user ? G.user : xuid2uname(getuid()),
369                                      xgethostbyname(host)->h_name);
370         }
371         free(host);
372
373         smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
374
375         // process message
376
377         // read recipients from message and add them to those given on cmdline.
378         // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
379         // and then use the rest of stdin as message body
380         code = 0; // set "analyze headers" mode
381         while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
382  dump:
383                 // put message lines doubling leading dots
384                 if (code) {
385                         // escape leading dots
386                         // N.B. this feature is implied even if no -i (-oi) switch given
387                         // N.B. we need to escape the leading dot regardless of
388                         // whether it is single or not character on the line
389                         if ('.' == s[0] /*&& '\0' == s[1] */)
390                                 bb_putchar('.');
391                         // dump read line
392                         send_r_n(s);
393                         free(s);
394                         continue;
395                 }
396
397                 // analyze headers
398                 // To: or Cc: headers add recipients
399                 check_hdr = (0 == strncasecmp("To:", s, 3));
400                 has_to |= check_hdr;
401                 if (opts & OPT_t) {
402                         if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
403                                 rcptto_list(s+3);
404                                 last_hdr = HDR_TOCC;
405                                 goto addheader;
406                         }
407                         // Bcc: header adds blind copy (hidden) recipient
408                         if (0 == strncasecmp("Bcc:", s, 4)) {
409                                 rcptto_list(s+4);
410                                 free(s);
411                                 last_hdr = HDR_BCC;
412                                 continue; // N.B. Bcc: vanishes from headers!
413                         }
414                 }
415                 check_hdr = (list && isspace(s[0]));
416                 if (strchr(s, ':') || check_hdr) {
417                         // other headers go verbatim
418                         // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
419                         // Continuation is denoted by prefixing additional lines with whitespace(s).
420                         // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
421                         if (check_hdr && last_hdr != HDR_OTHER) {
422                                 rcptto_list(s+1);
423                                 if (last_hdr == HDR_BCC)
424                                         continue;
425                                         // N.B. Bcc: vanishes from headers!
426                         } else {
427                                 last_hdr = HDR_OTHER;
428                         }
429  addheader:
430                         // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
431                         if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
432                                 goto bail;
433                         llist_add_to_end(&list, s);
434                 } else {
435                         // a line without ":" (an empty line too, by definition) doesn't look like a valid header
436                         // so stop "analyze headers" mode
437  reenter:
438                         // put recipients specified on cmdline
439                         check_hdr = 1;
440                         while (*argv) {
441                                 char *t = sane_address(*argv);
442                                 rcptto(t);
443                                 //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
444                                 //      goto bail;
445                                 if (!has_to) {
446                                         const char *hdr;
447
448                                         if (check_hdr && argv[1])
449                                                 hdr = "To: %s,";
450                                         else if (check_hdr)
451                                                 hdr = "To: %s";
452                                         else if (argv[1])
453                                                 hdr = "To: %s," + 3;
454                                         else
455                                                 hdr = "To: %s" + 3;
456                                         llist_add_to_end(&list,
457                                                         xasprintf(hdr, t));
458                                         check_hdr = 0;
459                                 }
460                                 argv++;
461                         }
462                         // enter "put message" mode
463                         // N.B. DATA fails iff no recipients were accepted (or even provided)
464                         // in this case just bail out gracefully
465                         if (354 != smtp_check("DATA", -1))
466                                 goto bail;
467                         // dump the headers
468                         while (list) {
469                                 send_r_n((char *) llist_pop(&list));
470                         }
471                         // stop analyzing headers
472                         code++;
473                         // N.B. !s means: we read nothing, and nothing to be read in the future.
474                         // just dump empty line and break the loop
475                         if (!s) {
476                                 send_r_n("");
477                                 break;
478                         }
479                         // go dump message body
480                         // N.B. "s" already contains the first non-header line, so pretend we read it from input
481                         goto dump;
482                 }
483         }
484         // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
485         // N.B. after reenter code will be > 0
486         if (!code)
487                 goto reenter;
488
489         // finalize the message
490         smtp_check(".", 250);
491  bail:
492         // ... and say goodbye
493         smtp_check("QUIT", 221);
494         // cleanup
495         if (ENABLE_FEATURE_CLEAN_UP)
496                 fclose(G.fp0);
497
498         return EXIT_SUCCESS;
499 }