1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
7 * Licensed under GPLv2, see file LICENSE in this source tree.
10 //kbuild:lib-$(CONFIG_SENDMAIL) += sendmail.o mail.o
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"
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"
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."
40 //usage: "\nUse makemime to create emails with attachments."
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!
46 * From http://cr.yp.to/smtp/address.html:
48 * SMTP offers three ways to encode a character inside an address:
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,
54 * "slashed": backslash followed by the character.
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.
61 * For example, the encoded box parts
67 * all represent the 6-byte string "angels", and the encoded box parts
71 * all represent the 7-byte string "a,comma".
73 * An encoded address contains
75 * optionally, a route followed by a colon;
76 * an encoded box part, the byte @, and a domain; and
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
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".
92 // limit maximum allowed number of headers to prevent overflows.
93 // set to 0 to not limit
94 #define MAX_HEADERS 256
96 static void send_r_n(const char *s)
99 bb_error_msg("send:'%s'", s);
103 static int smtp_checkp(const char *fmt, const char *param, int code)
106 char *msg = send_mail_command(fmt, param);
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) {
115 bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
116 if (strlen(answer) <= 3 || '-' != answer[3])
121 int n = atoi(answer);
125 if (-1 == code || n == code) {
130 bb_error_msg_and_die("%s failed", msg);
133 static int smtp_check(const char *fmt, int code)
135 return smtp_checkp(fmt, NULL, code);
138 // strip argument of bad chars
139 static char *sane_address(char *str)
146 if (!isalnum(*s) && !strchr("_-.@", *s)) {
147 bb_error_msg("bad address '%s'", str);
157 // check for an address inside angle brackets, if not found fall back to normal
158 static char *angle_address(char *str)
163 e = last_char_is(str, '>');
165 s = strrchr(str, '<');
171 return sane_address(str);
174 static void rcptto(const char *s)
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);
183 // send to a list of comma separated addresses
184 static void rcptto_list(const char *list)
186 char *str = xstrdup(list);
194 if (ch == '"' && prev != '\\') {
195 in_quote = !in_quote;
196 } else if (!in_quote && ch == ',') {
198 rcptto(angle_address(str));
204 rcptto(angle_address(str));
208 int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
209 int sendmail_main(int argc UNUSED_PARAM, char **argv)
212 char *opt_from = NULL;
214 llist_t *list = NULL;
215 char *host = sane_address(safe_gethostname());
216 unsigned nheaders = 0;
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
240 // init global variables
243 // default HOST[:PORT] is $SMTPHOST, or localhost
244 opt_connect = getenv("SMTPHOST");
246 opt_connect = (char *)"127.0.0.1";
248 // save initial stdin since body is piped!
249 xdup2(STDIN_FILENO, 3);
250 G.fp0 = xfdopen_for_read(3);
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);
263 // process -a[upm]<token> options
264 if ((opts & OPT_a) && !list)
267 char *a = (char *) llist_pop(&list);
269 G.user = xstrdup(a+1);
271 G.pass = xstrdup(a+1);
272 // N.B. we support only AUTH LOGIN so far
274 // G.method = xstrdup(a+1);
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);
281 // connection helper ordered? ->
284 const char *args[] = { "sh", "-c", opt_connect, NULL };
288 // our stdout will go to helper's stdin,
289 // helper's stdout will be available on our stdin.
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.
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.
303 // If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
305 delay = getenv("SMTP_ANTISPAM_DELAY");
308 code = smtp_check("NOOP", -1);
310 // we got 220 - this is not STARTTLSed connection,
311 // eat 250 response to our NOOP
312 smtp_check(NULL, 250);
315 bb_error_msg_and_die("SMTP init failed");
317 // vanilla connection
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);
324 // Wait for initial server 220 message
325 smtp_check(NULL, 220);
328 // we should start with modern EHLO
329 if (250 != smtp_checkp("EHLO %s", host, -1))
330 smtp_checkp("HELO %s", host, 250);
332 // perform authentication
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)
338 encode_base64(NULL, G.user, NULL);
340 encode_base64(NULL, G.pass, NULL);
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.
355 // got no sender address? use auth name, then UID username as a last resort
357 opt_from = xasprintf("%s@%s",
358 G.user ? G.user : xuid2uname(getuid()),
359 xgethostbyname(host)->h_name);
363 smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
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) {
373 // put message lines doubling leading dots
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] */)
388 // To: or Cc: headers add recipients
389 check_hdr = (0 == strncasecmp("To:", s, 3));
392 if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
397 // Bcc: header adds blind copy (hidden) recipient
398 if (0 == strncasecmp("Bcc:", s, 4)) {
402 continue; // N.B. Bcc: vanishes from headers!
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) {
413 if (last_hdr == HDR_BCC)
415 // N.B. Bcc: vanishes from headers!
417 last_hdr = HDR_OTHER;
420 // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
421 if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
423 llist_add_to_end(&list, s);
425 // a line without ":" (an empty line too, by definition) doesn't look like a valid header
426 // so stop "analyze headers" mode
428 // put recipients specified on cmdline
431 char *t = sane_address(*argv);
433 //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
438 if (check_hdr && argv[1])
446 llist_add_to_end(&list,
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))
459 send_r_n((char *) llist_pop(&list));
461 // stop analyzing headers
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
469 // go dump message body
470 // N.B. "s" already contains the first non-header line, so pretend we read it from input
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
479 // finalize the message
480 smtp_check(".", 250);
482 // ... and say goodbye
483 smtp_check("QUIT", 221);
485 if (ENABLE_FEATURE_CLEAN_UP)