sendmail.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. static int smtp_checkp(const char *fmt, const char *param, int code)
  12. {
  13. char *answer;
  14. const char *msg = command(fmt, param);
  15. // read stdin
  16. // if the string has a form \d\d\d- -- read next string. E.g. EHLO response
  17. // parse first bytes to a number
  18. // if code = -1 then just return this number
  19. // if code != -1 then checks whether the number equals the code
  20. // if not equal -> die saying msg
  21. while ((answer = xmalloc_fgetline(stdin)) != NULL)
  22. if (strlen(answer) <= 3 || '-' != answer[3])
  23. break;
  24. if (answer) {
  25. int n = atoi(answer);
  26. if (timeout)
  27. alarm(0);
  28. free(answer);
  29. if (-1 == code || n == code)
  30. return n;
  31. }
  32. bb_error_msg_and_die("%s failed", msg);
  33. }
  34. static int smtp_check(const char *fmt, int code)
  35. {
  36. return smtp_checkp(fmt, NULL, code);
  37. }
  38. // strip argument of bad chars
  39. static char *sane_address(char *str)
  40. {
  41. char *s = str;
  42. char *p = s;
  43. while (*s) {
  44. if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
  45. *p++ = *s;
  46. }
  47. s++;
  48. }
  49. *p = '\0';
  50. return str;
  51. }
  52. static void rcptto(const char *s)
  53. {
  54. smtp_checkp("RCPT TO:<%s>", s, 250);
  55. }
  56. int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  57. int sendmail_main(int argc UNUSED_PARAM, char **argv)
  58. {
  59. #if ENABLE_FEATURE_SENDMAIL_MAILX
  60. llist_t *opt_attachments = NULL;
  61. const char *opt_subject;
  62. #if ENABLE_FEATURE_SENDMAIL_MAILXX
  63. llist_t *opt_carboncopies = NULL;
  64. char *opt_errors_to;
  65. #endif
  66. #endif
  67. char *opt_connect = opt_connect;
  68. char *opt_from, *opt_fullname;
  69. char *boundary;
  70. llist_t *l;
  71. llist_t *headers = NULL;
  72. char *domain = sane_address(safe_getdomainname());
  73. int code;
  74. enum {
  75. OPT_w = 1 << 0, // network timeout
  76. OPT_t = 1 << 1, // read message for recipients
  77. OPT_N = 1 << 2, // request notification
  78. OPT_f = 1 << 3, // sender address
  79. OPT_F = 1 << 4, // sender name, overrides $NAME
  80. OPT_s = 1 << 5, // subject
  81. OPT_j = 1 << 6, // assumed charset
  82. OPT_a = 1 << 7, // attachment(s)
  83. OPT_H = 1 << 8, // use external connection helper
  84. OPT_S = 1 << 9, // specify connection string
  85. OPT_c = 1 << 10, // carbon copy
  86. OPT_e = 1 << 11, // errors-to address
  87. };
  88. // init global variables
  89. INIT_G();
  90. // save initial stdin since body is piped!
  91. xdup2(STDIN_FILENO, 3);
  92. G.fp0 = fdopen(3, "r");
  93. // parse options
  94. opt_complementary = "w+" USE_FEATURE_SENDMAIL_MAILX(":a::H--S:S--H") USE_FEATURE_SENDMAIL_MAILXX(":c::");
  95. opts = getopt32(argv,
  96. "w:t" "N:f:F:" USE_FEATURE_SENDMAIL_MAILX("s:j:a:H:S:") USE_FEATURE_SENDMAIL_MAILXX("c:e:")
  97. "X:V:vq:R:O:o:nmL:Iih:GC:B:b:A:" // postfix compat only, ignored
  98. // r:Q:p:M:Dd are candidates from another man page. TODO?
  99. "46E", // ssmtp introduces another quirks. TODO?: -a[upm] (user, pass, method) to be supported
  100. &timeout /* -w */, NULL, &opt_from, &opt_fullname,
  101. USE_FEATURE_SENDMAIL_MAILX(&opt_subject, &G.opt_charset, &opt_attachments, &opt_connect, &opt_connect,)
  102. USE_FEATURE_SENDMAIL_MAILXX(&opt_carboncopies, &opt_errors_to,)
  103. NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
  104. );
  105. //argc -= optind;
  106. argv += optind;
  107. // connect to server
  108. #if ENABLE_FEATURE_SENDMAIL_MAILX
  109. // N.B. -H and -S are mutually exclusive so they do not spoil opt_connect
  110. // connection helper ordered? ->
  111. if (opts & OPT_H) {
  112. const char *args[] = { "sh", "-c", opt_connect, NULL };
  113. // plug it in
  114. launch_helper(args);
  115. // vanilla connection
  116. } else
  117. #endif
  118. {
  119. int fd;
  120. // host[:port] not explicitly specified ? -> use $SMTPHOST
  121. // no $SMTPHOST ? -> use localhost
  122. if (!(opts & OPT_S)) {
  123. opt_connect = getenv("SMTPHOST");
  124. if (!opt_connect)
  125. opt_connect = (char *)"127.0.0.1";
  126. }
  127. // do connect
  128. fd = create_and_connect_stream_or_die(opt_connect, 25);
  129. // and make ourselves a simple IO filter
  130. xmove_fd(fd, STDIN_FILENO);
  131. xdup2(STDIN_FILENO, STDOUT_FILENO);
  132. }
  133. // N.B. from now we know nothing about network :)
  134. // wait for initial server OK
  135. // N.B. if we used openssl the initial 220 answer is already swallowed during openssl TLS init procedure
  136. // so we need to push the server to see whether we are ok
  137. code = smtp_check("NOOP", -1);
  138. // 220 on plain connection, 250 on openssl-helped TLS session
  139. if (220 == code)
  140. smtp_check(NULL, 250); // reread the code to stay in sync
  141. else if (250 != code)
  142. bb_error_msg_and_die("INIT failed");
  143. // we should start with modern EHLO
  144. if (250 != smtp_checkp("EHLO %s", domain, -1)) {
  145. smtp_checkp("HELO %s", domain, 250);
  146. }
  147. // set sender
  148. // N.B. we have here a very loosely defined algotythm
  149. // since sendmail historically offers no means to specify secrets on cmdline.
  150. // 1) server can require no authentication ->
  151. // we must just provide a (possibly fake) reply address.
  152. // 2) server can require AUTH ->
  153. // we must provide valid username and password along with a (possibly fake) reply address.
  154. // For the sake of security username and password are to be read either from console or from a secured file.
  155. // Since reading from console may defeat usability, the solution is either to read from a predefined
  156. // file descriptor (e.g. 4), or again from a secured file.
  157. // got no sender address? -> use system username as a resort
  158. if (!(opts & OPT_f)) {
  159. // N.B. IMHO getenv("USER") can be way easily spoofed!
  160. G.user = bb_getpwuid(NULL, -1, getuid());
  161. opt_from = xasprintf("%s@%s", G.user, domain);
  162. }
  163. if (ENABLE_FEATURE_CLEAN_UP)
  164. free(domain);
  165. code = -1; // first try softly without authentication
  166. while (250 != smtp_checkp("MAIL FROM:<%s>", opt_from, code)) {
  167. // MAIL FROM failed -> authentication needed
  168. if (334 == smtp_check("AUTH LOGIN", -1)) {
  169. // we must read credentials
  170. get_cred_or_die(4);
  171. encode_base64(NULL, G.user, NULL);
  172. smtp_check("", 334);
  173. encode_base64(NULL, G.pass, NULL);
  174. smtp_check("", 235);
  175. }
  176. // authenticated OK? -> retry to set sender
  177. // but this time die on failure!
  178. code = 250;
  179. }
  180. // recipients specified as arguments
  181. while (*argv) {
  182. char *s = sane_address(*argv);
  183. // loose test on email address validity
  184. // if (strchr(s, '@')) {
  185. rcptto(s);
  186. llist_add_to_end(&headers, xasprintf("To: %s", s));
  187. // }
  188. argv++;
  189. }
  190. #if ENABLE_FEATURE_SENDMAIL_MAILXX
  191. // carbon copies recipients specified as -c options
  192. for (l = opt_carboncopies; l; l = l->link) {
  193. char *s = sane_address(l->data);
  194. // loose test on email address validity
  195. // if (strchr(s, '@')) {
  196. rcptto(s);
  197. // TODO: do we ever need to mangle the message?
  198. //llist_add_to_end(&headers, xasprintf("Cc: %s", s));
  199. // }
  200. }
  201. #endif
  202. // if -t specified or no recipients specified -> read recipients from message
  203. // i.e. scan stdin for To:, Cc:, Bcc: lines ...
  204. // ... and then use the rest of stdin as message body
  205. // N.B. subject read from body can be further overrided with one specified on command line.
  206. // recipients are merged. Bcc: lines are deleted
  207. // N.B. other headers are collected and will be dumped verbatim
  208. if (opts & OPT_t || !headers) {
  209. // fetch recipients and (optionally) subject
  210. char *s;
  211. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  212. if (0 == strncasecmp("To: ", s, 4) || 0 == strncasecmp("Cc: ", s, 4)) {
  213. rcptto(sane_address(s+4));
  214. llist_add_to_end(&headers, s);
  215. } else if (0 == strncasecmp("Bcc: ", s, 5)) {
  216. rcptto(sane_address(s+5));
  217. free(s);
  218. // N.B. Bcc vanishes from headers!
  219. } else if (0 == strncmp("Subject: ", s, 9)) {
  220. // we read subject -> use it verbatim unless it is specified
  221. // on command line
  222. if (!(opts & OPT_s))
  223. llist_add_to_end(&headers, s);
  224. else
  225. free(s);
  226. } else if (s[0]) {
  227. // misc header
  228. llist_add_to_end(&headers, s);
  229. } else {
  230. free(s);
  231. break; // stop on the first empty line
  232. }
  233. }
  234. }
  235. // enter "put message" mode
  236. smtp_check("DATA", 354);
  237. // put headers we could have preread with -t
  238. for (l = headers; l; l = l->link) {
  239. printf("%s\r\n", l->data);
  240. if (ENABLE_FEATURE_CLEAN_UP)
  241. free(l->data);
  242. }
  243. // put (possibly encoded) subject
  244. #if ENABLE_FEATURE_SENDMAIL_MAILX
  245. if (opts & OPT_s) {
  246. printf("Subject: ");
  247. if (opts & OPT_j) {
  248. printf("=?%s?B?", G.opt_charset);
  249. encode_base64(NULL, opt_subject, NULL);
  250. printf("?=");
  251. } else {
  252. printf("%s", opt_subject);
  253. }
  254. printf("\r\n");
  255. }
  256. #endif
  257. // put sender name, $NAME is the default
  258. if (!(opts & OPT_F))
  259. opt_fullname = getenv("NAME");
  260. if (opt_fullname)
  261. printf("From: \"%s\" <%s>\r\n", opt_fullname, opt_from);
  262. // put notification
  263. if (opts & OPT_N)
  264. printf("Disposition-Notification-To: %s\r\n", opt_from);
  265. #if ENABLE_FEATURE_SENDMAIL_MAILXX
  266. // put errors recipient
  267. if (opts & OPT_e)
  268. printf("Errors-To: %s\r\n", opt_errors_to);
  269. #endif
  270. // make a random string -- it will delimit message parts
  271. srand(monotonic_us());
  272. boundary = xasprintf("%d=_%d-%d", rand(), rand(), rand());
  273. // put common headers
  274. // TODO: do we really need this?
  275. // printf("Message-ID: <%s>\r\n", boundary);
  276. #if ENABLE_FEATURE_SENDMAIL_MAILX
  277. // have attachments? -> compose multipart MIME
  278. if (opt_attachments) {
  279. const char *fmt;
  280. const char *p;
  281. char *q;
  282. printf(
  283. "Mime-Version: 1.0\r\n"
  284. "%smultipart/mixed; boundary=\"%s\"\r\n"
  285. , "Content-Type: "
  286. , boundary
  287. );
  288. // body is pseudo attachment read from stdin in first turn
  289. llist_add_to(&opt_attachments, (char *)"-");
  290. // put body + attachment(s)
  291. // N.B. all these weird things just to be tiny
  292. // by reusing string patterns!
  293. fmt =
  294. "\r\n--%s\r\n"
  295. "%stext/plain; charset=%s\r\n"
  296. "%s%s\r\n"
  297. "%s"
  298. ;
  299. p = G.opt_charset;
  300. q = (char *)"";
  301. l = opt_attachments;
  302. while (l) {
  303. printf(
  304. fmt
  305. , boundary
  306. , "Content-Type: "
  307. , p
  308. , "Content-Disposition: inline"
  309. , q
  310. , "Content-Transfer-Encoding: base64\r\n"
  311. );
  312. p = "";
  313. fmt =
  314. "\r\n--%s\r\n"
  315. "%sapplication/octet-stream%s\r\n"
  316. "%s; filename=\"%s\"\r\n"
  317. "%s"
  318. ;
  319. encode_base64(l->data, (const char *)G.fp0, "\r");
  320. l = l->link;
  321. if (l)
  322. q = bb_get_last_path_component_strip(l->data);
  323. }
  324. // put message terminator
  325. printf("\r\n--%s--\r\n" "\r\n", boundary);
  326. // no attachments? -> just dump message
  327. } else
  328. #endif
  329. {
  330. char *s;
  331. // terminate headers
  332. printf("\r\n");
  333. // put plain text respecting leading dots
  334. while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
  335. // escape leading dots
  336. // N.B. this feature is implied even if no -i (-oi) switch given
  337. // N.B. we need to escape the leading dot regardless of
  338. // whether it is single or not character on the line
  339. if ('.' == s[0] /*&& '\0' == s[1] */)
  340. printf(".");
  341. // dump read line
  342. printf("%s\r\n", s);
  343. }
  344. }
  345. // leave "put message" mode
  346. smtp_check(".", 250);
  347. // ... and say goodbye
  348. smtp_check("QUIT", 221);
  349. // cleanup
  350. if (ENABLE_FEATURE_CLEAN_UP)
  351. fclose(G.fp0);
  352. return EXIT_SUCCESS;
  353. }