busybox/mailutils/sendmail.c

507 lines
15 KiB
C
Raw Normal View History

2008-11-07 05:12:42 +05:30
/* vi: set sw=4 ts=4: */
/*
* bare bones sendmail
*
* Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
2008-11-07 05:12:42 +05:30
*/
//config:config SENDMAIL
//config: bool "sendmail (14 kb)"
//config: default y
//config: help
//config: Barebones sendmail.
//applet:IF_SENDMAIL(APPLET(sendmail, BB_DIR_USR_SBIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_SENDMAIL) += sendmail.o mail.o
//usage:#define sendmail_trivial_usage
//usage: "[-tv] [-f SENDER] [-amLOGIN 4<user_pass.txt | -auUSER -apPASS]"
//usage: "\n [-w SECS] [-H 'PROG ARGS' | -S HOST] [RECIPIENT_EMAIL]..."
//usage:#define sendmail_full_usage "\n\n"
//usage: "Read email from stdin and send it\n"
//usage: "\nStandard options:"
//usage: "\n -t Read additional recipients from message body"
//usage: "\n -f SENDER For use in MAIL FROM:<sender>. Can be empty string"
//usage: "\n Default: -auUSER, or username of current UID"
//usage: "\n -o OPTIONS Various options. -oi implied, others are ignored"
//usage: "\n -i -oi synonym, implied and ignored"
//usage: "\n"
//usage: "\nBusybox specific options:"
//usage: "\n -v Verbose"
//usage: "\n -w SECS Network timeout"
//usage: "\n -H 'PROG ARGS' Run connection helper. Examples:"
//usage: "\n openssl s_client -quiet -tls1 -starttls smtp -connect smtp.gmail.com:25"
//usage: "\n openssl s_client -quiet -tls1 -connect smtp.gmail.com:465"
//usage: "\n $SMTP_ANTISPAM_DELAY: seconds to wait after helper connect"
//usage: "\n -S HOST[:PORT] Server (default $SMTPHOST or 127.0.0.1)"
//usage: "\n -amLOGIN Log in using AUTH LOGIN (-amCRAM-MD5 not supported)"
//usage: "\n -auUSER Username for AUTH"
//usage: "\n -apPASS Password for AUTH"
//usage: "\n"
//usage: "\nIf no -a options are given, authentication is not done."
//usage: "\nIf -amLOGIN is given but no -au/-ap, user/password is read from fd #4."
//usage: "\nOther options are silently ignored; -oi is implied."
//usage: IF_MAKEMIME(
//usage: "\nUse makemime to create emails with attachments."
//usage: )
/* Currently we don't sanitize or escape user-supplied SENDER and RECIPIENT_EMAILs.
* We may need to do so. For one, '.' in usernames seems to require escaping!
*
* From http://cr.yp.to/smtp/address.html:
*
* SMTP offers three ways to encode a character inside an address:
*
* "safe": the character, if it is not <>()[].,;:@, backslash,
* double-quote, space, or an ASCII control character;
* "quoted": the character, if it is not \012, \015, backslash,
* or double-quote; or
* "slashed": backslash followed by the character.
*
* An encoded box part is either (1) a sequence of one or more slashed
* or safe characters or (2) a double quote, a sequence of zero or more
* slashed or quoted characters, and a double quote. It represents
* the concatenation of the characters encoded inside it.
*
* For example, the encoded box parts
* angels
* \a\n\g\e\l\s
* "\a\n\g\e\l\s"
* "angels"
* "ang\els"
* all represent the 6-byte string "angels", and the encoded box parts
* a\,comma
* \a\,\c\o\m\m\a
* "a,comma"
* all represent the 7-byte string "a,comma".
*
* An encoded address contains
* the byte <;
* optionally, a route followed by a colon;
* an encoded box part, the byte @, and a domain; and
* the byte >.
*
* It represents an Internet mail address, given by concatenating
* the string represented by the encoded box part, the byte @,
* and the domain. For example, the encoded addresses
* <God@heaven.af.mil>
* <\God@heaven.af.mil>
* <"God"@heaven.af.mil>
* <@gateway.af.mil,@uucp.local:"\G\o\d"@heaven.af.mil>
* all represent the Internet mail address "God@heaven.af.mil".
*/
2008-11-07 05:12:42 +05:30
#include "libbb.h"
#include "mail.h"
// limit maximum allowed number of headers to prevent overflows.
// set to 0 to not limit
#define MAX_HEADERS 256
static void send_r_n(const char *s)
{
if (verbose)
bb_error_msg("send:'%s'", s);
printf("%s\r\n", s);
}
2008-11-07 05:12:42 +05:30
static int smtp_checkp(const char *fmt, const char *param, int code)
{
char *answer;
char *msg = send_mail_command(fmt, param);
2008-11-07 05:12:42 +05:30
// read stdin
// if the string has a form NNN- -- read next string. E.g. EHLO response
2008-11-07 05:12:42 +05:30
// parse first bytes to a number
// if code = -1 then just return this number
// if code != -1 then checks whether the number equals the code
// if not equal -> die saying msg
while ((answer = xmalloc_fgetline(stdin)) != NULL) {
if (verbose)
bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
2008-11-07 05:12:42 +05:30
if (strlen(answer) <= 3 || '-' != answer[3])
break;
free(answer);
}
2008-11-07 05:12:42 +05:30
if (answer) {
int n = atoi(answer);
if (timeout)
alarm(0);
free(answer);
if (-1 == code || n == code) {
free(msg);
2008-11-07 05:12:42 +05:30
return n;
}
2008-11-07 05:12:42 +05:30
}
bb_error_msg_and_die("%s failed", msg);
}
static int smtp_check(const char *fmt, int code)
{
return smtp_checkp(fmt, NULL, code);
}
// strip argument of bad chars
static char *sane_address(char *str)
{
char *s;
trim(str);
s = str;
2008-11-07 05:12:42 +05:30
while (*s) {
/* Standard allows these chars in username without quoting:
* /!#$%&'*+-=?^_`{|}~
* and allows dot (.) with some restrictions.
* I chose to only allow a saner subset.
* I propose to expand it only on user's request.
*/
if (!isalnum(*s) && !strchr("=+_-.@", *s)) {
bb_error_msg("bad address '%s'", str);
/* returning "": */
str[0] = '\0';
return str;
2008-11-07 05:12:42 +05:30
}
s++;
}
return str;
}
// check for an address inside angle brackets, if not found fall back to normal
static char *angle_address(char *str)
{
char *s, *e;
e = trim(str);
if (e != str && *--e == '>') {
s = strrchr(str, '<');
if (s) {
*e = '\0';
str = s + 1;
}
}
return sane_address(str);
}
2008-11-07 05:12:42 +05:30
static void rcptto(const char *s)
{
if (!*s)
return;
// N.B. we don't die if recipient is rejected, for the other recipients may be accepted
if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
bb_error_msg("Bad recipient: <%s>", s);
2008-11-07 05:12:42 +05:30
}
// send to a list of comma separated addresses
static void rcptto_list(const char *list)
{
char *free_me = xstrdup(list);
char *str = free_me;
char *s = free_me;
char prev = 0;
int in_quote = 0;
while (*s) {
char ch = *s++;
if (ch == '"' && prev != '\\') {
in_quote = !in_quote;
} else if (!in_quote && ch == ',') {
s[-1] = '\0';
rcptto(angle_address(str));
str = s;
}
prev = ch;
}
if (prev != ',')
rcptto(angle_address(str));
free(free_me);
}
2008-11-07 05:12:42 +05:30
int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sendmail_main(int argc UNUSED_PARAM, char **argv)
{
char *opt_connect;
char *opt_from = NULL;
char *s;
llist_t *list = NULL;
char *host = sane_address(safe_gethostname());
unsigned nheaders = 0;
2008-11-07 05:12:42 +05:30
int code;
enum {
HDR_OTHER = 0,
HDR_TOCC,
HDR_BCC,
} last_hdr = 0;
int check_hdr;
int has_to = 0;
2008-11-07 05:12:42 +05:30
enum {
//--- standard options
OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
OPT_f = 1 << 1, // sender address
OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
OPT_i = 1 << 3, // IMPLIED!
//--- BB specific options
OPT_w = 1 << 4, // network timeout
OPT_H = 1 << 5, // use external connection helper
OPT_S = 1 << 6, // specify connection string
OPT_a = 1 << 7, // authentication tokens
OPT_v = 1 << 8, // verbosity
2008-11-07 05:12:42 +05:30
};
// init global variables
INIT_G();
// default HOST[:PORT] is $SMTPHOST, or localhost
opt_connect = getenv("SMTPHOST");
if (!opt_connect)
opt_connect = (char *)"127.0.0.1";
2008-11-07 05:12:42 +05:30
// save initial stdin since body is piped!
xdup2(STDIN_FILENO, 3);
G.fp0 = xfdopen_for_read(3);
2008-11-07 05:12:42 +05:30
// parse options
// N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
// -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
// it is still under development.
getopt32: remove opt_complementary function old new delta vgetopt32 1318 1392 +74 runsvdir_main 703 713 +10 bb_make_directory 423 425 +2 collect_cpu 546 545 -1 opt_chars 3 - -3 opt_complementary 4 - -4 tftpd_main 567 562 -5 ntp_init 476 471 -5 zcip_main 1266 1256 -10 xxd_main 428 418 -10 whois_main 140 130 -10 who_main 463 453 -10 which_main 212 202 -10 wget_main 2535 2525 -10 watchdog_main 291 281 -10 watch_main 222 212 -10 vlock_main 399 389 -10 uuencode_main 332 322 -10 uudecode_main 316 306 -10 unlink_main 45 35 -10 udhcpd_main 1482 1472 -10 udhcpc_main 2762 2752 -10 tune2fs_main 290 280 -10 tunctl_main 366 356 -10 truncate_main 218 208 -10 tr_main 518 508 -10 time_main 1134 1124 -10 tftp_main 286 276 -10 telnetd_main 1873 1863 -10 tcpudpsvd_main 1785 1775 -10 taskset_main 521 511 -10 tar_main 1009 999 -10 tail_main 1644 1634 -10 syslogd_main 1967 1957 -10 switch_root_main 368 358 -10 svlogd_main 1454 1444 -10 sv 1296 1286 -10 stat_main 104 94 -10 start_stop_daemon_main 1028 1018 -10 split_main 542 532 -10 sort_main 796 786 -10 slattach_main 624 614 -10 shuf_main 504 494 -10 setsid_main 96 86 -10 setserial_main 1132 1122 -10 setfont_main 388 378 -10 setconsole_main 78 68 -10 sendmail_main 1209 1199 -10 sed_main 677 667 -10 script_main 1077 1067 -10 run_parts_main 325 315 -10 rtcwake_main 454 444 -10 rm_main 175 165 -10 reformime_main 119 109 -10 readlink_main 123 113 -10 rdate_main 246 236 -10 pwdx_main 189 179 -10 pstree_main 317 307 -10 pscan_main 663 653 -10 popmaildir_main 818 808 -10 pmap_main 80 70 -10 nc_main 1042 1032 -10 mv_main 558 548 -10 mountpoint_main 477 467 -10 mount_main 1264 1254 -10 modprobe_main 768 758 -10 modinfo_main 333 323 -10 mktemp_main 200 190 -10 mkswap_main 324 314 -10 mkfs_vfat_main 1489 1479 -10 microcom_main 715 705 -10 md5_sha1_sum_main 521 511 -10 man_main 867 857 -10 makedevs_main 1052 1042 -10 ls_main 563 553 -10 losetup_main 432 422 -10 loadfont_main 89 79 -10 ln_main 524 514 -10 link_main 75 65 -10 ipcalc_main 544 534 -10 iostat_main 2397 2387 -10 install_main 768 758 -10 id_main 480 470 -10 i2cset_main 1239 1229 -10 i2cget_main 380 370 -10 i2cdump_main 1482 1472 -10 i2cdetect_main 682 672 -10 hwclock_main 406 396 -10 httpd_main 741 731 -10 grep_main 837 827 -10 getty_main 1559 1549 -10 fuser_main 297 287 -10 ftpgetput_main 345 335 -10 ftpd_main 2232 2222 -10 fstrim_main 251 241 -10 fsfreeze_main 77 67 -10 fsck_minix_main 2921 2911 -10 flock_main 314 304 -10 flashcp_main 740 730 -10 flash_eraseall_main 833 823 -10 fdformat_main 532 522 -10 expand_main 680 670 -10 eject_main 335 325 -10 dumpleases_main 630 620 -10 du_main 314 304 -10 dos2unix_main 441 431 -10 diff_main 1350 1340 -10 df_main 1064 1054 -10 date_main 1095 1085 -10 cut_main 961 951 -10 cryptpw_main 228 218 -10 crontab_main 575 565 -10 crond_main 1149 1139 -10 cp_main 370 360 -10 common_traceroute_main 3834 3824 -10 common_ping_main 1767 1757 -10 comm_main 239 229 -10 cmp_main 655 645 -10 chrt_main 379 369 -10 chpst_main 704 694 -10 chpasswd_main 308 298 -10 chown_main 171 161 -10 chmod_main 158 148 -10 cat_main 428 418 -10 bzip2_main 120 110 -10 blkdiscard_main 264 254 -10 base64_main 221 211 -10 arping_main 1665 1655 -10 ar_main 556 546 -10 adjtimex_main 406 396 -10 adduser_main 882 872 -10 addgroup_main 411 401 -10 acpid_main 1198 1188 -10 optstring 11 - -11 opt_string 18 - -18 OPT_STR 25 - -25 ubi_tools_main 1288 1258 -30 ls_options 31 - -31 ------------------------------------------------------------------------------ (add/remove: 0/6 grow/shrink: 3/129 up/down: 86/-1383) Total: -1297 bytes text data bss dec hex filename 915428 485 6876 922789 e14a5 busybox_old 914629 485 6872 921986 e1182 busybox_unstripped Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2017-08-09 01:25:02 +05:30
opts = getopt32(argv, "^"
"tf:o:iw:+H:S:a:*:v"
"\0"
// -v is a counter, -H and -S are mutually exclusive, -a is a list
"vv:H--S:S--H",
&opt_from, NULL,
&timeout, &opt_connect, &opt_connect, &list, &verbose
);
2008-11-07 05:12:42 +05:30
//argc -= optind;
argv += optind;
// process -a[upm]<token> options
if ((opts & OPT_a) && !list)
bb_show_usage();
while (list) {
char *a = (char *) llist_pop(&list);
if ('u' == a[0])
G.user = xstrdup(a+1);
if ('p' == a[0])
G.pass = xstrdup(a+1);
// N.B. we support only AUTH LOGIN so far
//if ('m' == a[0])
// G.method = xstrdup(a+1);
}
// N.B. list == NULL here
//bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
2008-11-07 05:12:42 +05:30
// connect to server
// connection helper ordered? ->
if (opts & OPT_H) {
const char *delay;
2008-11-07 05:12:42 +05:30
const char *args[] = { "sh", "-c", opt_connect, NULL };
// plug it in
launch_helper(args);
// Now:
// our stdout will go to helper's stdin,
// helper's stdout will be available on our stdin.
// Wait for initial server message.
// If helper (such as openssl) invokes STARTTLS, the initial 220
// is swallowed by helper (and not repeated after TLS is initiated).
// We will send NOOP cmd to server and check the response.
// We should get 220+250 on plain connection, 250 on STARTTLSed session.
//
// The problem here is some servers delay initial 220 message,
// and consider client to be a spammer if it starts sending cmds
// before 220 reached it. The code below is unsafe in this regard:
// in non-STARTTLSed case, we potentially send NOOP before 220
// is sent by server.
//
// If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
//
delay = getenv("SMTP_ANTISPAM_DELAY");
if (delay)
sleep(atoi(delay));
code = smtp_check("NOOP", -1);
if (code == 220)
// we got 220 - this is not STARTTLSed connection,
// eat 250 response to our NOOP
smtp_check(NULL, 250);
else
if (code != 250)
bb_error_msg_and_die("SMTP init failed");
} else {
// vanilla connection
2008-11-07 05:12:42 +05:30
int fd;
fd = create_and_connect_stream_or_die(opt_connect, 25);
// and make ourselves a simple IO filter
xmove_fd(fd, STDIN_FILENO);
xdup2(STDIN_FILENO, STDOUT_FILENO);
// Wait for initial server 220 message
smtp_check(NULL, 220);
}
2008-11-07 05:12:42 +05:30
// we should start with modern EHLO
if (250 != smtp_checkp("EHLO %s", host, -1))
smtp_checkp("HELO %s", host, 250);
// perform authentication
if (opts & OPT_a) {
smtp_check("AUTH LOGIN", 334);
// we must read credentials unless they are given via -a[up] options
if (!G.user || !G.pass)
get_cred_or_die(4);
encode_base64(NULL, G.user, NULL);
smtp_check("", 334);
encode_base64(NULL, G.pass, NULL);
smtp_check("", 235);
}
2008-11-07 05:12:42 +05:30
// set sender
// N.B. we have here a very loosely defined algorythm
2008-11-07 05:12:42 +05:30
// since sendmail historically offers no means to specify secrets on cmdline.
// 1) server can require no authentication ->
// we must just provide a (possibly fake) reply address.
// 2) server can require AUTH ->
// we must provide valid username and password along with a (possibly fake) reply address.
// For the sake of security username and password are to be read either from console or from a secured file.
// Since reading from console may defeat usability, the solution is either to read from a predefined
// file descriptor (e.g. 4), or again from a secured file.
// got no sender address? use auth name, then UID username as a last resort
if (!opt_from) {
opt_from = xasprintf("%s@%s",
G.user ? G.user : xuid2uname(getuid()),
xgethostbyname(host)->h_name);
}
free(host);
smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
// process message
// read recipients from message and add them to those given on cmdline.
// this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
// and then use the rest of stdin as message body
code = 0; // set "analyze headers" mode
while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
dump:
// put message lines doubling leading dots
if (code) {
2008-11-07 05:12:42 +05:30
// escape leading dots
// N.B. this feature is implied even if no -i (-oi) switch given
// N.B. we need to escape the leading dot regardless of
// whether it is single or not character on the line
if ('.' == s[0] /*&& '\0' == s[1] */)
bb_putchar('.');
2008-11-07 05:12:42 +05:30
// dump read line
send_r_n(s);
free(s);
continue;
}
// analyze headers
// To: or Cc: headers add recipients
check_hdr = (0 == strncasecmp("To:", s, 3));
has_to |= check_hdr;
if (opts & OPT_t) {
if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
rcptto_list(s+3);
last_hdr = HDR_TOCC;
goto addheader;
}
// Bcc: header adds blind copy (hidden) recipient
if (0 == strncasecmp("Bcc:", s, 4)) {
rcptto_list(s+4);
free(s);
last_hdr = HDR_BCC;
continue; // N.B. Bcc: vanishes from headers!
}
}
check_hdr = (list && isspace(s[0]));
if (strchr(s, ':') || check_hdr) {
// other headers go verbatim
// N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
// Continuation is denoted by prefixing additional lines with whitespace(s).
// Thanks (stefan.seyfried at googlemail.com) for pointing this out.
if (check_hdr && last_hdr != HDR_OTHER) {
rcptto_list(s+1);
if (last_hdr == HDR_BCC)
continue;
// N.B. Bcc: vanishes from headers!
} else {
last_hdr = HDR_OTHER;
}
addheader:
// N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
goto bail;
llist_add_to_end(&list, s);
} else {
// a line without ":" (an empty line too, by definition) doesn't look like a valid header
// so stop "analyze headers" mode
reenter:
// put recipients specified on cmdline
check_hdr = 1;
while (*argv) {
char *t = sane_address(*argv);
rcptto(t);
//if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
// goto bail;
if (!has_to) {
const char *hdr;
if (check_hdr && argv[1])
hdr = "To: %s,";
else if (check_hdr)
hdr = "To: %s";
else if (argv[1])
hdr = "To: %s," + 3;
else
hdr = "To: %s" + 3;
llist_add_to_end(&list,
xasprintf(hdr, t));
check_hdr = 0;
}
argv++;
}
// enter "put message" mode
// N.B. DATA fails iff no recipients were accepted (or even provided)
// in this case just bail out gracefully
if (354 != smtp_check("DATA", -1))
goto bail;
// dump the headers
while (list) {
send_r_n((char *) llist_pop(&list));
}
// stop analyzing headers
code++;
// N.B. !s means: we read nothing, and nothing to be read in the future.
// just dump empty line and break the loop
if (!s) {
send_r_n("");
break;
}
// go dump message body
// N.B. "s" already contains the first non-header line, so pretend we read it from input
goto dump;
2008-11-07 05:12:42 +05:30
}
}
// odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
// N.B. after reenter code will be > 0
if (!code)
goto reenter;
2008-11-07 05:12:42 +05:30
// finalize the message
2008-11-07 05:12:42 +05:30
smtp_check(".", 250);
bail:
2008-11-07 05:12:42 +05:30
// ... and say goodbye
smtp_check("QUIT", 221);
// cleanup
if (ENABLE_FEATURE_CLEAN_UP)
fclose(G.fp0);
return EXIT_SUCCESS;
}