sendmail.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. //config:config SENDMAIL
  10. //config: bool "sendmail"
  11. //config: default y
  12. //config: help
  13. //config: Barebones sendmail.
  14. //applet:IF_SENDMAIL(APPLET(sendmail, BB_DIR_USR_SBIN, BB_SUID_DROP))
  15. //kbuild:lib-$(CONFIG_SENDMAIL) += sendmail.o mail.o
  16. //usage:#define sendmail_trivial_usage
  17. //usage: "[-tv] [-f SENDER] [-amLOGIN 4<user_pass.txt | -auUSER -apPASS]"
  18. //usage: "\n [-w SECS] [-H 'PROG ARGS' | -S HOST] [RECIPIENT_EMAIL]..."
  19. //usage:#define sendmail_full_usage "\n\n"
  20. //usage: "Read email from stdin and send it\n"
  21. //usage: "\nStandard options:"
  22. //usage: "\n -t Read additional recipients from message body"
  23. //usage: "\n -f SENDER For use in MAIL FROM:<sender>. Can be empty string"
  24. //usage: "\n Default: -auUSER, or username of current UID"
  25. //usage: "\n -o OPTIONS Various options. -oi implied, others are ignored"
  26. //usage: "\n -i -oi synonym, implied and ignored"
  27. //usage: "\n"
  28. //usage: "\nBusybox specific options:"
  29. //usage: "\n -v Verbose"
  30. //usage: "\n -w SECS Network timeout"
  31. //usage: "\n -H 'PROG ARGS' Run connection helper. Examples:"
  32. //usage: "\n openssl s_client -quiet -tls1 -starttls smtp -connect smtp.gmail.com:25"
  33. //usage: "\n openssl s_client -quiet -tls1 -connect smtp.gmail.com:465"
  34. //usage: "\n $SMTP_ANTISPAM_DELAY: seconds to wait after helper connect"
  35. //usage: "\n -S HOST[:PORT] Server (default $SMTPHOST or 127.0.0.1)"
  36. //usage: "\n -amLOGIN Log in using AUTH LOGIN (-amCRAM-MD5 not supported)"
  37. //usage: "\n -auUSER Username for AUTH"
  38. //usage: "\n -apPASS Password for AUTH"
  39. //usage: "\n"
  40. //usage: "\nIf no -a options are given, authentication is not done."
  41. //usage: "\nIf -amLOGIN is given but no -au/-ap, user/password is read from fd #4."
  42. //usage: "\nOther options are silently ignored; -oi is implied."
  43. //usage: IF_MAKEMIME(
  44. //usage: "\nUse makemime to create emails with attachments."
  45. //usage: )
  46. /* Currently we don't sanitize or escape user-supplied SENDER and RECIPIENT_EMAILs.
  47. * We may need to do so. For one, '.' in usernames seems to require escaping!
  48. *
  49. * From http://cr.yp.to/smtp/address.html:
  50. *
  51. * SMTP offers three ways to encode a character inside an address:
  52. *
  53. * "safe": the character, if it is not <>()[].,;:@, backslash,
  54. * double-quote, space, or an ASCII control character;
  55. * "quoted": the character, if it is not \012, \015, backslash,
  56. * or double-quote; or
  57. * "slashed": backslash followed by the character.
  58. *
  59. * An encoded box part is either (1) a sequence of one or more slashed
  60. * or safe characters or (2) a double quote, a sequence of zero or more
  61. * slashed or quoted characters, and a double quote. It represents
  62. * the concatenation of the characters encoded inside it.
  63. *
  64. * For example, the encoded box parts
  65. * angels
  66. * \a\n\g\e\l\s
  67. * "\a\n\g\e\l\s"
  68. * "angels"
  69. * "ang\els"
  70. * all represent the 6-byte string "angels", and the encoded box parts
  71. * a\,comma
  72. * \a\,\c\o\m\m\a
  73. * "a,comma"
  74. * all represent the 7-byte string "a,comma".
  75. *
  76. * An encoded address contains
  77. * the byte <;
  78. * optionally, a route followed by a colon;
  79. * an encoded box part, the byte @, and a domain; and
  80. * the byte >.
  81. *
  82. * It represents an Internet mail address, given by concatenating
  83. * the string represented by the encoded box part, the byte @,
  84. * and the domain. For example, the encoded addresses
  85. * <God@heaven.af.mil>
  86. * <\God@heaven.af.mil>
  87. * <"God"@heaven.af.mil>
  88. * <@gateway.af.mil,@uucp.local:"\G\o\d"@heaven.af.mil>
  89. * all represent the Internet mail address "God@heaven.af.mil".
  90. */
  91. #include "libbb.h"
  92. #include "mail.h"
  93. // limit maximum allowed number of headers to prevent overflows.
  94. // set to 0 to not limit
  95. #define MAX_HEADERS 256
  96. static void send_r_n(const char *s)
  97. {
  98. if (verbose)
  99. bb_error_msg("send:'%s'", s);
  100. printf("%s\r\n", s);
  101. }
  102. static int smtp_checkp(const char *fmt, const char *param, int code)
  103. {
  104. char *answer;
  105. char *msg = send_mail_command(fmt, param);
  106. // read stdin
  107. // if the string has a form NNN- -- read next string. E.g. EHLO response
  108. // parse first bytes to a number
  109. // if code = -1 then just return this number
  110. // if code != -1 then checks whether the number equals the code
  111. // if not equal -> die saying msg
  112. while ((answer = xmalloc_fgetline(stdin)) != NULL) {
  113. if (verbose)
  114. bb_error_msg("recv:'%.*s'", (int)(strchrnul(answer, '\r') - answer), answer);
  115. if (strlen(answer) <= 3 || '-' != answer[3])
  116. break;
  117. free(answer);
  118. }
  119. if (answer) {
  120. int n = atoi(answer);
  121. if (timeout)
  122. alarm(0);
  123. free(answer);
  124. if (-1 == code || n == code) {
  125. free(msg);
  126. return n;
  127. }
  128. }
  129. bb_error_msg_and_die("%s failed", msg);
  130. }
  131. static int smtp_check(const char *fmt, int code)
  132. {
  133. return smtp_checkp(fmt, NULL, code);
  134. }
  135. // strip argument of bad chars
  136. static char *sane_address(char *str)
  137. {
  138. char *s;
  139. trim(str);
  140. s = str;
  141. while (*s) {
  142. if (!isalnum(*s) && !strchr("_-.@", *s)) {
  143. bb_error_msg("bad address '%s'", str);
  144. /* returning "": */
  145. str[0] = '\0';
  146. return str;
  147. }
  148. s++;
  149. }
  150. return str;
  151. }
  152. // check for an address inside angle brackets, if not found fall back to normal
  153. static char *angle_address(char *str)
  154. {
  155. char *s, *e;
  156. trim(str);
  157. e = last_char_is(str, '>');
  158. if (e) {
  159. s = strrchr(str, '<');
  160. if (s) {
  161. *e = '\0';
  162. str = s + 1;
  163. }
  164. }
  165. return sane_address(str);
  166. }
  167. static void rcptto(const char *s)
  168. {
  169. if (!*s)
  170. return;
  171. // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
  172. if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
  173. bb_error_msg("Bad recipient: <%s>", s);
  174. }
  175. // send to a list of comma separated addresses
  176. static void rcptto_list(const char *list)
  177. {
  178. char *str = xstrdup(list);
  179. char *s = str;
  180. char prev = 0;
  181. int in_quote = 0;
  182. while (*s) {
  183. char ch = *s++;
  184. if (ch == '"' && prev != '\\') {
  185. in_quote = !in_quote;
  186. } else if (!in_quote && ch == ',') {
  187. s[-1] = '\0';
  188. rcptto(angle_address(str));
  189. str = s;
  190. }
  191. prev = ch;
  192. }
  193. if (prev != ',')
  194. rcptto(angle_address(str));
  195. free(str);
  196. }
  197. int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  198. int sendmail_main(int argc UNUSED_PARAM, char **argv)
  199. {
  200. char *opt_connect;
  201. char *opt_from = NULL;
  202. char *s;
  203. llist_t *list = NULL;
  204. char *host = sane_address(safe_gethostname());
  205. unsigned nheaders = 0;
  206. int code;
  207. enum {
  208. HDR_OTHER = 0,
  209. HDR_TOCC,
  210. HDR_BCC,
  211. } last_hdr = 0;
  212. int check_hdr;
  213. int has_to = 0;
  214. enum {
  215. //--- standard options
  216. OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
  217. OPT_f = 1 << 1, // sender address
  218. OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
  219. OPT_i = 1 << 3, // IMPLIED!
  220. //--- BB specific options
  221. OPT_w = 1 << 4, // network timeout
  222. OPT_H = 1 << 5, // use external connection helper
  223. OPT_S = 1 << 6, // specify connection string
  224. OPT_a = 1 << 7, // authentication tokens
  225. OPT_v = 1 << 8, // verbosity
  226. };
  227. // init global variables
  228. INIT_G();
  229. // default HOST[:PORT] is $SMTPHOST, or localhost
  230. opt_connect = getenv("SMTPHOST");
  231. if (!opt_connect)
  232. opt_connect = (char *)"127.0.0.1";
  233. // save initial stdin since body is piped!
  234. xdup2(STDIN_FILENO, 3);
  235. G.fp0 = xfdopen_for_read(3);
  236. // parse options
  237. // -v is a counter, -H and -S are mutually exclusive, -a is a list
  238. opt_complementary = "vv:H--S:S--H";
  239. // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
  240. // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
  241. // it is still under development.
  242. opts = getopt32(argv, "tf:o:iw:+H:S:a:*:v", &opt_from, NULL,
  243. &timeout, &opt_connect, &opt_connect, &list, &verbose);
  244. //argc -= optind;
  245. argv += optind;
  246. // process -a[upm]<token> options
  247. if ((opts & OPT_a) && !list)
  248. bb_show_usage();
  249. while (list) {
  250. char *a = (char *) llist_pop(&list);
  251. if ('u' == a[0])
  252. G.user = xstrdup(a+1);
  253. if ('p' == a[0])
  254. G.pass = xstrdup(a+1);
  255. // N.B. we support only AUTH LOGIN so far
  256. //if ('m' == a[0])
  257. // G.method = xstrdup(a+1);
  258. }
  259. // N.B. list == NULL here
  260. //bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
  261. // connect to server
  262. // connection helper ordered? ->
  263. if (opts & OPT_H) {
  264. const char *delay;
  265. const char *args[] = { "sh", "-c", opt_connect, NULL };
  266. // plug it in
  267. launch_helper(args);
  268. // Now:
  269. // our stdout will go to helper's stdin,
  270. // helper's stdout will be available on our stdin.
  271. // Wait for initial server message.
  272. // If helper (such as openssl) invokes STARTTLS, the initial 220
  273. // is swallowed by helper (and not repeated after TLS is initiated).
  274. // We will send NOOP cmd to server and check the response.
  275. // We should get 220+250 on plain connection, 250 on STARTTLSed session.
  276. //
  277. // The problem here is some servers delay initial 220 message,
  278. // and consider client to be a spammer if it starts sending cmds
  279. // before 220 reached it. The code below is unsafe in this regard:
  280. // in non-STARTTLSed case, we potentially send NOOP before 220
  281. // is sent by server.
  282. //
  283. // If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
  284. //
  285. delay = getenv("SMTP_ANTISPAM_DELAY");
  286. if (delay)
  287. sleep(atoi(delay));
  288. code = smtp_check("NOOP", -1);
  289. if (code == 220)
  290. // we got 220 - this is not STARTTLSed connection,
  291. // eat 250 response to our NOOP
  292. smtp_check(NULL, 250);
  293. else
  294. if (code != 250)
  295. bb_error_msg_and_die("SMTP init failed");
  296. } else {
  297. // vanilla connection
  298. int fd;
  299. fd = create_and_connect_stream_or_die(opt_connect, 25);
  300. // and make ourselves a simple IO filter
  301. xmove_fd(fd, STDIN_FILENO);
  302. xdup2(STDIN_FILENO, STDOUT_FILENO);
  303. // Wait for initial server 220 message
  304. smtp_check(NULL, 220);
  305. }
  306. // we should start with modern EHLO
  307. if (250 != smtp_checkp("EHLO %s", host, -1))
  308. smtp_checkp("HELO %s", host, 250);
  309. // perform authentication
  310. if (opts & OPT_a) {
  311. smtp_check("AUTH LOGIN", 334);
  312. // we must read credentials unless they are given via -a[up] options
  313. if (!G.user || !G.pass)
  314. get_cred_or_die(4);
  315. encode_base64(NULL, G.user, NULL);
  316. smtp_check("", 334);
  317. encode_base64(NULL, G.pass, NULL);
  318. smtp_check("", 235);
  319. }
  320. // set sender
  321. // N.B. we have here a very loosely defined algorythm
  322. // since sendmail historically offers no means to specify secrets on cmdline.
  323. // 1) server can require no authentication ->
  324. // we must just provide a (possibly fake) reply address.
  325. // 2) server can require AUTH ->
  326. // we must provide valid username and password along with a (possibly fake) reply address.
  327. // For the sake of security username and password are to be read either from console or from a secured file.
  328. // Since reading from console may defeat usability, the solution is either to read from a predefined
  329. // file descriptor (e.g. 4), or again from a secured file.
  330. // got no sender address? use auth name, then UID username as a last resort
  331. if (!opt_from) {
  332. opt_from = xasprintf("%s@%s",
  333. G.user ? G.user : xuid2uname(getuid()),
  334. xgethostbyname(host)->h_name);
  335. }
  336. free(host);
  337. smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
  338. // process message
  339. // read recipients from message and add them to those given on cmdline.
  340. // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
  341. // and then use the rest of stdin as message body
  342. code = 0; // set "analyze headers" mode
  343. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  344. dump:
  345. // put message lines doubling leading dots
  346. if (code) {
  347. // escape leading dots
  348. // N.B. this feature is implied even if no -i (-oi) switch given
  349. // N.B. we need to escape the leading dot regardless of
  350. // whether it is single or not character on the line
  351. if ('.' == s[0] /*&& '\0' == s[1] */)
  352. bb_putchar('.');
  353. // dump read line
  354. send_r_n(s);
  355. free(s);
  356. continue;
  357. }
  358. // analyze headers
  359. // To: or Cc: headers add recipients
  360. check_hdr = (0 == strncasecmp("To:", s, 3));
  361. has_to |= check_hdr;
  362. if (opts & OPT_t) {
  363. if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
  364. rcptto_list(s+3);
  365. last_hdr = HDR_TOCC;
  366. goto addheader;
  367. }
  368. // Bcc: header adds blind copy (hidden) recipient
  369. if (0 == strncasecmp("Bcc:", s, 4)) {
  370. rcptto_list(s+4);
  371. free(s);
  372. last_hdr = HDR_BCC;
  373. continue; // N.B. Bcc: vanishes from headers!
  374. }
  375. }
  376. check_hdr = (list && isspace(s[0]));
  377. if (strchr(s, ':') || check_hdr) {
  378. // other headers go verbatim
  379. // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
  380. // Continuation is denoted by prefixing additional lines with whitespace(s).
  381. // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
  382. if (check_hdr && last_hdr != HDR_OTHER) {
  383. rcptto_list(s+1);
  384. if (last_hdr == HDR_BCC)
  385. continue;
  386. // N.B. Bcc: vanishes from headers!
  387. } else {
  388. last_hdr = HDR_OTHER;
  389. }
  390. addheader:
  391. // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
  392. if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  393. goto bail;
  394. llist_add_to_end(&list, s);
  395. } else {
  396. // a line without ":" (an empty line too, by definition) doesn't look like a valid header
  397. // so stop "analyze headers" mode
  398. reenter:
  399. // put recipients specified on cmdline
  400. check_hdr = 1;
  401. while (*argv) {
  402. char *t = sane_address(*argv);
  403. rcptto(t);
  404. //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  405. // goto bail;
  406. if (!has_to) {
  407. const char *hdr;
  408. if (check_hdr && argv[1])
  409. hdr = "To: %s,";
  410. else if (check_hdr)
  411. hdr = "To: %s";
  412. else if (argv[1])
  413. hdr = "To: %s," + 3;
  414. else
  415. hdr = "To: %s" + 3;
  416. llist_add_to_end(&list,
  417. xasprintf(hdr, t));
  418. check_hdr = 0;
  419. }
  420. argv++;
  421. }
  422. // enter "put message" mode
  423. // N.B. DATA fails iff no recipients were accepted (or even provided)
  424. // in this case just bail out gracefully
  425. if (354 != smtp_check("DATA", -1))
  426. goto bail;
  427. // dump the headers
  428. while (list) {
  429. send_r_n((char *) llist_pop(&list));
  430. }
  431. // stop analyzing headers
  432. code++;
  433. // N.B. !s means: we read nothing, and nothing to be read in the future.
  434. // just dump empty line and break the loop
  435. if (!s) {
  436. send_r_n("");
  437. break;
  438. }
  439. // go dump message body
  440. // N.B. "s" already contains the first non-header line, so pretend we read it from input
  441. goto dump;
  442. }
  443. }
  444. // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
  445. // N.B. after reenter code will be > 0
  446. if (!code)
  447. goto reenter;
  448. // finalize the message
  449. smtp_check(".", 250);
  450. bail:
  451. // ... and say goodbye
  452. smtp_check("QUIT", 221);
  453. // cleanup
  454. if (ENABLE_FEATURE_CLEAN_UP)
  455. fclose(G.fp0);
  456. return EXIT_SUCCESS;
  457. }