sendmail.c 8.9 KB

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