sendmail.c 14 KB

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