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