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