reformime: do not require \r\n
[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:       "[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 | -au<username> -ap<password>]"
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 | -au<username> -ap<password>]"
33 //usage:     "\n        -S HOST[:PORT]  Server"
34 //usage:     "\n        -au<username>   Username for AUTH LOGIN"
35 //usage:     "\n        -ap<password>   Password for AUTH LOGIN"
36 //usage:     "\n        -am<method>     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 applet to create message 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' %d", (int)(strchrnul(answer, '\r') - answer), answer, verbose);
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(msg);
79                 free(answer);
80                 if (-1 == code || n == code)
81                         return n;
82         }
83         bb_error_msg_and_die("%s failed", msg);
84 }
85
86 static int smtp_check(const char *fmt, int code)
87 {
88         return smtp_checkp(fmt, NULL, code);
89 }
90
91 // strip argument of bad chars
92 static char *sane_address(char *str)
93 {
94         char *s = str;
95         char *p = s;
96         while (*s) {
97                 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
98                         *p++ = *s;
99                 }
100                 s++;
101         }
102         *p = '\0';
103         return str;
104 }
105
106 static void rcptto(const char *s)
107 {
108         // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
109         if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
110                 bb_error_msg("Bad recipient: <%s>", s);
111 }
112
113 int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
114 int sendmail_main(int argc UNUSED_PARAM, char **argv)
115 {
116         char *opt_connect = opt_connect;
117         char *opt_from;
118         char *s;
119         llist_t *list = NULL;
120         char *domain = sane_address(safe_getdomainname());
121         unsigned nheaders = 0;
122         int code;
123
124         enum {
125         //--- standard options
126                 OPT_t = 1 << 0,         // read message for recipients, append them to those on cmdline
127                 OPT_f = 1 << 1,         // sender address
128                 OPT_o = 1 << 2,         // various options. -oi IMPLIED! others are IGNORED!
129                 OPT_i = 1 << 3,         // IMPLIED!
130         //--- BB specific options
131                 OPT_w = 1 << 4,         // network timeout
132                 OPT_H = 1 << 5,         // use external connection helper
133                 OPT_S = 1 << 6,         // specify connection string
134                 OPT_a = 1 << 7,         // authentication tokens
135                 OPT_v = 1 << 8,         // verbosity
136         };
137
138         // init global variables
139         INIT_G();
140
141         // save initial stdin since body is piped!
142         xdup2(STDIN_FILENO, 3);
143         G.fp0 = xfdopen_for_read(3);
144
145         // parse options
146         // -v is a counter, -f is required. -H and -S are mutually exclusive, -a is a list
147         opt_complementary = "vv:f:w+:H--S:S--H:a::";
148         // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
149         // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
150         // it is still under development.
151         opts = getopt32(argv, "tf:o:iw:H:S:a::v", &opt_from, NULL,
152                         &timeout, &opt_connect, &opt_connect, &list, &verbose);
153         //argc -= optind;
154         argv += optind;
155
156         // process -a[upm]<token> options
157         if ((opts & OPT_a) && !list)
158                 bb_show_usage();
159         while (list) {
160                 char *a = (char *) llist_pop(&list);
161                 if ('u' == a[0])
162                         G.user = xstrdup(a+1);
163                 if ('p' == a[0])
164                         G.pass = xstrdup(a+1);
165                 // N.B. we support only AUTH LOGIN so far
166                 //if ('m' == a[0])
167                 //      G.method = xstrdup(a+1);
168         }
169         // N.B. list == NULL here
170         //bb_info_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
171
172         // connect to server
173
174         // connection helper ordered? ->
175         if (opts & OPT_H) {
176                 const char *args[] = { "sh", "-c", opt_connect, NULL };
177                 // plug it in
178                 launch_helper(args);
179         // vanilla connection
180         } else {
181                 int fd;
182                 // host[:port] not explicitly specified? -> use $SMTPHOST
183                 // no $SMTPHOST ? -> use localhost
184                 if (!(opts & OPT_S)) {
185                         opt_connect = getenv("SMTPHOST");
186                         if (!opt_connect)
187                                 opt_connect = (char *)"127.0.0.1";
188                 }
189                 // do connect
190                 fd = create_and_connect_stream_or_die(opt_connect, 25);
191                 // and make ourselves a simple IO filter
192                 xmove_fd(fd, STDIN_FILENO);
193                 xdup2(STDIN_FILENO, STDOUT_FILENO);
194         }
195         // N.B. from now we know nothing about network :)
196
197         // wait for initial server OK
198         // N.B. if we used openssl the initial 220 answer is already swallowed during openssl TLS init procedure
199         // so we need to kick the server to see whether we are ok
200         code = smtp_check("NOOP", -1);
201         // 220 on plain connection, 250 on openssl-helped TLS session
202         if (220 == code)
203                 smtp_check(NULL, 250); // reread the code to stay in sync
204         else if (250 != code)
205                 bb_error_msg_and_die("INIT failed");
206
207         // we should start with modern EHLO
208         if (250 != smtp_checkp("EHLO %s", domain, -1)) {
209                 smtp_checkp("HELO %s", domain, 250);
210         }
211         if (ENABLE_FEATURE_CLEAN_UP)
212                 free(domain);
213
214         // perform authentication
215         if (opts & OPT_a) {
216                 smtp_check("AUTH LOGIN", 334);
217                 // we must read credentials unless they are given via -a[up] options
218                 if (!G.user || !G.pass)
219                         get_cred_or_die(4);
220                 encode_base64(NULL, G.user, NULL);
221                 smtp_check("", 334);
222                 encode_base64(NULL, G.pass, NULL);
223                 smtp_check("", 235);
224         }
225
226         // set sender
227         // N.B. we have here a very loosely defined algotythm
228         // since sendmail historically offers no means to specify secrets on cmdline.
229         // 1) server can require no authentication ->
230         //      we must just provide a (possibly fake) reply address.
231         // 2) server can require AUTH ->
232         //      we must provide valid username and password along with a (possibly fake) reply address.
233         //      For the sake of security username and password are to be read either from console or from a secured file.
234         //      Since reading from console may defeat usability, the solution is either to read from a predefined
235         //      file descriptor (e.g. 4), or again from a secured file.
236
237         // got no sender address? -> use system username as a resort
238         // N.B. we marked -f as required option!
239         //if (!G.user) {
240         //      // N.B. IMHO getenv("USER") can be way easily spoofed!
241         //      G.user = xuid2uname(getuid());
242         //      opt_from = xasprintf("%s@%s", G.user, domain);
243         //}
244         //if (ENABLE_FEATURE_CLEAN_UP)
245         //      free(domain);
246         smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
247
248         // process message
249
250         // read recipients from message and add them to those given on cmdline.
251         // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
252         // and then use the rest of stdin as message body
253         code = 0; // set "analyze headers" mode
254         while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
255  dump:
256                 // put message lines doubling leading dots
257                 if (code) {
258                         // escape leading dots
259                         // N.B. this feature is implied even if no -i (-oi) switch given
260                         // N.B. we need to escape the leading dot regardless of
261                         // whether it is single or not character on the line
262                         if ('.' == s[0] /*&& '\0' == s[1] */)
263                                 printf(".");
264                         // dump read line
265                         send_r_n(s);
266                         free(s);
267                         continue;
268                 }
269
270                 // analyze headers
271                 // To: or Cc: headers add recipients
272                 if (0 == strncasecmp("To:", s, 3) || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
273                         rcptto(sane_address(s+3));
274                         goto addheader;
275                 // Bcc: header adds blind copy (hidden) recipient
276                 } else if (0 == strncasecmp("Bcc:", s, 4)) {
277                         rcptto(sane_address(s+4));
278                         free(s);
279                         // N.B. Bcc: vanishes from headers!
280
281                 // other headers go verbatim
282
283                 // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
284                 // Continuation is denoted by prefixing additional lines with whitespace(s).
285                 // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
286                 } else if (strchr(s, ':') || (list && skip_whitespace(s) != s)) {
287  addheader:
288                         // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
289                         if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
290                                 goto bail;
291                         llist_add_to_end(&list, s);
292                 // a line without ":" (an empty line too, by definition) doesn't look like a valid header
293                 // so stop "analyze headers" mode
294                 } else {
295  reenter:
296                         // put recipients specified on cmdline
297                         while (*argv) {
298                                 char *t = sane_address(*argv);
299                                 rcptto(t);
300                                 //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
301                                 //      goto bail;
302                                 llist_add_to_end(&list, xasprintf("To: %s", t));
303                                 argv++;
304                         }
305                         // enter "put message" mode
306                         // N.B. DATA fails iff no recipients were accepted (or even provided)
307                         // in this case just bail out gracefully
308                         if (354 != smtp_check("DATA", -1))
309                                 goto bail;
310                         // dump the headers
311                         while (list) {
312                                 send_r_n((char *) llist_pop(&list));
313                         }
314                         // stop analyzing headers
315                         code++;
316                         // N.B. !s means: we read nothing, and nothing to be read in the future.
317                         // just dump empty line and break the loop
318                         if (!s) {
319                                 send_r_n("");
320                                 break;
321                         }
322                         // go dump message body
323                         // N.B. "s" already contains the first non-header line, so pretend we read it from input
324                         goto dump;
325                 }
326         }
327         // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
328         // N.B. after reenter code will be > 0
329         if (!code)
330                 goto reenter;
331
332         // finalize the message
333         smtp_check(".", 250);
334  bail:
335         // ... and say goodbye
336         smtp_check("QUIT", 221);
337         // cleanup
338         if (ENABLE_FEATURE_CLEAN_UP)
339                 fclose(G.fp0);
340
341         return EXIT_SUCCESS;
342 }