3
0

sendmail.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 (14 kb)"
  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. /* Standard allows these chars in username without quoting:
  143. * /!#$%&'*+-=?^_`{|}~
  144. * and allows dot (.) with some restrictions.
  145. * I chose to only allow a saner subset.
  146. * I propose to expand it only on user's request.
  147. */
  148. if (!isalnum(*s) && !strchr("=+_-.@", *s)) {
  149. bb_error_msg("bad address '%s'", str);
  150. /* returning "": */
  151. str[0] = '\0';
  152. return str;
  153. }
  154. s++;
  155. }
  156. return str;
  157. }
  158. // check for an address inside angle brackets, if not found fall back to normal
  159. static char *angle_address(char *str)
  160. {
  161. char *s, *e;
  162. e = trim(str);
  163. if (e != str && e[-1] == '>') {
  164. s = strrchr(str, '<');
  165. if (s) {
  166. *e = '\0';
  167. str = s + 1;
  168. }
  169. }
  170. return sane_address(str);
  171. }
  172. static void rcptto(const char *s)
  173. {
  174. if (!*s)
  175. return;
  176. // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
  177. if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
  178. bb_error_msg("Bad recipient: <%s>", s);
  179. }
  180. // send to a list of comma separated addresses
  181. static void rcptto_list(const char *list)
  182. {
  183. char *free_me = xstrdup(list);
  184. char *str = free_me;
  185. char *s = free_me;
  186. char prev = 0;
  187. int in_quote = 0;
  188. while (*s) {
  189. char ch = *s++;
  190. if (ch == '"' && prev != '\\') {
  191. in_quote = !in_quote;
  192. } else if (!in_quote && ch == ',') {
  193. s[-1] = '\0';
  194. rcptto(angle_address(str));
  195. str = s;
  196. }
  197. prev = ch;
  198. }
  199. if (prev != ',')
  200. rcptto(angle_address(str));
  201. free(free_me);
  202. }
  203. int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  204. int sendmail_main(int argc UNUSED_PARAM, char **argv)
  205. {
  206. char *opt_connect;
  207. char *opt_from = NULL;
  208. char *s;
  209. llist_t *list = NULL;
  210. char *host = sane_address(safe_gethostname());
  211. unsigned nheaders = 0;
  212. int code;
  213. enum {
  214. HDR_OTHER = 0,
  215. HDR_TOCC,
  216. HDR_BCC,
  217. } last_hdr = 0;
  218. int check_hdr;
  219. int has_to = 0;
  220. enum {
  221. //--- standard options
  222. OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
  223. OPT_f = 1 << 1, // sender address
  224. OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
  225. OPT_i = 1 << 3, // IMPLIED!
  226. //--- BB specific options
  227. OPT_w = 1 << 4, // network timeout
  228. OPT_H = 1 << 5, // use external connection helper
  229. OPT_S = 1 << 6, // specify connection string
  230. OPT_a = 1 << 7, // authentication tokens
  231. OPT_v = 1 << 8, // verbosity
  232. };
  233. // init global variables
  234. INIT_G();
  235. // default HOST[:PORT] is $SMTPHOST, or localhost
  236. opt_connect = getenv("SMTPHOST");
  237. if (!opt_connect)
  238. opt_connect = (char *)"127.0.0.1";
  239. // save initial stdin since body is piped!
  240. xdup2(STDIN_FILENO, 3);
  241. G.fp0 = xfdopen_for_read(3);
  242. // parse options
  243. // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
  244. // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
  245. // it is still under development.
  246. opts = getopt32(argv, "^"
  247. "tf:o:iw:+H:S:a:*:v"
  248. "\0"
  249. // -v is a counter, -H and -S are mutually exclusive, -a is a list
  250. "vv:H--S:S--H",
  251. &opt_from, NULL,
  252. &timeout, &opt_connect, &opt_connect, &list, &verbose
  253. );
  254. //argc -= optind;
  255. argv += optind;
  256. // process -a[upm]<token> options
  257. if ((opts & OPT_a) && !list)
  258. bb_show_usage();
  259. while (list) {
  260. char *a = (char *) llist_pop(&list);
  261. if ('u' == a[0])
  262. G.user = xstrdup(a+1);
  263. if ('p' == a[0])
  264. G.pass = xstrdup(a+1);
  265. // N.B. we support only AUTH LOGIN so far
  266. //if ('m' == a[0])
  267. // G.method = xstrdup(a+1);
  268. }
  269. // N.B. list == NULL here
  270. //bb_error_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
  271. // connect to server
  272. // connection helper ordered? ->
  273. if (opts & OPT_H) {
  274. const char *delay;
  275. const char *args[] = { "sh", "-c", opt_connect, NULL };
  276. // plug it in
  277. launch_helper(args);
  278. // Now:
  279. // our stdout will go to helper's stdin,
  280. // helper's stdout will be available on our stdin.
  281. // Wait for initial server message.
  282. // If helper (such as openssl) invokes STARTTLS, the initial 220
  283. // is swallowed by helper (and not repeated after TLS is initiated).
  284. // We will send NOOP cmd to server and check the response.
  285. // We should get 220+250 on plain connection, 250 on STARTTLSed session.
  286. //
  287. // The problem here is some servers delay initial 220 message,
  288. // and consider client to be a spammer if it starts sending cmds
  289. // before 220 reached it. The code below is unsafe in this regard:
  290. // in non-STARTTLSed case, we potentially send NOOP before 220
  291. // is sent by server.
  292. //
  293. // If $SMTP_ANTISPAM_DELAY is set, we pause before sending NOOP.
  294. //
  295. delay = getenv("SMTP_ANTISPAM_DELAY");
  296. if (delay)
  297. sleep(atoi(delay));
  298. code = smtp_check("NOOP", -1);
  299. if (code == 220)
  300. // we got 220 - this is not STARTTLSed connection,
  301. // eat 250 response to our NOOP
  302. smtp_check(NULL, 250);
  303. else
  304. if (code != 250)
  305. bb_error_msg_and_die("SMTP init failed");
  306. } else {
  307. // vanilla connection
  308. int fd;
  309. fd = create_and_connect_stream_or_die(opt_connect, 25);
  310. // and make ourselves a simple IO filter
  311. xmove_fd(fd, STDIN_FILENO);
  312. xdup2(STDIN_FILENO, STDOUT_FILENO);
  313. // Wait for initial server 220 message
  314. smtp_check(NULL, 220);
  315. }
  316. // we should start with modern EHLO
  317. if (250 != smtp_checkp("EHLO %s", host, -1))
  318. smtp_checkp("HELO %s", host, 250);
  319. // perform authentication
  320. if (opts & OPT_a) {
  321. smtp_check("AUTH LOGIN", 334);
  322. // we must read credentials unless they are given via -a[up] options
  323. if (!G.user || !G.pass)
  324. get_cred_or_die(4);
  325. encode_base64(NULL, G.user, NULL);
  326. smtp_check("", 334);
  327. encode_base64(NULL, G.pass, NULL);
  328. smtp_check("", 235);
  329. }
  330. // set sender
  331. // N.B. we have here a very loosely defined algorythm
  332. // since sendmail historically offers no means to specify secrets on cmdline.
  333. // 1) server can require no authentication ->
  334. // we must just provide a (possibly fake) reply address.
  335. // 2) server can require AUTH ->
  336. // we must provide valid username and password along with a (possibly fake) reply address.
  337. // For the sake of security username and password are to be read either from console or from a secured file.
  338. // Since reading from console may defeat usability, the solution is either to read from a predefined
  339. // file descriptor (e.g. 4), or again from a secured file.
  340. // got no sender address? use auth name, then UID username as a last resort
  341. if (!opt_from) {
  342. opt_from = xasprintf("%s@%s",
  343. G.user ? G.user : xuid2uname(getuid()),
  344. xgethostbyname(host)->h_name);
  345. }
  346. free(host);
  347. smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
  348. // process message
  349. // read recipients from message and add them to those given on cmdline.
  350. // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
  351. // and then use the rest of stdin as message body
  352. code = 0; // set "analyze headers" mode
  353. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  354. dump:
  355. // put message lines doubling leading dots
  356. if (code) {
  357. // escape leading dots
  358. // N.B. this feature is implied even if no -i (-oi) switch given
  359. // N.B. we need to escape the leading dot regardless of
  360. // whether it is single or not character on the line
  361. if ('.' == s[0] /*&& '\0' == s[1] */)
  362. bb_putchar('.');
  363. // dump read line
  364. send_r_n(s);
  365. free(s);
  366. continue;
  367. }
  368. // analyze headers
  369. // To: or Cc: headers add recipients
  370. check_hdr = (0 == strncasecmp("To:", s, 3));
  371. has_to |= check_hdr;
  372. if (opts & OPT_t) {
  373. if (check_hdr || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
  374. rcptto_list(s+3);
  375. last_hdr = HDR_TOCC;
  376. goto addheader;
  377. }
  378. // Bcc: header adds blind copy (hidden) recipient
  379. if (0 == strncasecmp("Bcc:", s, 4)) {
  380. rcptto_list(s+4);
  381. free(s);
  382. last_hdr = HDR_BCC;
  383. continue; // N.B. Bcc: vanishes from headers!
  384. }
  385. }
  386. check_hdr = (list && isspace(s[0]));
  387. if (strchr(s, ':') || check_hdr) {
  388. // other headers go verbatim
  389. // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
  390. // Continuation is denoted by prefixing additional lines with whitespace(s).
  391. // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
  392. if (check_hdr && last_hdr != HDR_OTHER) {
  393. rcptto_list(s+1);
  394. if (last_hdr == HDR_BCC)
  395. continue;
  396. // N.B. Bcc: vanishes from headers!
  397. } else {
  398. last_hdr = HDR_OTHER;
  399. }
  400. addheader:
  401. // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
  402. if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  403. goto bail;
  404. llist_add_to_end(&list, s);
  405. } else {
  406. // a line without ":" (an empty line too, by definition) doesn't look like a valid header
  407. // so stop "analyze headers" mode
  408. reenter:
  409. // put recipients specified on cmdline
  410. check_hdr = 1;
  411. while (*argv) {
  412. char *t = sane_address(*argv);
  413. rcptto(t);
  414. //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  415. // goto bail;
  416. if (!has_to) {
  417. const char *hdr;
  418. if (check_hdr && argv[1])
  419. hdr = "To: %s,";
  420. else if (check_hdr)
  421. hdr = "To: %s";
  422. else if (argv[1])
  423. hdr = "To: %s," + 3;
  424. else
  425. hdr = "To: %s" + 3;
  426. llist_add_to_end(&list,
  427. xasprintf(hdr, t));
  428. check_hdr = 0;
  429. }
  430. argv++;
  431. }
  432. // enter "put message" mode
  433. // N.B. DATA fails iff no recipients were accepted (or even provided)
  434. // in this case just bail out gracefully
  435. if (354 != smtp_check("DATA", -1))
  436. goto bail;
  437. // dump the headers
  438. while (list) {
  439. send_r_n((char *) llist_pop(&list));
  440. }
  441. // stop analyzing headers
  442. code++;
  443. // N.B. !s means: we read nothing, and nothing to be read in the future.
  444. // just dump empty line and break the loop
  445. if (!s) {
  446. send_r_n("");
  447. break;
  448. }
  449. // go dump message body
  450. // N.B. "s" already contains the first non-header line, so pretend we read it from input
  451. goto dump;
  452. }
  453. }
  454. // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
  455. // N.B. after reenter code will be > 0
  456. if (!code)
  457. goto reenter;
  458. // finalize the message
  459. smtp_check(".", 250);
  460. bail:
  461. // ... and say goodbye
  462. smtp_check("QUIT", 221);
  463. // cleanup
  464. if (ENABLE_FEATURE_CLEAN_UP)
  465. fclose(G.fp0);
  466. return EXIT_SUCCESS;
  467. }