ucode.c 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. #include <libubox/blobmsg.h>
  20. #include <ucode/compiler.h>
  21. #include <ucode/lib.h>
  22. #include <ucode/vm.h>
  23. #include <stdio.h>
  24. #include <poll.h>
  25. #include "uhttpd.h"
  26. #include "plugin.h"
  27. #define UH_UCODE_CB "handle_request"
  28. static const struct uhttpd_ops *ops;
  29. static struct config *_conf;
  30. #define conf (*_conf)
  31. static struct ucode_prefix *current_prefix;
  32. static uc_value_t *
  33. uh_ucode_recv(uc_vm_t *vm, size_t nargs)
  34. {
  35. static struct pollfd pfd = { .fd = STDIN_FILENO, .events = POLLIN };
  36. int data_len = 0, len = BUFSIZ, rlen, r;
  37. uc_value_t *v = uc_fn_arg(0);
  38. uc_stringbuf_t *buf;
  39. if (ucv_type(v) == UC_INTEGER) {
  40. len = ucv_int64_get(v);
  41. }
  42. else if (v != NULL) {
  43. uc_vm_raise_exception(vm, EXCEPTION_TYPE, "Argument not an integer");
  44. return NULL;
  45. }
  46. buf = ucv_stringbuf_new();
  47. while (len > 0) {
  48. rlen = (len < BUFSIZ) ? len : BUFSIZ;
  49. if (printbuf_memset(buf, -1, 0, rlen)) {
  50. uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, "Out of memory");
  51. printbuf_free(buf);
  52. return NULL;
  53. }
  54. buf->bpos -= rlen;
  55. r = read(STDIN_FILENO, buf->buf + buf->bpos, rlen);
  56. if (r < 0) {
  57. if (errno == EWOULDBLOCK || errno == EAGAIN) {
  58. pfd.revents = 0;
  59. poll(&pfd, 1, 1000);
  60. if (pfd.revents & POLLIN)
  61. continue;
  62. }
  63. if (errno == EINTR)
  64. continue;
  65. if (!data_len)
  66. data_len = -1;
  67. break;
  68. }
  69. buf->bpos += r;
  70. data_len += r;
  71. len -= r;
  72. if (r != rlen)
  73. break;
  74. }
  75. if (data_len > 0) {
  76. /* add final guard \0 but do not count it */
  77. if (printbuf_memset(buf, -1, 0, 1)) {
  78. uc_vm_raise_exception(vm, EXCEPTION_RUNTIME, "Out of memory");
  79. printbuf_free(buf);
  80. return NULL;
  81. }
  82. buf->bpos--;
  83. return ucv_stringbuf_finish(buf);
  84. }
  85. printbuf_free(buf);
  86. return NULL;
  87. }
  88. static uc_value_t *
  89. uh_ucode_send(uc_vm_t *vm, size_t nargs)
  90. {
  91. uc_value_t *val;
  92. size_t arridx;
  93. ssize_t len = 0;
  94. char *p;
  95. for (arridx = 0; arridx < nargs; arridx++) {
  96. val = uc_fn_arg(arridx);
  97. if (ucv_type(val) == UC_STRING) {
  98. len += write(STDOUT_FILENO, ucv_string_get(val), ucv_string_length(val));
  99. }
  100. else if (val != NULL) {
  101. p = ucv_to_string(vm, val);
  102. len += p ? write(STDOUT_FILENO, p, strlen(p)) : 0;
  103. free(p);
  104. }
  105. }
  106. return ucv_int64_new(len);
  107. }
  108. static uc_value_t *
  109. uh_ucode_strconvert(uc_vm_t *vm, size_t nargs, int (*convert)(char *, int, const char *, int))
  110. {
  111. uc_value_t *val = uc_fn_arg(0);
  112. static char out_buf[4096];
  113. int out_len;
  114. char *p;
  115. if (ucv_type(val) == UC_STRING) {
  116. out_len = convert(out_buf, sizeof(out_buf),
  117. ucv_string_get(val), ucv_string_length(val));
  118. }
  119. else if (val != NULL) {
  120. p = ucv_to_string(vm, val);
  121. out_len = p ? convert(out_buf, sizeof(out_buf), p, strlen(p)) : 0;
  122. free(p);
  123. }
  124. else {
  125. out_len = 0;
  126. }
  127. if (out_len < 0) {
  128. const char *error;
  129. if (out_len == -1)
  130. error = "buffer overflow";
  131. else
  132. error = "malformed string";
  133. uc_vm_raise_exception(vm, EXCEPTION_RUNTIME,
  134. "%s on URL conversion\n", error);
  135. return NULL;
  136. }
  137. return ucv_string_new_length(out_buf, out_len);
  138. }
  139. static uc_value_t *
  140. uh_ucode_urldecode(uc_vm_t *vm, size_t nargs)
  141. {
  142. return uh_ucode_strconvert(vm, nargs, ops->urldecode);
  143. }
  144. static uc_value_t *
  145. uh_ucode_urlencode(uc_vm_t *vm, size_t nargs)
  146. {
  147. return uh_ucode_strconvert(vm, nargs, ops->urlencode);
  148. }
  149. static uc_parse_config_t config = {
  150. .strict_declarations = false,
  151. .lstrip_blocks = true,
  152. .trim_blocks = true
  153. };
  154. static void
  155. uh_ucode_exception(uc_vm_t *vm, uc_exception_t *ex)
  156. {
  157. uc_value_t *ctx;
  158. if (ex->type == EXCEPTION_EXIT)
  159. return;
  160. printf("Status: 500 Internal Server Error\r\n\r\n"
  161. "Exception while executing ucode program %s:\n",
  162. current_prefix->handler);
  163. switch (ex->type) {
  164. case EXCEPTION_SYNTAX: printf("Syntax error"); break;
  165. case EXCEPTION_RUNTIME: printf("Runtime error"); break;
  166. case EXCEPTION_TYPE: printf("Type error"); break;
  167. case EXCEPTION_REFERENCE: printf("Reference error"); break;
  168. default: printf("Error");
  169. }
  170. printf(": %s\n", ex->message);
  171. ctx = ucv_object_get(ucv_array_get(ex->stacktrace, 0), "context", NULL);
  172. if (ctx)
  173. printf("%s\n", ucv_string_get(ctx));
  174. }
  175. static void
  176. uh_ucode_state_init(struct ucode_prefix *ucode)
  177. {
  178. char *syntax_error = NULL;
  179. uc_vm_t *vm = &ucode->ctx;
  180. uc_program_t *handler;
  181. uc_vm_status_t status;
  182. uc_source_t *src;
  183. uc_value_t *v;
  184. int exitcode;
  185. uc_search_path_init(&config.module_search_path);
  186. uc_vm_init(vm, &config);
  187. uc_stdlib_load(uc_vm_scope_get(vm));
  188. /* build uhttpd api table */
  189. v = ucv_object_new(vm);
  190. ucv_object_add(v, "send", ucv_cfunction_new("send", uh_ucode_send));
  191. ucv_object_add(v, "sendc", ucv_get(ucv_object_get(v, "send", NULL)));
  192. ucv_object_add(v, "recv", ucv_cfunction_new("recv", uh_ucode_recv));
  193. ucv_object_add(v, "urldecode", ucv_cfunction_new("urldecode", uh_ucode_urldecode));
  194. ucv_object_add(v, "urlencode", ucv_cfunction_new("urlencode", uh_ucode_urlencode));
  195. ucv_object_add(v, "docroot", ucv_string_new(conf.docroot));
  196. ucv_object_add(uc_vm_scope_get(vm), "uhttpd", v);
  197. src = uc_source_new_file(ucode->handler);
  198. if (!src) {
  199. fprintf(stderr, "Error: Unable to open ucode handler: %s\n",
  200. strerror(errno));
  201. exit(1);
  202. }
  203. handler = uc_compile(&config, src, &syntax_error);
  204. uc_source_put(src);
  205. if (!handler) {
  206. fprintf(stderr, "Error: Unable to compile ucode handler: %s\n",
  207. syntax_error);
  208. exit(1);
  209. }
  210. free(syntax_error);
  211. vm->output = fopen("/dev/null", "w");
  212. if (!vm->output) {
  213. fprintf(stderr, "Error: Unable to open /dev/null for writing: %s\n",
  214. strerror(errno));
  215. exit(1);
  216. }
  217. status = uc_vm_execute(vm, handler, &v);
  218. exitcode = (int)ucv_int64_get(v);
  219. uc_program_put(handler);
  220. ucv_put(v);
  221. switch (status) {
  222. case STATUS_OK:
  223. break;
  224. case STATUS_EXIT:
  225. fprintf(stderr, "Error: The ucode handler invoked exit(%d)\n", exitcode);
  226. exit(exitcode ? exitcode : 1);
  227. case ERROR_COMPILE:
  228. fprintf(stderr, "Error: Compilation error while executing ucode handler\n");
  229. exit(1);
  230. case ERROR_RUNTIME:
  231. fprintf(stderr, "Error: Runtime error while executing ucode handler\n");
  232. exit(2);
  233. }
  234. v = ucv_object_get(uc_vm_scope_get(vm), UH_UCODE_CB, NULL);
  235. if (!ucv_is_callable(v)) {
  236. fprintf(stderr, "Error: The ucode handler declares no " UH_UCODE_CB "() callback.\n");
  237. exit(1);
  238. }
  239. uc_vm_exception_handler_set(vm, uh_ucode_exception);
  240. ucv_gc(vm);
  241. fclose(vm->output);
  242. vm->output = stdout;
  243. }
  244. static void
  245. ucode_main(struct client *cl, struct path_info *pi, char *url)
  246. {
  247. uc_vm_t *vm = &current_prefix->ctx;
  248. uc_value_t *req, *hdr, *res;
  249. int path_len, prefix_len;
  250. struct blob_attr *cur;
  251. struct env_var *var;
  252. char *str;
  253. int rem;
  254. /* new env table for this request */
  255. req = ucv_object_new(vm);
  256. prefix_len = strlen(pi->name);
  257. path_len = strlen(url);
  258. str = strchr(url, '?');
  259. if (str) {
  260. if (*(str + 1))
  261. pi->query = str + 1;
  262. path_len = str - url;
  263. }
  264. if (prefix_len > 0 && pi->name[prefix_len - 1] == '/')
  265. prefix_len--;
  266. if (path_len > prefix_len) {
  267. ucv_object_add(req, "PATH_INFO",
  268. ucv_string_new_length(url + prefix_len, path_len - prefix_len));
  269. }
  270. for (var = ops->get_process_vars(cl, pi); var->name; var++) {
  271. if (!var->value)
  272. continue;
  273. ucv_object_add(req, var->name, ucv_string_new(var->value));
  274. }
  275. ucv_object_add(req, "HTTP_VERSION",
  276. ucv_double_new(0.9 + (cl->request.version / 10.0)));
  277. hdr = ucv_object_new(vm);
  278. blob_for_each_attr(cur, cl->hdr.head, rem)
  279. ucv_object_add(hdr, blobmsg_name(cur), ucv_string_new(blobmsg_data(cur)));
  280. ucv_object_add(req, "headers", hdr);
  281. res = uc_vm_invoke(vm, UH_UCODE_CB, 1, req);
  282. ucv_put(req);
  283. ucv_put(res);
  284. exit(0);
  285. }
  286. static void
  287. ucode_handle_request(struct client *cl, char *url, struct path_info *pi)
  288. {
  289. struct ucode_prefix *p;
  290. static struct path_info _pi;
  291. list_for_each_entry(p, &conf.ucode_prefix, list) {
  292. if (!ops->path_match(p->prefix, url))
  293. continue;
  294. pi = &_pi;
  295. pi->name = p->prefix;
  296. pi->phys = p->handler;
  297. current_prefix = p;
  298. if (!ops->create_process(cl, pi, url, ucode_main)) {
  299. ops->client_error(cl, 500, "Internal Server Error",
  300. "Failed to create CGI process: %s",
  301. strerror(errno));
  302. }
  303. return;
  304. }
  305. ops->client_error(cl, 500, "Internal Server Error",
  306. "Failed to lookup matching handler");
  307. }
  308. static bool
  309. check_ucode_url(const char *url)
  310. {
  311. struct ucode_prefix *p;
  312. list_for_each_entry(p, &conf.ucode_prefix, list)
  313. if (ops->path_match(p->prefix, url))
  314. return true;
  315. return false;
  316. }
  317. static struct dispatch_handler ucode_dispatch = {
  318. .script = true,
  319. .check_url = check_ucode_url,
  320. .handle_request = ucode_handle_request,
  321. };
  322. static int
  323. ucode_plugin_init(const struct uhttpd_ops *o, struct config *c)
  324. {
  325. struct ucode_prefix *p;
  326. ops = o;
  327. _conf = c;
  328. list_for_each_entry(p, &conf.ucode_prefix, list)
  329. uh_ucode_state_init(p);
  330. ops->dispatch_add(&ucode_dispatch);
  331. return 0;
  332. }
  333. struct uhttpd_plugin uhttpd_plugin = {
  334. .init = ucode_plugin_init,
  335. };