3
0

sendmail.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 = str;
  88. char *p = s;
  89. while (*s) {
  90. if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
  91. *p++ = *s;
  92. }
  93. s++;
  94. }
  95. *p = '\0';
  96. return str;
  97. }
  98. static void rcptto(const char *s)
  99. {
  100. // N.B. we don't die if recipient is rejected, for the other recipients may be accepted
  101. if (250 != smtp_checkp("RCPT TO:<%s>", s, -1))
  102. bb_error_msg("Bad recipient: <%s>", s);
  103. }
  104. int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  105. int sendmail_main(int argc UNUSED_PARAM, char **argv)
  106. {
  107. char *opt_connect = opt_connect;
  108. char *opt_from;
  109. char *s;
  110. llist_t *list = NULL;
  111. char *host = sane_address(safe_gethostname());
  112. unsigned nheaders = 0;
  113. int code;
  114. enum {
  115. //--- standard options
  116. OPT_t = 1 << 0, // read message for recipients, append them to those on cmdline
  117. OPT_f = 1 << 1, // sender address
  118. OPT_o = 1 << 2, // various options. -oi IMPLIED! others are IGNORED!
  119. OPT_i = 1 << 3, // IMPLIED!
  120. //--- BB specific options
  121. OPT_w = 1 << 4, // network timeout
  122. OPT_H = 1 << 5, // use external connection helper
  123. OPT_S = 1 << 6, // specify connection string
  124. OPT_a = 1 << 7, // authentication tokens
  125. OPT_v = 1 << 8, // verbosity
  126. };
  127. // init global variables
  128. INIT_G();
  129. // save initial stdin since body is piped!
  130. xdup2(STDIN_FILENO, 3);
  131. G.fp0 = xfdopen_for_read(3);
  132. // parse options
  133. // -v is a counter, -f is required. -H and -S are mutually exclusive, -a is a list
  134. opt_complementary = "vv:f:w+:H--S:S--H:a::";
  135. // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
  136. // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
  137. // it is still under development.
  138. opts = getopt32(argv, "tf:o:iw:H:S:a::v", &opt_from, NULL,
  139. &timeout, &opt_connect, &opt_connect, &list, &verbose);
  140. //argc -= optind;
  141. argv += optind;
  142. // process -a[upm]<token> options
  143. if ((opts & OPT_a) && !list)
  144. bb_show_usage();
  145. while (list) {
  146. char *a = (char *) llist_pop(&list);
  147. if ('u' == a[0])
  148. G.user = xstrdup(a+1);
  149. if ('p' == a[0])
  150. G.pass = xstrdup(a+1);
  151. // N.B. we support only AUTH LOGIN so far
  152. //if ('m' == a[0])
  153. // G.method = xstrdup(a+1);
  154. }
  155. // N.B. list == NULL here
  156. //bb_info_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
  157. // connect to server
  158. // connection helper ordered? ->
  159. if (opts & OPT_H) {
  160. const char *args[] = { "sh", "-c", opt_connect, NULL };
  161. // plug it in
  162. launch_helper(args);
  163. // Now:
  164. // our stdout will go to helper's stdin,
  165. // helper's stdout will be available on our stdin.
  166. // Wait for initial server message.
  167. // If helper (such as openssl) invokes STARTTLS, the initial 220
  168. // is swallowed by helper (and not repeated after TLS is initiated).
  169. // We will send NOOP cmd to server and check the response.
  170. // We should get 220+250 on plain connection, 250 on STARTTLSed session.
  171. //
  172. // The problem here is some servers delay initial 220 message,
  173. // and consider client to be a spammer if it starts sending cmds
  174. // before 220 reached it. The code below is unsafe in this regard:
  175. // in non-STARTTLSed case, we potentially send NOOP before 220
  176. // is sent by server.
  177. // Ideas? (--delay SECS opt? --assume-starttls-helper opt?)
  178. code = smtp_check("NOOP", -1);
  179. if (code == 220)
  180. // we got 220 - this is not STARTTLSed connection,
  181. // eat 250 response to our NOOP
  182. smtp_check(NULL, 250);
  183. else
  184. if (code != 250)
  185. bb_error_msg_and_die("SMTP init failed");
  186. } else {
  187. // vanilla connection
  188. int fd;
  189. // host[:port] not explicitly specified? -> use $SMTPHOST
  190. // no $SMTPHOST? -> use localhost
  191. if (!(opts & OPT_S)) {
  192. opt_connect = getenv("SMTPHOST");
  193. if (!opt_connect)
  194. opt_connect = (char *)"127.0.0.1";
  195. }
  196. // do connect
  197. fd = create_and_connect_stream_or_die(opt_connect, 25);
  198. // and make ourselves a simple IO filter
  199. xmove_fd(fd, STDIN_FILENO);
  200. xdup2(STDIN_FILENO, STDOUT_FILENO);
  201. // Wait for initial server 220 message
  202. smtp_check(NULL, 220);
  203. }
  204. // we should start with modern EHLO
  205. if (250 != smtp_checkp("EHLO %s", host, -1))
  206. smtp_checkp("HELO %s", host, 250);
  207. free(host);
  208. // perform authentication
  209. if (opts & OPT_a) {
  210. smtp_check("AUTH LOGIN", 334);
  211. // we must read credentials unless they are given via -a[up] options
  212. if (!G.user || !G.pass)
  213. get_cred_or_die(4);
  214. encode_base64(NULL, G.user, NULL);
  215. smtp_check("", 334);
  216. encode_base64(NULL, G.pass, NULL);
  217. smtp_check("", 235);
  218. }
  219. // set sender
  220. // N.B. we have here a very loosely defined algorythm
  221. // since sendmail historically offers no means to specify secrets on cmdline.
  222. // 1) server can require no authentication ->
  223. // we must just provide a (possibly fake) reply address.
  224. // 2) server can require AUTH ->
  225. // we must provide valid username and password along with a (possibly fake) reply address.
  226. // For the sake of security username and password are to be read either from console or from a secured file.
  227. // Since reading from console may defeat usability, the solution is either to read from a predefined
  228. // file descriptor (e.g. 4), or again from a secured file.
  229. // got no sender address? -> use system username as a resort
  230. // N.B. we marked -f as required option!
  231. //if (!G.user) {
  232. // // N.B. IMHO getenv("USER") can be way easily spoofed!
  233. // G.user = xuid2uname(getuid());
  234. // opt_from = xasprintf("%s@%s", G.user, domain);
  235. //}
  236. smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
  237. // process message
  238. // read recipients from message and add them to those given on cmdline.
  239. // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
  240. // and then use the rest of stdin as message body
  241. code = 0; // set "analyze headers" mode
  242. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  243. dump:
  244. // put message lines doubling leading dots
  245. if (code) {
  246. // escape leading dots
  247. // N.B. this feature is implied even if no -i (-oi) switch given
  248. // N.B. we need to escape the leading dot regardless of
  249. // whether it is single or not character on the line
  250. if ('.' == s[0] /*&& '\0' == s[1] */)
  251. printf(".");
  252. // dump read line
  253. send_r_n(s);
  254. free(s);
  255. continue;
  256. }
  257. // analyze headers
  258. // To: or Cc: headers add recipients
  259. if (opts & OPT_t) {
  260. if (0 == strncasecmp("To:", s, 3) || 0 == strncasecmp("Bcc:" + 1, s, 3)) {
  261. rcptto(sane_address(s+3));
  262. goto addheader;
  263. }
  264. // Bcc: header adds blind copy (hidden) recipient
  265. if (0 == strncasecmp("Bcc:", s, 4)) {
  266. rcptto(sane_address(s+4));
  267. free(s);
  268. continue; // N.B. Bcc: vanishes from headers!
  269. }
  270. }
  271. if (strchr(s, ':') || (list && isspace(s[0]))) {
  272. // other headers go verbatim
  273. // N.B. RFC2822 2.2.3 "Long Header Fields" allows for headers to occupy several lines.
  274. // Continuation is denoted by prefixing additional lines with whitespace(s).
  275. // Thanks (stefan.seyfried at googlemail.com) for pointing this out.
  276. addheader:
  277. // N.B. we allow MAX_HEADERS generic headers at most to prevent attacks
  278. if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  279. goto bail;
  280. llist_add_to_end(&list, s);
  281. } else {
  282. // a line without ":" (an empty line too, by definition) doesn't look like a valid header
  283. // so stop "analyze headers" mode
  284. reenter:
  285. // put recipients specified on cmdline
  286. while (*argv) {
  287. char *t = sane_address(*argv);
  288. rcptto(t);
  289. //if (MAX_HEADERS && ++nheaders >= MAX_HEADERS)
  290. // goto bail;
  291. llist_add_to_end(&list, xasprintf("To: %s", t));
  292. argv++;
  293. }
  294. // enter "put message" mode
  295. // N.B. DATA fails iff no recipients were accepted (or even provided)
  296. // in this case just bail out gracefully
  297. if (354 != smtp_check("DATA", -1))
  298. goto bail;
  299. // dump the headers
  300. while (list) {
  301. send_r_n((char *) llist_pop(&list));
  302. }
  303. // stop analyzing headers
  304. code++;
  305. // N.B. !s means: we read nothing, and nothing to be read in the future.
  306. // just dump empty line and break the loop
  307. if (!s) {
  308. send_r_n("");
  309. break;
  310. }
  311. // go dump message body
  312. // N.B. "s" already contains the first non-header line, so pretend we read it from input
  313. goto dump;
  314. }
  315. }
  316. // odd case: we didn't stop "analyze headers" mode -> message body is empty. Reenter the loop
  317. // N.B. after reenter code will be > 0
  318. if (!code)
  319. goto reenter;
  320. // finalize the message
  321. smtp_check(".", 250);
  322. bail:
  323. // ... and say goodbye
  324. smtp_check("QUIT", 221);
  325. // cleanup
  326. if (ENABLE_FEATURE_CLEAN_UP)
  327. fclose(G.fp0);
  328. return EXIT_SUCCESS;
  329. }