blob: 4f73512e99402f0014a8a679ad9fd5730e94b273 [file] [log] [blame]
Denis Vlasenko239d06b2008-11-06 23:42:42 +00001/* vi: set sw=4 ts=4: */
2/*
3 * bare bones sendmail
4 *
5 * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02007 * Licensed under GPLv2, see file LICENSE in this source tree.
Denis Vlasenko239d06b2008-11-06 23:42:42 +00008 */
Denys Vlasenko5707b522010-12-20 05:12:39 +01009
Denys Vlasenkod616ab62011-05-22 03:46:33 +020010//kbuild:lib-$(CONFIG_SENDMAIL) += sendmail.o mail.o
11
Denys Vlasenko5707b522010-12-20 05:12:39 +010012//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"
Denys Vlasenko34c469a2011-09-18 03:01:49 +020029//usage: "\n [4<username_and_passwd.txt | -auUSER -apPASS]"
Denys Vlasenko5707b522010-12-20 05:12:39 +010030//usage: "\n -H 'exec openssl s_client -quiet -tls1"
31//usage: "\n -connect smtp.gmail.com:465' <email.txt"
Denys Vlasenko34c469a2011-09-18 03:01:49 +020032//usage: "\n [4<username_and_passwd.txt | -auUSER -apPASS]"
Denys Vlasenko5707b522010-12-20 05:12:39 +010033//usage: "\n -S HOST[:PORT] Server"
Denys Vlasenko34c469a2011-09-18 03:01:49 +020034//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"
Denys Vlasenko5707b522010-12-20 05:12:39 +010037//usage: "\n"
38//usage: "\nOther options are silently ignored; -oi -t is implied"
39//usage: IF_MAKEMIME(
Denys Vlasenko34c469a2011-09-18 03:01:49 +020040//usage: "\nUse makemime to create emails with attachments"
Denys Vlasenko5707b522010-12-20 05:12:39 +010041//usage: )
42
Denis Vlasenko239d06b2008-11-06 23:42:42 +000043#include "libbb.h"
44#include "mail.h"
45
Vladimir Dronnikov944d2752009-10-15 23:50:48 +020046// limit maximum allowed number of headers to prevent overflows.
47// set to 0 to not limit
48#define MAX_HEADERS 256
49
Denys Vlasenko5707b522010-12-20 05:12:39 +010050static 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
Denis Vlasenko239d06b2008-11-06 23:42:42 +000057static int smtp_checkp(const char *fmt, const char *param, int code)
58{
59 char *answer;
Denys Vlasenko5707b522010-12-20 05:12:39 +010060 char *msg = send_mail_command(fmt, param);
Denis Vlasenko239d06b2008-11-06 23:42:42 +000061 // read stdin
Denys Vlasenko5707b522010-12-20 05:12:39 +010062 // if the string has a form NNN- -- read next string. E.g. EHLO response
Denis Vlasenko239d06b2008-11-06 23:42:42 +000063 // 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
Denys Vlasenko5707b522010-12-20 05:12:39 +010067 while ((answer = xmalloc_fgetline(stdin)) != NULL) {
Denys Vlasenko51d714c2010-12-20 12:19:46 +010068 if (verbose)
Denys Vlasenko34c469a2011-09-18 03:01:49 +020069 bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
Denis Vlasenko239d06b2008-11-06 23:42:42 +000070 if (strlen(answer) <= 3 || '-' != answer[3])
71 break;
Denys Vlasenko5707b522010-12-20 05:12:39 +010072 free(answer);
73 }
Denis Vlasenko239d06b2008-11-06 23:42:42 +000074 if (answer) {
75 int n = atoi(answer);
76 if (timeout)
77 alarm(0);
78 free(answer);
Denys Vlasenko34c469a2011-09-18 03:01:49 +020079 if (-1 == code || n == code) {
80 free(msg);
Denis Vlasenko239d06b2008-11-06 23:42:42 +000081 return n;
Denys Vlasenko34c469a2011-09-18 03:01:49 +020082 }
Denis Vlasenko239d06b2008-11-06 23:42:42 +000083 }
84 bb_error_msg_and_die("%s failed", msg);
85}
86
87static int smtp_check(const char *fmt, int code)
88{
89 return smtp_checkp(fmt, NULL, code);
90}
91
92// strip argument of bad chars
93static char *sane_address(char *str)
94{
95 char *s = str;
96 char *p = s;
Aaro Koskinen14285d12013-02-25 00:45:06 +020097 int leading_space = 1;
98 int trailing_space = 0;
99
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000100 while (*s) {
Aaro Koskinen14285d12013-02-25 00:45:06 +0200101 if (isspace(*s)) {
102 trailing_space = !leading_space;
103 } else {
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000104 *p++ = *s;
Aaro Koskinen14285d12013-02-25 00:45:06 +0200105 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;
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000113 }
114 s++;
115 }
116 *p = '\0';
117 return str;
118}
119
120static void rcptto(const char *s)
121{
Aaro Koskinen14285d12013-02-25 00:45:06 +0200122 if (!*s)
123 return;
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200124 // 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);
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000127}
128
129int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
130int sendmail_main(int argc UNUSED_PARAM, char **argv)
131{
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000132 char *opt_connect = opt_connect;
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000133 char *opt_from;
134 char *s;
135 llist_t *list = NULL;
Ron Yorston576b1d32012-04-28 17:04:19 +0200136 char *host = sane_address(safe_gethostname());
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200137 unsigned nheaders = 0;
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000138 int code;
139
140 enum {
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000141 //--- 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!
Vladimir Dronnikovb618dba2009-10-04 01:34:54 +0200145 OPT_i = 1 << 3, // IMPLIED!
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000146 //--- BB specific options
Vladimir Dronnikovb618dba2009-10-04 01:34:54 +0200147 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
Denys Vlasenko5707b522010-12-20 05:12:39 +0100151 OPT_v = 1 << 8, // verbosity
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000152 };
153
154 // init global variables
155 INIT_G();
156
157 // save initial stdin since body is piped!
158 xdup2(STDIN_FILENO, 3);
Denys Vlasenkoa7ccdee2009-11-15 23:28:11 +0100159 G.fp0 = xfdopen_for_read(3);
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000160
161 // parse options
Denys Vlasenko5707b522010-12-20 05:12:39 +0100162 // -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::";
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000164 // 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.
Denys Vlasenko5707b522010-12-20 05:12:39 +0100167 opts = getopt32(argv, "tf:o:iw:H:S:a::v", &opt_from, NULL,
168 &timeout, &opt_connect, &opt_connect, &list, &verbose);
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000169 //argc -= optind;
170 argv += optind;
171
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000172 // process -a[upm]<token> options
173 if ((opts & OPT_a) && !list)
174 bb_show_usage();
175 while (list) {
176 char *a = (char *) llist_pop(&list);
177 if ('u' == a[0])
178 G.user = xstrdup(a+1);
179 if ('p' == a[0])
180 G.pass = xstrdup(a+1);
181 // N.B. we support only AUTH LOGIN so far
182 //if ('m' == a[0])
183 // G.method = xstrdup(a+1);
184 }
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);
187
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000188 // connect to server
189
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000190 // connection helper ordered? ->
191 if (opts & OPT_H) {
192 const char *args[] = { "sh", "-c", opt_connect, NULL };
193 // plug it in
194 launch_helper(args);
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200195 // Now:
196 // our stdout will go to helper's stdin,
197 // helper's stdout will be available on our stdin.
198
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.
204 //
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);
212 if (code == 220)
213 // we got 220 - this is not STARTTLSed connection,
214 // eat 250 response to our NOOP
215 smtp_check(NULL, 250);
216 else
217 if (code != 250)
218 bb_error_msg_and_die("SMTP init failed");
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000219 } else {
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200220 // vanilla connection
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000221 int fd;
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000222 // host[:port] not explicitly specified? -> use $SMTPHOST
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200223 // no $SMTPHOST? -> use localhost
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000224 if (!(opts & OPT_S)) {
225 opt_connect = getenv("SMTPHOST");
226 if (!opt_connect)
227 opt_connect = (char *)"127.0.0.1";
228 }
229 // do connect
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);
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000234
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200235 // Wait for initial server 220 message
236 smtp_check(NULL, 220);
237 }
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000238
239 // we should start with modern EHLO
Ron Yorston576b1d32012-04-28 17:04:19 +0200240 if (250 != smtp_checkp("EHLO %s", host, -1))
241 smtp_checkp("HELO %s", host, 250);
242 free(host);
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000243
244 // perform authentication
245 if (opts & OPT_a) {
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)
249 get_cred_or_die(4);
250 encode_base64(NULL, G.user, NULL);
251 smtp_check("", 334);
252 encode_base64(NULL, G.pass, NULL);
253 smtp_check("", 235);
254 }
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000255
256 // set sender
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200257 // N.B. we have here a very loosely defined algorythm
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000258 // 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.
266
267 // got no sender address? -> use system username as a resort
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000268 // N.B. we marked -f as required option!
269 //if (!G.user) {
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);
273 //}
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000274 smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000275
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000276 // process message
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000277
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000278 // 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) {
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200283 dump:
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000284 // put message lines doubling leading dots
285 if (code) {
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000286 // 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] */)
291 printf(".");
292 // dump read line
Denys Vlasenko5707b522010-12-20 05:12:39 +0100293 send_r_n(s);
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000294 free(s);
295 continue;
296 }
297
298 // analyze headers
299 // To: or Cc: headers add recipients
Denys Vlasenko41fea012011-11-18 22:25:35 +0100300 if (opts & OPT_t) {
301 if (0 == strncasecmp("To:", s, 3) || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
302 rcptto(sane_address(s+3));
303 goto addheader;
304 }
305 // Bcc: header adds blind copy (hidden) recipient
306 if (0 == strncasecmp("Bcc:", s, 4)) {
307 rcptto(sane_address(s+4));
308 free(s);
309 continue; // N.B. Bcc: vanishes from headers!
310 }
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200311 }
Denys Vlasenko578b8172011-11-19 13:54:50 +0100312 if (strchr(s, ':') || (list && isspace(s[0]))) {
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200313 // other headers go verbatim
314 // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
315 // Continuation is denoted by prefixing additional lines with whitespace(s).
316 // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200317 addheader:
Vladimir Dronnikov8dbe9bb2009-10-17 03:35:10 +0200318 // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200319 if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
320 goto bail;
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000321 llist_add_to_end(&list, s);
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000322 } else {
Denys Vlasenko34c469a2011-09-18 03:01:49 +0200323 // a line without ":" (an empty line too, by definition) doesn't look like a valid header
324 // so stop "analyze headers" mode
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200325 reenter:
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000326 // put recipients specified on cmdline
327 while (*argv) {
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200328 char *t = sane_address(*argv);
329 rcptto(t);
330 //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
331 // goto bail;
332 llist_add_to_end(&list, xasprintf("To: %s", t));
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000333 argv++;
334 }
335 // enter "put message" mode
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200336 // N.B. DATA fails iff no recipients were accepted (or even provided)
337 // in this case just bail out gracefully
338 if (354 != smtp_check("DATA", -1))
339 goto bail;
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000340 // dump the headers
341 while (list) {
Denys Vlasenko5707b522010-12-20 05:12:39 +0100342 send_r_n((char *) llist_pop(&list));
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000343 }
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000344 // stop analyzing headers
345 code++;
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200346 // N.B. !s means: we read nothing, and nothing to be read in the future.
347 // just dump empty line and break the loop
348 if (!s) {
Denys Vlasenko5707b522010-12-20 05:12:39 +0100349 send_r_n("");
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200350 break;
351 }
352 // go dump message body
353 // N.B. "s" already contains the first non-header line, so pretend we read it from input
354 goto dump;
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000355 }
356 }
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200357 // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
358 // N.B. after reenter code will be > 0
359 if (!code)
360 goto reenter;
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000361
Denis Vlasenko88b8f0a2009-03-31 23:41:53 +0000362 // finalize the message
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000363 smtp_check(".", 250);
Vladimir Dronnikov944d2752009-10-15 23:50:48 +0200364 bail:
Denis Vlasenko239d06b2008-11-06 23:42:42 +0000365 // ... and say goodbye
366 smtp_check("QUIT", 221);
367 // cleanup
368 if (ENABLE_FEATURE_CLEAN_UP)
369 fclose(G.fp0);
370
371 return EXIT_SUCCESS;
372}