sendmail.c 13 KB

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