main.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. " -I string Use given filename as index for directories, multiple allowed\n"
  125. " -S Do not follow symbolic links outside of the docroot\n"
  126. " -D Do not allow directory listings, send 403 instead\n"
  127. " -R Enable RFC1918 filter\n"
  128. " -n count Maximum allowed number of concurrent script requests\n"
  129. " -N count Maximum allowed number of concurrent connections\n"
  130. #ifdef HAVE_LUA
  131. " -l string URL prefix for Lua handler, default is '/lua'\n"
  132. " -L file Lua handler script, omit to disable Lua\n"
  133. #endif
  134. #ifdef HAVE_UBUS
  135. " -u string URL prefix for UBUS via JSON-RPC handler\n"
  136. " -U file Override ubus socket path\n"
  137. " -a Do not authenticate JSON-RPC requests against UBUS session api\n"
  138. " -X Enable CORS HTTP headers on JSON-RPC api\n"
  139. " -e Events subscription reconnection time (retry value)\n"
  140. #endif
  141. " -x string URL prefix for CGI handler, default is '/cgi-bin'\n"
  142. " -y alias[=path] URL alias handle\n"
  143. " -i .ext=path Use interpreter at path for files with the given extension\n"
  144. " -t seconds CGI, Lua and UBUS script timeout in seconds, default is 60\n"
  145. " -T seconds Network timeout in seconds, default is 30\n"
  146. " -k seconds HTTP keepalive timeout\n"
  147. " -A seconds TCP keepalive timeout, default is unset\n"
  148. " -d string URL decode given string\n"
  149. " -r string Specify basic auth realm\n"
  150. " -m string MD5 crypt given string\n"
  151. "\n", name
  152. );
  153. return 1;
  154. }
  155. static void init_defaults_pre(void)
  156. {
  157. conf.script_timeout = 60;
  158. conf.network_timeout = 30;
  159. conf.http_keepalive = 20;
  160. conf.max_script_requests = 3;
  161. conf.max_connections = 100;
  162. conf.realm = "Protected Area";
  163. conf.cgi_prefix = "/cgi-bin";
  164. conf.cgi_path = "/sbin:/usr/sbin:/bin:/usr/bin";
  165. INIT_LIST_HEAD(&conf.cgi_alias);
  166. INIT_LIST_HEAD(&conf.lua_prefix);
  167. }
  168. static void init_defaults_post(void)
  169. {
  170. uh_index_add("index.html");
  171. uh_index_add("index.htm");
  172. uh_index_add("default.html");
  173. uh_index_add("default.htm");
  174. if (conf.cgi_prefix) {
  175. char *str = malloc(strlen(conf.docroot) + strlen(conf.cgi_prefix) + 1);
  176. strcpy(str, conf.docroot);
  177. strcat(str, conf.cgi_prefix);
  178. conf.cgi_docroot_path = str;
  179. conf.cgi_prefix_len = strlen(conf.cgi_prefix);
  180. };
  181. }
  182. static void fixup_prefix(char *str)
  183. {
  184. int len;
  185. if (!str || !str[0])
  186. return;
  187. len = strlen(str) - 1;
  188. while (len >= 0 && str[len] == '/')
  189. len--;
  190. str[len + 1] = 0;
  191. }
  192. #ifdef HAVE_LUA
  193. static void add_lua_prefix(const char *prefix, const char *handler) {
  194. struct lua_prefix *p;
  195. char *pprefix, *phandler;
  196. p = calloc_a(sizeof(*p),
  197. &pprefix, strlen(prefix) + 1,
  198. &phandler, strlen(handler) + 1);
  199. if (!p)
  200. return;
  201. p->prefix = strcpy(pprefix, prefix);
  202. p->handler = strcpy(phandler, handler);
  203. list_add_tail(&p->list, &conf.lua_prefix);
  204. }
  205. #endif
  206. int main(int argc, char **argv)
  207. {
  208. struct alias *alias;
  209. bool nofork = false;
  210. char *port;
  211. int opt, ch;
  212. int cur_fd;
  213. int bound = 0;
  214. #ifdef HAVE_TLS
  215. int n_tls = 0;
  216. const char *tls_key = NULL, *tls_crt = NULL, *tls_ciphers = NULL;
  217. #endif
  218. #ifdef HAVE_LUA
  219. const char *lua_prefix = NULL, *lua_handler = NULL;
  220. #endif
  221. BUILD_BUG_ON(sizeof(uh_buf) < PATH_MAX);
  222. uh_dispatch_add(&cgi_dispatch);
  223. init_defaults_pre();
  224. signal(SIGPIPE, SIG_IGN);
  225. while ((ch = getopt(argc, argv, "A:aC:c:Dd:E:e:fh:H:I:i:K:k:L:l:m:N:n:P:p:qRr:Ss:T:t:U:u:Xx:y:")) != -1) {
  226. switch(ch) {
  227. #ifdef HAVE_TLS
  228. case 'C':
  229. tls_crt = optarg;
  230. break;
  231. case 'K':
  232. tls_key = optarg;
  233. break;
  234. case 'P':
  235. tls_ciphers = optarg;
  236. break;
  237. case 'q':
  238. conf.tls_redirect = 1;
  239. break;
  240. case 's':
  241. n_tls++;
  242. /* fall through */
  243. #else
  244. case 'C':
  245. case 'K':
  246. case 'P':
  247. case 'q':
  248. case 's':
  249. fprintf(stderr, "uhttpd: TLS support not compiled, "
  250. "ignoring -%c\n", ch);
  251. break;
  252. #endif
  253. case 'p':
  254. optarg = strdup(optarg);
  255. bound += add_listener_arg(optarg, (ch == 's'));
  256. break;
  257. case 'h':
  258. if (!realpath(optarg, uh_buf)) {
  259. fprintf(stderr, "Error: Invalid directory %s: %s\n",
  260. optarg, strerror(errno));
  261. exit(1);
  262. }
  263. conf.docroot = strdup(uh_buf);
  264. break;
  265. case 'H':
  266. if (uh_handler_add(optarg)) {
  267. fprintf(stderr, "Error: Failed to load handler script %s\n",
  268. optarg);
  269. exit(1);
  270. }
  271. break;
  272. case 'E':
  273. if (optarg[0] != '/') {
  274. fprintf(stderr, "Error: Invalid error handler: %s\n",
  275. optarg);
  276. exit(1);
  277. }
  278. conf.error_handler = optarg;
  279. break;
  280. case 'I':
  281. if (optarg[0] == '/') {
  282. fprintf(stderr, "Error: Invalid index page: %s\n",
  283. optarg);
  284. exit(1);
  285. }
  286. uh_index_add(optarg);
  287. break;
  288. case 'S':
  289. conf.no_symlinks = 1;
  290. break;
  291. case 'D':
  292. conf.no_dirlists = 1;
  293. break;
  294. case 'R':
  295. conf.rfc1918_filter = 1;
  296. break;
  297. case 'n':
  298. conf.max_script_requests = atoi(optarg);
  299. break;
  300. case 'N':
  301. conf.max_connections = atoi(optarg);
  302. break;
  303. case 'x':
  304. fixup_prefix(optarg);
  305. conf.cgi_prefix = optarg;
  306. break;
  307. case 'y':
  308. alias = calloc(1, sizeof(*alias));
  309. if (!alias) {
  310. fprintf(stderr, "Error: failed to allocate alias\n");
  311. exit(1);
  312. }
  313. alias->alias = strdup(optarg);
  314. alias->path = strchr(alias->alias, '=');
  315. if (alias->path)
  316. *alias->path++ = 0;
  317. list_add(&alias->list, &conf.cgi_alias);
  318. break;
  319. case 'i':
  320. optarg = strdup(optarg);
  321. port = strchr(optarg, '=');
  322. if (optarg[0] != '.' || !port) {
  323. fprintf(stderr, "Error: Invalid interpreter: %s\n",
  324. optarg);
  325. exit(1);
  326. }
  327. *port++ = 0;
  328. uh_interpreter_add(optarg, port);
  329. break;
  330. case 't':
  331. conf.script_timeout = atoi(optarg);
  332. break;
  333. case 'T':
  334. conf.network_timeout = atoi(optarg);
  335. break;
  336. case 'k':
  337. conf.http_keepalive = atoi(optarg);
  338. break;
  339. case 'A':
  340. conf.tcp_keepalive = atoi(optarg);
  341. break;
  342. case 'f':
  343. nofork = 1;
  344. break;
  345. case 'd':
  346. optarg = strdup(optarg);
  347. port = alloca(strlen(optarg) + 1);
  348. if (!port)
  349. return -1;
  350. /* "decode" plus to space to retain compat */
  351. for (opt = 0; optarg[opt]; opt++)
  352. if (optarg[opt] == '+')
  353. optarg[opt] = ' ';
  354. /* opt now contains strlen(optarg) -- no need to re-scan */
  355. if (uh_urldecode(port, opt, optarg, opt) < 0) {
  356. fprintf(stderr, "uhttpd: invalid encoding\n");
  357. return -1;
  358. }
  359. printf("%s", port);
  360. return 0;
  361. break;
  362. /* basic auth realm */
  363. case 'r':
  364. conf.realm = optarg;
  365. break;
  366. /* md5 crypt */
  367. case 'm':
  368. printf("%s\n", crypt(optarg, "$1$"));
  369. return 0;
  370. break;
  371. /* config file */
  372. case 'c':
  373. conf.file = optarg;
  374. break;
  375. #ifdef HAVE_LUA
  376. case 'l':
  377. case 'L':
  378. if (ch == 'l') {
  379. if (lua_prefix)
  380. fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
  381. ch, lua_prefix);
  382. lua_prefix = optarg;
  383. }
  384. else {
  385. if (lua_handler)
  386. fprintf(stderr, "uhttpd: Ignoring previous -%c %s\n",
  387. ch, lua_handler);
  388. lua_handler = optarg;
  389. }
  390. if (lua_prefix && lua_handler) {
  391. add_lua_prefix(lua_prefix, lua_handler);
  392. lua_prefix = NULL;
  393. lua_handler = NULL;
  394. }
  395. break;
  396. #else
  397. case 'l':
  398. case 'L':
  399. fprintf(stderr, "uhttpd: Lua support not compiled, "
  400. "ignoring -%c\n", ch);
  401. break;
  402. #endif
  403. #ifdef HAVE_UBUS
  404. case 'a':
  405. conf.ubus_noauth = 1;
  406. break;
  407. case 'u':
  408. conf.ubus_prefix = optarg;
  409. break;
  410. case 'U':
  411. conf.ubus_socket = optarg;
  412. break;
  413. case 'X':
  414. conf.ubus_cors = 1;
  415. break;
  416. case 'e':
  417. conf.events_retry = atoi(optarg);
  418. break;
  419. #else
  420. case 'a':
  421. case 'u':
  422. case 'U':
  423. case 'X':
  424. case 'e':
  425. fprintf(stderr, "uhttpd: UBUS support not compiled, "
  426. "ignoring -%c\n", ch);
  427. break;
  428. #endif
  429. default:
  430. return usage(argv[0]);
  431. }
  432. }
  433. uh_config_parse();
  434. if (!conf.docroot) {
  435. if (!realpath(".", uh_buf)) {
  436. fprintf(stderr, "Error: Unable to determine work dir\n");
  437. return 1;
  438. }
  439. conf.docroot = strdup(uh_buf);
  440. }
  441. init_defaults_post();
  442. if (!bound) {
  443. fprintf(stderr, "Error: No sockets bound, unable to continue\n");
  444. return 1;
  445. }
  446. #ifdef HAVE_TLS
  447. if (n_tls) {
  448. if (!tls_crt || !tls_key) {
  449. fprintf(stderr, "Please specify a certificate and "
  450. "a key file to enable SSL support\n");
  451. return 1;
  452. }
  453. if (uh_tls_init(tls_key, tls_crt, tls_ciphers))
  454. return 1;
  455. }
  456. #endif
  457. #ifdef HAVE_LUA
  458. if (lua_handler || lua_prefix) {
  459. fprintf(stderr, "Need handler and prefix to enable Lua support\n");
  460. return 1;
  461. }
  462. if (!list_empty(&conf.lua_prefix) && uh_plugin_init("uhttpd_lua.so"))
  463. return 1;
  464. #endif
  465. #ifdef HAVE_UBUS
  466. if (conf.ubus_prefix && uh_plugin_init("uhttpd_ubus.so"))
  467. return 1;
  468. #endif
  469. /* fork (if not disabled) */
  470. if (!nofork) {
  471. switch (fork()) {
  472. case -1:
  473. perror("fork()");
  474. exit(1);
  475. case 0:
  476. /* daemon setup */
  477. if (chdir("/"))
  478. perror("chdir()");
  479. cur_fd = open("/dev/null", O_WRONLY);
  480. if (cur_fd > 0) {
  481. dup2(cur_fd, 0);
  482. dup2(cur_fd, 1);
  483. dup2(cur_fd, 2);
  484. }
  485. break;
  486. default:
  487. exit(0);
  488. }
  489. }
  490. return run_server();
  491. }