main.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. /*
  2. * uhttpd - Tiny single-threaded httpd
  3. *
  4. * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
  5. * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
  6. *
  7. * Permission to use, copy, modify, and/or distribute this software for any
  8. * purpose with or without fee is hereby granted, provided that the above
  9. * copyright notice and this permission notice appear in all copies.
  10. *
  11. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  12. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  13. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  14. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  15. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  16. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  17. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  18. */
  19. #ifndef _DEFAULT_SOURCE
  20. # define _DEFAULT_SOURCE
  21. #endif
  22. #define _BSD_SOURCE
  23. #define _GNU_SOURCE
  24. #define _XOPEN_SOURCE 700
  25. #include <sys/types.h>
  26. #include <sys/socket.h>
  27. #include <netinet/in.h>
  28. #include <getopt.h>
  29. #include <errno.h>
  30. #include <netdb.h>
  31. #include <signal.h>
  32. #include <libubox/usock.h>
  33. #include <libubox/utils.h>
  34. #include "uhttpd.h"
  35. #include "tls.h"
  36. char uh_buf[4096];
  37. static int run_server(void)
  38. {
  39. uloop_init();
  40. uh_setup_listeners();
  41. uh_plugin_post_init();
  42. uloop_run();
  43. return 0;
  44. }
  45. static void uh_config_parse(void)
  46. {
  47. const char *path = conf.file;
  48. FILE *c;
  49. char line[512];
  50. char *col1;
  51. char *col2;
  52. char *eol;
  53. if (!path)
  54. path = "/etc/httpd.conf";
  55. c = fopen(path, "r");
  56. if (!c)
  57. return;
  58. memset(line, 0, sizeof(line));
  59. while (fgets(line, sizeof(line) - 1, c)) {
  60. if ((line[0] == '/') && (strchr(line, ':') != NULL)) {
  61. if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
  62. !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
  63. !(eol = strchr(col2, '\n')) || (*eol++ = 0))
  64. continue;
  65. uh_auth_add(line, col1, col2);
  66. } else if (!strncmp(line, "I:", 2)) {
  67. if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
  68. !(eol = strchr(col1, '\n')) || (*eol++ = 0))
  69. continue;
  70. uh_index_add(strdup(col1));
  71. } else if (!strncmp(line, "E404:", 5)) {
  72. if (!(col1 = strchr(line, ':')) || (*col1++ = 0) ||
  73. !(eol = strchr(col1, '\n')) || (*eol++ = 0))
  74. continue;
  75. conf.error_handler = strdup(col1);
  76. }
  77. else if ((line[0] == '*') && (strchr(line, ':') != NULL)) {
  78. if (!(col1 = strchr(line, '*')) || (*col1++ = 0) ||
  79. !(col2 = strchr(col1, ':')) || (*col2++ = 0) ||
  80. !(eol = strchr(col2, '\n')) || (*eol++ = 0))
  81. continue;
  82. uh_interpreter_add(col1, col2);
  83. }
  84. }
  85. fclose(c);
  86. }
  87. static int add_listener_arg(char *arg, bool tls)
  88. {
  89. char *host = NULL;
  90. char *port = arg;
  91. char *s;
  92. int l;
  93. s = strrchr(arg, ':');
  94. if (s) {
  95. host = arg;
  96. port = s + 1;
  97. *s = 0;
  98. }
  99. if (host && *host == '[') {
  100. l = strlen(host);
  101. if (l >= 2) {
  102. host[l-1] = 0;
  103. host++;
  104. }
  105. }
  106. return uh_socket_bind(host, port, tls);
  107. }
  108. static int usage(const char *name)
  109. {
  110. fprintf(stderr,
  111. "Usage: %s -p [addr:]port -h docroot\n"
  112. " -f Do not fork to background\n"
  113. " -c file Configuration file, default is '/etc/httpd.conf'\n"
  114. " -p [addr:]port Bind to specified address and port, multiple allowed\n"
  115. #ifdef HAVE_TLS
  116. " -s [addr:]port Like -p but provide HTTPS on this port\n"
  117. " -C file ASN.1 server certificate file\n"
  118. " -K file ASN.1 server private key file\n"
  119. " -P ciphers Colon separated list of allowed TLS ciphers\n"
  120. " -q Redirect all HTTP requests to HTTPS\n"
  121. #endif
  122. " -h directory Specify the document root, default is '.'\n"
  123. " -E string Use given virtual URL as 404 error handler\n"
  124. " -b string Use given charset for directory listings, default to UTF-8\n"
  125. " -I string Use given filename as index for directories, multiple allowed\n"
  126. " -S Do not follow symbolic links outside of the docroot\n"
  127. " -D Do not allow directory listings, send 403 instead\n"
  128. " -R Enable RFC1918 filter\n"
  129. " -n count Maximum allowed number of concurrent script requests\n"
  130. " -N count Maximum allowed number of concurrent connections\n"
  131. #ifdef HAVE_LUA
  132. " -l string URL prefix for Lua handler\n"
  133. " -L file Path to Lua handler script, -l and -L may be repeated in pairs\n"
  134. #endif
  135. #ifdef HAVE_UCODE
  136. " -o string URL prefix for ucode handler\n"
  137. " -O file Path to ucode handler script, -o and -O may be repeated in pairs\n"
  138. #endif
  139. #ifdef HAVE_UBUS
  140. " -u string URL prefix for UBUS via JSON-RPC handler\n"
  141. " -U file Override ubus socket path\n"
  142. " -a Do not authenticate JSON-RPC requests against UBUS session api\n"
  143. " -X Enable CORS HTTP headers on JSON-RPC api\n"
  144. " -e Events subscription reconnection time (retry value)\n"
  145. #endif
  146. " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
  147. " -y alias[=path] URL alias handle\n"
  148. " -i .ext=path Use interpreter at path for files with the given extension\n"
  149. " -t seconds CGI, Lua and UBUS script timeout in seconds, default is 60\n"
  150. " -T seconds Network timeout in seconds, default is 30\n"
  151. " -k seconds HTTP keepalive timeout\n"
  152. " -A seconds TCP keepalive timeout, default is unset\n"
  153. " -d string URL decode given string\n"
  154. " -r string Specify basic auth realm\n"
  155. " -m string MD5 crypt given string\n"
  156. "\n", name
  157. );
  158. return 1;
  159. }
  160. static void init_defaults_pre(void)
  161. {
  162. conf.script_timeout = 60;
  163. conf.network_timeout = 30;
  164. conf.http_keepalive = 20;
  165. conf.max_script_requests = 3;
  166. conf.max_connections = 100;
  167. conf.realm = "Protected Area";
  168. conf.cgi_prefix = "/cgi-bin";
  169. conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
  170. INIT_LIST_HEAD(&conf.cgi_alias);
  171. INIT_LIST_HEAD(&conf.lua_prefix);
  172. #if HAVE_UCODE
  173. INIT_LIST_HEAD(&conf.ucode_prefix);
  174. #endif
  175. }
  176. static void init_defaults_post(void)
  177. {
  178. uh_index_add("index.html");
  179. uh_index_add("index.htm");
  180. uh_index_add("default.html");
  181. uh_index_add("default.htm");
  182. if (conf.cgi_prefix) {
  183. char *str = malloc(strlen(conf.docroot) + strlen(conf.cgi_prefix) + 1);
  184. strcpy(str, conf.docroot);
  185. strcat(str, conf.cgi_prefix);
  186. conf.cgi_docroot_path = str;
  187. conf.cgi_prefix_len = strlen(conf.cgi_prefix);
  188. };
  189. }
  190. static void fixup_prefix(char *str)
  191. {
  192. int len;
  193. if (!str || !str[0])
  194. return;
  195. len = strlen(str) - 1;
  196. while (len >= 0 && str[len] == '/')
  197. len--;
  198. str[len + 1] = 0;
  199. }
  200. #ifdef HAVE_LUA
  201. static void add_lua_prefix(const char *prefix, const char *handler) {
  202. struct lua_prefix *p;
  203. char *pprefix, *phandler;
  204. p = calloc_a(sizeof(*p),
  205. &pprefix, strlen(prefix) + 1,
  206. &phandler, strlen(handler) + 1);
  207. if (!p)
  208. return;
  209. p->prefix = strcpy(pprefix, prefix);
  210. p->handler = strcpy(phandler, handler);
  211. list_add_tail(&p->list, &conf.lua_prefix);
  212. }
  213. #endif
  214. #ifdef HAVE_UCODE
  215. static void add_ucode_prefix(const char *prefix, const char *handler) {
  216. struct ucode_prefix *p;
  217. char *pprefix, *phandler;
  218. p = calloc_a(sizeof(*p),
  219. &pprefix, strlen(prefix) + 1,
  220. &phandler, strlen(handler) + 1);
  221. if (!p)
  222. return;
  223. p->prefix = strcpy(pprefix, prefix);
  224. p->handler = strcpy(phandler, handler);
  225. list_add_tail(&p->list, &conf.ucode_prefix);
  226. }
  227. #endif
  228. int main(int argc, char **argv)
  229. {
  230. struct alias *alias;
  231. bool nofork = false;
  232. char *port;
  233. int opt, ch;
  234. int cur_fd;
  235. int bound = 0;
  236. #ifdef HAVE_TLS
  237. int n_tls = 0;
  238. const char *tls_key = NULL, *tls_crt = NULL, *tls_ciphers = NULL;
  239. #endif
  240. #ifdef HAVE_LUA
  241. const char *lua_prefix = NULL, *lua_handler = NULL;
  242. #endif
  243. #ifdef HAVE_UCODE
  244. const char *ucode_prefix = NULL, *ucode_handler = NULL;
  245. #endif
  246. BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
  247. uh_dispatch_add(&cgi_dispatch);
  248. init_defaults_pre();
  249. signal(SIGPIPE, SIG_IGN);
  250. while ((ch = getopt(argc, argv, "A:ab:C:c:Dd:E:e:fh:H:I:i:K:k:L:l:m:N:n:O:o:P:p:qRr:Ss:T:t:U:u:Xx:y:")) != -1) {
  251. switch(ch) {
  252. #ifdef HAVE_TLS
  253. case 'C':
  254. tls_crt = optarg;
  255. break;
  256. case 'K':
  257. tls_key = optarg;
  258. break;
  259. case 'P':
  260. tls_ciphers = optarg;
  261. break;
  262. case 'q':
  263. conf.tls_redirect = 1;
  264. break;
  265. case 's':
  266. n_tls++;
  267. /* fall through */
  268. #else
  269. case 'C':
  270. case 'K':
  271. case 'P':
  272. case 'q':
  273. case 's':
  274. fprintf(stderr, "uhttpd: TLS support not compiled, "
  275. "ignoring -%c\n", ch);
  276. break;
  277. #endif
  278. case 'p':
  279. optarg = strdup(optarg);
  280. bound += add_listener_arg(optarg, (ch == 's'));
  281. free(optarg);
  282. break;
  283. case 'h':
  284. if (!realpath(optarg, uh_buf)) {
  285. fprintf(stderr, "Error: Invalid directory %s: %s\n",
  286. optarg, strerror(errno));
  287. exit(1);
  288. }
  289. conf.docroot = strdup(uh_buf);
  290. break;
  291. case 'H':
  292. if (uh_handler_add(optarg)) {
  293. fprintf(stderr, "Error: Failed to load handler script %s\n",
  294. optarg);
  295. exit(1);
  296. }
  297. break;
  298. case 'E':
  299. if (optarg[0] != '/') {
  300. fprintf(stderr, "Error: Invalid error handler: %s\n",
  301. optarg);
  302. exit(1);
  303. }
  304. conf.error_handler = optarg;
  305. break;
  306. case 'I':
  307. if (optarg[0] == '/') {
  308. fprintf(stderr, "Error: Invalid index page: %s\n",
  309. optarg);
  310. exit(1);
  311. }
  312. uh_index_add(optarg);
  313. break;
  314. case 'b':
  315. conf.dirlist_charset = optarg;
  316. break;
  317. case 'S':
  318. conf.no_symlinks = 1;
  319. break;
  320. case 'D':
  321. conf.no_dirlists = 1;
  322. break;
  323. case 'R':
  324. conf.rfc1918_filter = 1;
  325. break;
  326. case 'n':
  327. conf.max_script_requests = atoi(optarg);
  328. break;
  329. case 'N':
  330. conf.max_connections = atoi(optarg);
  331. break;
  332. case 'x':
  333. fixup_prefix(optarg);
  334. conf.cgi_prefix = optarg;
  335. break;
  336. case 'y':
  337. alias = calloc(1, sizeof(*alias));
  338. if (!alias) {
  339. fprintf(stderr, "Error: failed to allocate alias\n");
  340. exit(1);
  341. }
  342. alias->alias = strdup(optarg);
  343. alias->path = strchr(alias->alias, '=');
  344. if (alias->path)
  345. *alias->path++ = 0;
  346. list_add(&alias->list, &conf.cgi_alias);
  347. break;
  348. case 'i':
  349. optarg = strdup(optarg);
  350. port = strchr(optarg, '=');
  351. if (optarg[0] != '.' || !port) {
  352. fprintf(stderr, "Error: Invalid interpreter: %s\n",
  353. optarg);
  354. exit(1);
  355. }
  356. *port++ = 0;
  357. uh_interpreter_add(optarg, port);
  358. break;
  359. case 't':
  360. conf.script_timeout = atoi(optarg);
  361. break;
  362. case 'T':
  363. conf.network_timeout = atoi(optarg);
  364. break;
  365. case 'k':
  366. conf.http_keepalive = atoi(optarg);
  367. break;
  368. case 'A':
  369. conf.tcp_keepalive = atoi(optarg);
  370. break;
  371. case 'f':
  372. nofork = 1;
  373. break;
  374. case 'd':
  375. optarg = strdup(optarg);
  376. port = alloca(strlen(optarg) + 1);
  377. if (!port)
  378. return -1;
  379. /* "decode" plus to space to retain compat */
  380. for (opt = 0; optarg[opt]; opt++)
  381. if (optarg[opt] == '+')
  382. optarg[opt] = ' ';
  383. /* opt now contains strlen(optarg) -- no need to re-scan */
  384. if (uh_urldecode(port, opt, optarg, opt) < 0) {
  385. fprintf(stderr, "uhttpd: invalid encoding\n");
  386. return -1;
  387. }
  388. printf("%s", port);
  389. return 0;
  390. break;
  391. /* basic auth realm */
  392. case 'r':
  393. conf.realm = optarg;
  394. break;
  395. /* md5 crypt */
  396. case 'm':
  397. printf("%s\n", crypt(optarg, "$1$"));
  398. return 0;
  399. break;
  400. /* config file */
  401. case 'c':
  402. conf.file = optarg;
  403. break;
  404. #ifdef HAVE_LUA
  405. case 'l':
  406. case 'L':
  407. if (ch == 'l') {
  408. if (lua_prefix)
  409. fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
  410. ch, lua_prefix);
  411. lua_prefix = optarg;
  412. }
  413. else {
  414. if (lua_handler)
  415. fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
  416. ch, lua_handler);
  417. lua_handler = optarg;
  418. }
  419. if (lua_prefix && lua_handler) {
  420. add_lua_prefix(lua_prefix, lua_handler);
  421. lua_prefix = NULL;
  422. lua_handler = NULL;
  423. }
  424. break;
  425. #else
  426. case 'l':
  427. case 'L':
  428. fprintf(stderr, "uhttpd: Lua support not compiled, "
  429. "ignoring -%c\n", ch);
  430. break;
  431. #endif
  432. #ifdef HAVE_UCODE
  433. case 'o':
  434. case 'O':
  435. if (ch == 'o') {
  436. if (ucode_prefix)
  437. fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
  438. ch, ucode_prefix);
  439. ucode_prefix = optarg;
  440. }
  441. else {
  442. if (ucode_handler)
  443. fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
  444. ch, ucode_handler);
  445. ucode_handler = optarg;
  446. }
  447. if (ucode_prefix && ucode_handler) {
  448. add_ucode_prefix(ucode_prefix, ucode_handler);
  449. ucode_prefix = NULL;
  450. ucode_handler = NULL;
  451. }
  452. break;
  453. #else
  454. case 'o':
  455. case 'O':
  456. fprintf(stderr, "uhttpd: ucode support not compiled, "
  457. "ignoring -%c\n", ch);
  458. break;
  459. #endif
  460. #ifdef HAVE_UBUS
  461. case 'a':
  462. conf.ubus_noauth = 1;
  463. break;
  464. case 'u':
  465. conf.ubus_prefix = optarg;
  466. break;
  467. case 'U':
  468. conf.ubus_socket = optarg;
  469. break;
  470. case 'X':
  471. conf.ubus_cors = 1;
  472. break;
  473. case 'e':
  474. conf.events_retry = atoi(optarg);
  475. break;
  476. #else
  477. case 'a':
  478. case 'u':
  479. case 'U':
  480. case 'X':
  481. case 'e':
  482. fprintf(stderr, "uhttpd: UBUS support not compiled, "
  483. "ignoring -%c\n", ch);
  484. break;
  485. #endif
  486. default:
  487. return usage(argv[0]);
  488. }
  489. }
  490. uh_config_parse();
  491. if (!conf.docroot) {
  492. if (!realpath(".", uh_buf)) {
  493. fprintf(stderr, "Error: Unable to determine work dir\n");
  494. return 1;
  495. }
  496. conf.docroot = strdup(uh_buf);
  497. }
  498. init_defaults_post();
  499. if (!bound) {
  500. fprintf(stderr, "Error: No sockets bound, unable to continue\n");
  501. return 1;
  502. }
  503. #ifdef HAVE_TLS
  504. if (n_tls) {
  505. if (!tls_crt || !tls_key) {
  506. fprintf(stderr, "Please specify a certificate and "
  507. "a key file to enable SSL support\n");
  508. return 1;
  509. }
  510. if (uh_tls_init(tls_key, tls_crt, tls_ciphers))
  511. return 1;
  512. }
  513. #endif
  514. #ifdef HAVE_LUA
  515. if (lua_handler || lua_prefix) {
  516. fprintf(stderr, "Need handler and prefix to enable Lua support\n");
  517. return 1;
  518. }
  519. if (!list_empty(&conf.lua_prefix) && uh_plugin_init("uhttpd_lua.so"))
  520. return 1;
  521. #endif
  522. #ifdef HAVE_UCODE
  523. if (ucode_handler || ucode_prefix) {
  524. fprintf(stderr, "Need handler and prefix to enable ucode support\n");
  525. return 1;
  526. }
  527. if (!list_empty(&conf.ucode_prefix) && uh_plugin_init("uhttpd_ucode.so"))
  528. return 1;
  529. #endif
  530. #ifdef HAVE_UBUS
  531. if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
  532. return 1;
  533. #endif
  534. /* fork (if not disabled) */
  535. if (!nofork) {
  536. switch (fork()) {
  537. case -1:
  538. perror("fork()");
  539. exit(1);
  540. case 0:
  541. /* daemon setup */
  542. if (chdir("/"))
  543. perror("chdir()");
  544. cur_fd = open("/dev/null", O_WRONLY);
  545. if (cur_fd > 0) {
  546. dup2(cur_fd, 0);
  547. dup2(cur_fd, 1);
  548. dup2(cur_fd, 2);
  549. }
  550. break;
  551. default:
  552. exit(0);
  553. }
  554. }
  555. return run_server();
  556. }