sendmail.c 11 KB

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