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: "[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"
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"
38 //usage: "\nOther options are silently ignored; -oi -t is implied"
40 //usage: "\nUse makemime to create emails with attachments"
46 // limit maximum allowed number of headers to prevent overflows.
47 // set to 0 to not limit
48 #define MAX_HEADERS 256
50 static void send_r_n(const char *s)
53 bb_error_msg("send:'%s'", s);
57 static int smtp_checkp(const char *fmt, const char *param, int code)
60 char *msg = send_mail_command(fmt, param);
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) {
69 bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
70 if (strlen(answer) <= 3 || '-' != answer[3])
79 if (-1 == code || n == code) {
84 bb_error_msg_and_die("%s failed", msg);
87 static int smtp_check(const char *fmt, int code)
89 return smtp_checkp(fmt, NULL, code);
92 // strip argument of bad chars
93 static char *sane_address(char *str)
97 int leading_space = 1;
98 int trailing_space = 0;
102 trailing_space = !leading_space;
105 if ((!isalnum(*s) && !strchr("_-.@", *s)) ||
108 bb_error_msg("Bad address: %s", str);
120 static void rcptto(const char *s)
124 // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
125 if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
126 bb_error_msg("Bad recipient: <%s>", s);
129 int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
130 int sendmail_main(int argc UNUSED_PARAM, char **argv)
132 char *opt_connect = opt_connect;
135 llist_t *list = NULL;
136 char *host = sane_address(safe_gethostname());
137 unsigned nheaders = 0;
141 //--- standard options
142 OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
143 OPT_f = 1 << 1, // sender address
144 OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
145 OPT_i = 1 << 3, // IMPLIED!
146 //--- BB specific options
147 OPT_w = 1 << 4, // network timeout
148 OPT_H = 1 << 5, // use external connection helper
149 OPT_S = 1 << 6, // specify connection string
150 OPT_a = 1 << 7, // authentication tokens
151 OPT_v = 1 << 8, // verbosity
154 // init global variables
157 // save initial stdin since body is piped!
158 xdup2(STDIN_FILENO, 3);
159 G.fp0 = xfdopen_for_read(3);
162 // -v is a counter, -f is required. -H and -S are mutually exclusive, -a is a list
163 opt_complementary = "vv:f:w+:H--S:S--H:a::";
164 // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
165 // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
166 // it is still under development.
167 opts = getopt32(argv, "tf:o:iw:H:S:a::v", &opt_from, NULL,
168 &timeout, &opt_connect, &opt_connect, &list, &verbose);
172 // process -a[upm]<token> options
173 if ((opts & OPT_a) && !list)
176 char *a = (char *) llist_pop(&list);
178 G.user = xstrdup(a+1);
180 G.pass = xstrdup(a+1);
181 // N.B. we support only AUTH LOGIN so far
183 // G.method = xstrdup(a+1);
185 // N.B. list == NULL here
186 //bb_info_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
190 // connection helper ordered? ->
192 const char *args[] = { "sh", "-c", opt_connect, NULL };
196 // our stdout will go to helper's stdin,
197 // helper's stdout will be available on our stdin.
199 // Wait for initial server message.
200 // If helper (such as openssl) invokes STARTTLS, the initial 220
201 // is swallowed by helper (and not repeated after TLS is initiated).
202 // We will send NOOP cmd to server and check the response.
203 // We should get 220+250 on plain connection, 250 on STARTTLSed session.
205 // The problem here is some servers delay initial 220 message,
206 // and consider client to be a spammer if it starts sending cmds
207 // before 220 reached it. The code below is unsafe in this regard:
208 // in non-STARTTLSed case, we potentially send NOOP before 220
209 // is sent by server.
210 // Ideas? (--delay SECS opt? --assume-starttls-helper opt?)
211 code = smtp_check("NOOP", -1);
213 // we got 220 - this is not STARTTLSed connection,
214 // eat 250 response to our NOOP
215 smtp_check(NULL, 250);
218 bb_error_msg_and_die("SMTP init failed");
220 // vanilla connection
222 // host[:port] not explicitly specified? -> use $SMTPHOST
223 // no $SMTPHOST? -> use localhost
224 if (!(opts & OPT_S)) {
225 opt_connect = getenv("SMTPHOST");
227 opt_connect = (char *)"127.0.0.1";
230 fd = create_and_connect_stream_or_die(opt_connect, 25);
231 // and make ourselves a simple IO filter
232 xmove_fd(fd, STDIN_FILENO);
233 xdup2(STDIN_FILENO, STDOUT_FILENO);
235 // Wait for initial server 220 message
236 smtp_check(NULL, 220);
239 // we should start with modern EHLO
240 if (250 != smtp_checkp("EHLO %s", host, -1))
241 smtp_checkp("HELO %s", host, 250);
244 // perform authentication
246 smtp_check("AUTH LOGIN", 334);
247 // we must read credentials unless they are given via -a[up] options
248 if (!G.user || !G.pass)
250 encode_base64(NULL, G.user, NULL);
252 encode_base64(NULL, G.pass, NULL);
257 // N.B. we have here a very loosely defined algorythm
258 // since sendmail historically offers no means to specify secrets on cmdline.
259 // 1) server can require no authentication ->
260 // we must just provide a (possibly fake) reply address.
261 // 2) server can require AUTH ->
262 // we must provide valid username and password along with a (possibly fake) reply address.
263 // For the sake of security username and password are to be read either from console or from a secured file.
264 // Since reading from console may defeat usability, the solution is either to read from a predefined
265 // file descriptor (e.g. 4), or again from a secured file.
267 // got no sender address? -> use system username as a resort
268 // N.B. we marked -f as required option!
270 // // N.B. IMHO getenv("USER") can be way easily spoofed!
271 // G.user = xuid2uname(getuid());
272 // opt_from = xasprintf("%s@%s", G.user, domain);
274 smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
278 // read recipients from message and add them to those given on cmdline.
279 // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
280 // and then use the rest of stdin as message body
281 code = 0; // set "analyze headers" mode
282 while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
284 // put message lines doubling leading dots
286 // escape leading dots
287 // N.B. this feature is implied even if no -i (-oi) switch given
288 // N.B. we need to escape the leading dot regardless of
289 // whether it is single or not character on the line
290 if ('.' == s[0] /*&& '\0' == s[1] */)
299 // To: or Cc: headers add recipients
301 if (0 == strncasecmp("To:", s, 3) || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
302 char *r = xstrdup(s+3);
303 rcptto(sane_address(r));
307 // Bcc: header adds blind copy (hidden) recipient
308 if (0 == strncasecmp("Bcc:", s, 4)) {
309 rcptto(sane_address(s+4));
311 continue; // N.B. Bcc: vanishes from headers!
314 if (strchr(s, ':') || (list && isspace(s[0]))) {
315 // other headers go verbatim
316 // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
317 // Continuation is denoted by prefixing additional lines with whitespace(s).
318 // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
320 // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
321 if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
323 llist_add_to_end(&list, s);
325 // a line without ":" (an empty line too, by definition) doesn't look like a valid header
326 // so stop "analyze headers" mode
328 // put recipients specified on cmdline
330 char *t = sane_address(*argv);
332 //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
334 llist_add_to_end(&list, xasprintf("To: %s", t));
337 // enter "put message" mode
338 // N.B. DATA fails iff no recipients were accepted (or even provided)
339 // in this case just bail out gracefully
340 if (354 != smtp_check("DATA", -1))
344 send_r_n((char *) llist_pop(&list));
346 // stop analyzing headers
348 // N.B. !s means: we read nothing, and nothing to be read in the future.
349 // just dump empty line and break the loop
354 // go dump message body
355 // N.B. "s" already contains the first non-header line, so pretend we read it from input
359 // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
360 // N.B. after reenter code will be > 0
364 // finalize the message
365 smtp_check(".", 250);
367 // ... and say goodbye
368 smtp_check("QUIT", 221);
370 if (ENABLE_FEATURE_CLEAN_UP)