http.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*!
  19. * \file
  20. * \brief http server for AMI access
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * This program implements a tiny http server
  25. * and was inspired by micro-httpd by Jef Poskanzer
  26. *
  27. * \ref AstHTTP - AMI over the http protocol
  28. */
  29. #include "asterisk.h"
  30. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  31. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  32. #include "asterisk/network.h"
  33. #include <time.h>
  34. #include <sys/time.h>
  35. #include <sys/stat.h>
  36. #include <sys/signal.h>
  37. #include <fcntl.h>
  38. #ifdef ENABLE_UPLOADS
  39. #include <gmime/gmime.h>
  40. #endif /* ENABLE_UPLOADS */
  41. #include "asterisk/cli.h"
  42. #include "asterisk/tcptls.h"
  43. #include "asterisk/http.h"
  44. #include "asterisk/utils.h"
  45. #include "asterisk/strings.h"
  46. #include "asterisk/config.h"
  47. #include "asterisk/stringfields.h"
  48. #include "asterisk/ast_version.h"
  49. #include "asterisk/manager.h"
  50. #define MAX_PREFIX 80
  51. /* See http.h for more information about the SSL implementation */
  52. #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
  53. #define DO_SSL /* comment in/out if you want to support ssl */
  54. #endif
  55. static struct ast_tls_config http_tls_cfg;
  56. static void *httpd_helper_thread(void *arg);
  57. /*!
  58. * we have up to two accepting threads, one for http, one for https
  59. */
  60. static struct server_args http_desc = {
  61. .accept_fd = -1,
  62. .master = AST_PTHREADT_NULL,
  63. .tls_cfg = NULL,
  64. .poll_timeout = -1,
  65. .name = "http server",
  66. .accept_fn = ast_tcptls_server_root,
  67. .worker_fn = httpd_helper_thread,
  68. };
  69. static struct server_args https_desc = {
  70. .accept_fd = -1,
  71. .master = AST_PTHREADT_NULL,
  72. .tls_cfg = &http_tls_cfg,
  73. .poll_timeout = -1,
  74. .name = "https server",
  75. .accept_fn = ast_tcptls_server_root,
  76. .worker_fn = httpd_helper_thread,
  77. };
  78. static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
  79. #ifdef ENABLE_UPLOADS
  80. struct ast_http_post_mapping {
  81. AST_RWLIST_ENTRY(ast_http_post_mapping) entry;
  82. char *from;
  83. char *to;
  84. };
  85. static AST_RWLIST_HEAD_STATIC(post_mappings, ast_http_post_mapping);
  86. struct mime_cbinfo {
  87. int count;
  88. const char *post_dir;
  89. };
  90. #endif /* ENABLE_UPLOADS */
  91. /* all valid URIs must be prepended by the string in prefix. */
  92. static char prefix[MAX_PREFIX];
  93. static int enablestatic;
  94. /*! \brief Limit the kinds of files we're willing to serve up */
  95. static struct {
  96. const char *ext;
  97. const char *mtype;
  98. } mimetypes[] = {
  99. { "png", "image/png" },
  100. { "jpg", "image/jpeg" },
  101. { "js", "application/x-javascript" },
  102. { "wav", "audio/x-wav" },
  103. { "mp3", "audio/mpeg" },
  104. { "svg", "image/svg+xml" },
  105. { "svgz", "image/svg+xml" },
  106. { "gif", "image/gif" },
  107. };
  108. struct http_uri_redirect {
  109. AST_LIST_ENTRY(http_uri_redirect) entry;
  110. char *dest;
  111. char target[0];
  112. };
  113. static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
  114. static const char *ftype2mtype(const char *ftype, char *wkspace, int wkspacelen)
  115. {
  116. int x;
  117. if (ftype) {
  118. for (x=0;x<sizeof(mimetypes) / sizeof(mimetypes[0]); x++) {
  119. if (!strcasecmp(ftype, mimetypes[x].ext))
  120. return mimetypes[x].mtype;
  121. }
  122. }
  123. snprintf(wkspace, wkspacelen, "text/%s", ftype ? ftype : "plain");
  124. return wkspace;
  125. }
  126. static uint32_t manid_from_vars(struct ast_variable *sid) {
  127. uint32_t mngid;
  128. while (sid && strcmp(sid->name, "mansession_id"))
  129. sid = sid->next;
  130. if (!sid || sscanf(sid->value, "%30x", &mngid) != 1)
  131. return 0;
  132. return mngid;
  133. }
  134. static struct ast_str *static_callback(struct ast_tcptls_session_instance *ser, const char *uri, struct ast_variable *vars, int *status, char **title, int *contentlength)
  135. {
  136. char *path;
  137. char *ftype;
  138. const char *mtype;
  139. char wkspace[80];
  140. struct stat st;
  141. int len;
  142. int fd;
  143. struct timeval tv = ast_tvnow();
  144. char buf[256];
  145. struct ast_tm tm;
  146. /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
  147. substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
  148. if (!enablestatic || ast_strlen_zero(uri))
  149. goto out403;
  150. /* Disallow any funny filenames at all */
  151. if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0]))
  152. goto out403;
  153. if (strstr(uri, "/.."))
  154. goto out403;
  155. if ((ftype = strrchr(uri, '.')))
  156. ftype++;
  157. mtype = ftype2mtype(ftype, wkspace, sizeof(wkspace));
  158. /* Cap maximum length */
  159. len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5;
  160. if (len > 1024)
  161. goto out403;
  162. path = alloca(len);
  163. sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
  164. if (stat(path, &st))
  165. goto out404;
  166. if (S_ISDIR(st.st_mode))
  167. goto out404;
  168. fd = open(path, O_RDONLY);
  169. if (fd < 0)
  170. goto out403;
  171. if (strstr(path, "/private/") && !astman_is_authed(manid_from_vars(vars))) {
  172. goto out403;
  173. }
  174. ast_strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&tv, &tm, "GMT"));
  175. fprintf(ser->f, "HTTP/1.1 200 OK\r\n"
  176. "Server: Asterisk/%s\r\n"
  177. "Date: %s\r\n"
  178. "Connection: close\r\n"
  179. "Cache-Control: private\r\n"
  180. "Content-Length: %d\r\n"
  181. "Content-type: %s\r\n\r\n",
  182. ast_get_version(), buf, (int) st.st_size, mtype);
  183. while ((len = read(fd, buf, sizeof(buf))) > 0)
  184. if (fwrite(buf, 1, len, ser->f) != len) {
  185. ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
  186. }
  187. close(fd);
  188. return NULL;
  189. out404:
  190. return ast_http_error((*status = 404),
  191. (*title = ast_strdup("Not Found")),
  192. NULL, "The requested URL was not found on this server.");
  193. out403:
  194. return ast_http_error((*status = 403),
  195. (*title = ast_strdup("Access Denied")),
  196. NULL, "You do not have permission to access the requested URL.");
  197. }
  198. static struct ast_str *httpstatus_callback(struct ast_tcptls_session_instance *ser, const char *uri, struct ast_variable *vars, int *status, char **title, int *contentlength)
  199. {
  200. struct ast_str *out = ast_str_create(512);
  201. struct ast_variable *v;
  202. if (out == NULL)
  203. return out;
  204. ast_str_append(&out, 0,
  205. "\r\n"
  206. "<title>Asterisk HTTP Status</title>\r\n"
  207. "<body bgcolor=\"#ffffff\">\r\n"
  208. "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
  209. "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
  210. ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
  211. ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
  212. ast_inet_ntoa(http_desc.oldsin.sin_addr));
  213. ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%d</b></td></tr>\r\n",
  214. ntohs(http_desc.oldsin.sin_port));
  215. if (http_tls_cfg.enabled)
  216. ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%d</b></td></tr>\r\n",
  217. ntohs(https_desc.oldsin.sin_port));
  218. ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  219. for (v = vars; v; v = v->next) {
  220. if (strncasecmp(v->name, "cookie_", 7))
  221. ast_str_append(&out, 0, "<tr><td><i>Submitted Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
  222. }
  223. ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  224. for (v = vars; v; v = v->next) {
  225. if (!strncasecmp(v->name, "cookie_", 7))
  226. ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
  227. }
  228. ast_str_append(&out, 0, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body>\r\n");
  229. return out;
  230. }
  231. static struct ast_http_uri statusuri = {
  232. .callback = httpstatus_callback,
  233. .description = "Asterisk HTTP General Status",
  234. .uri = "httpstatus",
  235. .has_subtree = 0,
  236. };
  237. static struct ast_http_uri staticuri = {
  238. .callback = static_callback,
  239. .description = "Asterisk HTTP Static Delivery",
  240. .uri = "static",
  241. .has_subtree = 1,
  242. .static_content = 1,
  243. };
  244. struct ast_str *ast_http_error(int status, const char *title, const char *extra_header, const char *text)
  245. {
  246. struct ast_str *out = ast_str_create(512);
  247. if (out == NULL)
  248. return out;
  249. ast_str_set(&out, 0,
  250. "Content-type: text/html\r\n"
  251. "%s"
  252. "\r\n"
  253. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
  254. "<html><head>\r\n"
  255. "<title>%d %s</title>\r\n"
  256. "</head><body>\r\n"
  257. "<h1>%s</h1>\r\n"
  258. "<p>%s</p>\r\n"
  259. "<hr />\r\n"
  260. "<address>Asterisk Server</address>\r\n"
  261. "</body></html>\r\n",
  262. (extra_header ? extra_header : ""), status, title, title, text);
  263. return out;
  264. }
  265. /*! \brief
  266. * Link the new uri into the list.
  267. *
  268. * They are sorted by length of
  269. * the string, not alphabetically. Duplicate entries are not replaced,
  270. * but the insertion order (using <= and not just <) makes sure that
  271. * more recent insertions hide older ones.
  272. * On a lookup, we just scan the list and stop at the first matching entry.
  273. */
  274. int ast_http_uri_link(struct ast_http_uri *urih)
  275. {
  276. struct ast_http_uri *uri;
  277. int len = strlen(urih->uri);
  278. AST_RWLIST_WRLOCK(&uris);
  279. if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
  280. AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
  281. AST_RWLIST_UNLOCK(&uris);
  282. return 0;
  283. }
  284. AST_RWLIST_TRAVERSE(&uris, uri, entry) {
  285. if ( AST_RWLIST_NEXT(uri, entry)
  286. && strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len ) {
  287. AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
  288. AST_RWLIST_UNLOCK(&uris);
  289. return 0;
  290. }
  291. }
  292. AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
  293. AST_RWLIST_UNLOCK(&uris);
  294. return 0;
  295. }
  296. void ast_http_uri_unlink(struct ast_http_uri *urih)
  297. {
  298. AST_RWLIST_WRLOCK(&uris);
  299. AST_RWLIST_REMOVE(&uris, urih, entry);
  300. AST_RWLIST_UNLOCK(&uris);
  301. }
  302. #ifdef ENABLE_UPLOADS
  303. /*! \note This assumes that the post_mappings list is locked */
  304. static struct ast_http_post_mapping *find_post_mapping(const char *uri)
  305. {
  306. struct ast_http_post_mapping *post_map;
  307. if (!ast_strlen_zero(prefix) && strncmp(prefix, uri, strlen(prefix))) {
  308. ast_debug(1, "URI %s does not have prefix %s\n", uri, prefix);
  309. return NULL;
  310. }
  311. uri += strlen(prefix);
  312. if (*uri == '/')
  313. uri++;
  314. AST_RWLIST_TRAVERSE(&post_mappings, post_map, entry) {
  315. if (!strcmp(uri, post_map->from))
  316. return post_map;
  317. }
  318. return NULL;
  319. }
  320. static void post_raw(GMimePart *part, const char *post_dir, const char *fn)
  321. {
  322. char filename[PATH_MAX];
  323. GMimeDataWrapper *content;
  324. GMimeStream *stream;
  325. int fd;
  326. snprintf(filename, sizeof(filename), "%s/%s", post_dir, fn);
  327. ast_debug(1, "Posting raw data to %s\n", filename);
  328. if ((fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666)) == -1) {
  329. ast_log(LOG_WARNING, "Unable to open %s for writing file from a POST!\n", filename);
  330. return;
  331. }
  332. stream = g_mime_stream_fs_new(fd);
  333. content = g_mime_part_get_content_object(part);
  334. g_mime_data_wrapper_write_to_stream(content, stream);
  335. g_mime_stream_flush(stream);
  336. g_object_unref(content);
  337. g_object_unref(stream);
  338. }
  339. static GMimeMessage *parse_message(FILE *f)
  340. {
  341. GMimeMessage *message;
  342. GMimeParser *parser;
  343. GMimeStream *stream;
  344. stream = g_mime_stream_file_new(f);
  345. parser = g_mime_parser_new_with_stream(stream);
  346. g_mime_parser_set_respect_content_length(parser, 1);
  347. g_object_unref(stream);
  348. message = g_mime_parser_construct_message(parser);
  349. g_object_unref(parser);
  350. return message;
  351. }
  352. static void process_message_callback(GMimeObject *part, gpointer user_data)
  353. {
  354. struct mime_cbinfo *cbinfo = user_data;
  355. cbinfo->count++;
  356. /* We strip off the headers before we get here, so should only see GMIME_IS_PART */
  357. if (GMIME_IS_MESSAGE_PART(part)) {
  358. ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MESSAGE_PART\n");
  359. return;
  360. } else if (GMIME_IS_MESSAGE_PARTIAL(part)) {
  361. ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MESSAGE_PARTIAL\n");
  362. return;
  363. } else if (GMIME_IS_MULTIPART(part)) {
  364. GList *l;
  365. ast_log(LOG_WARNING, "Got unexpected GMIME_IS_MULTIPART, trying to process subparts\n");
  366. l = GMIME_MULTIPART (part)->subparts;
  367. while (l) {
  368. process_message_callback(l->data, cbinfo);
  369. l = l->next;
  370. }
  371. } else if (GMIME_IS_PART(part)) {
  372. const char *filename;
  373. ast_debug(3, "Got mime part\n");
  374. if (ast_strlen_zero(filename = g_mime_part_get_filename(GMIME_PART(part)))) {
  375. ast_debug(1, "Skipping part with no filename\n");
  376. return;
  377. }
  378. post_raw(GMIME_PART(part), cbinfo->post_dir, filename);
  379. } else {
  380. ast_log(LOG_ERROR, "Encountered unknown MIME part. This should never happen!\n");
  381. }
  382. }
  383. static int process_message(GMimeMessage *message, const char *post_dir)
  384. {
  385. struct mime_cbinfo cbinfo = {
  386. .count = 0,
  387. .post_dir = post_dir,
  388. };
  389. g_mime_message_foreach_part(message, process_message_callback, &cbinfo);
  390. return cbinfo.count;
  391. }
  392. static struct ast_str *handle_post(struct ast_tcptls_session_instance *ser, char *uri,
  393. int *status, char **title, int *contentlength, struct ast_variable *headers,
  394. struct ast_variable *cookies)
  395. {
  396. char buf[4096];
  397. FILE *f;
  398. size_t res;
  399. struct ast_variable *var;
  400. int content_len = 0;
  401. struct ast_http_post_mapping *post_map;
  402. const char *post_dir;
  403. unsigned long ident = 0;
  404. GMimeMessage *message;
  405. int message_count = 0;
  406. for (var = cookies; var; var = var->next) {
  407. if (strcasecmp(var->name, "mansession_id"))
  408. continue;
  409. if (sscanf(var->value, "%30lx", &ident) != 1) {
  410. *status = 400;
  411. *title = ast_strdup("Bad Request");
  412. return ast_http_error(400, "Bad Request", NULL, "The was an error parsing the request.");
  413. }
  414. if (!astman_verify_session_writepermissions(ident, EVENT_FLAG_CONFIG)) {
  415. *status = 401;
  416. *title = ast_strdup("Unauthorized");
  417. return ast_http_error(401, "Unauthorized", NULL, "You are not authorized to make this request.");
  418. }
  419. break;
  420. }
  421. if (!var) {
  422. *status = 401;
  423. *title = ast_strdup("Unauthorized");
  424. return ast_http_error(401, "Unauthorized", NULL, "You are not authorized to make this request.");
  425. }
  426. if (!(f = tmpfile()))
  427. return NULL;
  428. for (var = headers; var; var = var->next) {
  429. if (!strcasecmp(var->name, "Content-Length")) {
  430. if ((sscanf(var->value, "%30u", &content_len)) != 1) {
  431. ast_log(LOG_ERROR, "Invalid Content-Length in POST request!\n");
  432. fclose(f);
  433. return NULL;
  434. }
  435. ast_debug(1, "Got a Content-Length of %d\n", content_len);
  436. } else if (!strcasecmp(var->name, "Content-Type"))
  437. fprintf(f, "Content-Type: %s\r\n\r\n", var->value);
  438. }
  439. for(res = sizeof(buf);content_len;content_len -= res) {
  440. if (content_len < res)
  441. res = content_len;
  442. if (fread(buf, 1, res, ser->f) != res) {
  443. ast_log(LOG_WARNING, "fread() failed: %s\n", strerror(errno));
  444. }
  445. if (fwrite(buf, 1, res, f) != res) {
  446. ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
  447. }
  448. }
  449. if (fseek(f, SEEK_SET, 0)) {
  450. ast_debug(1, "Failed to seek temp file back to beginning.\n");
  451. fclose(f);
  452. return NULL;
  453. }
  454. AST_RWLIST_RDLOCK(&post_mappings);
  455. if (!(post_map = find_post_mapping(uri))) {
  456. ast_debug(1, "%s is not a valid URI for POST\n", uri);
  457. AST_RWLIST_UNLOCK(&post_mappings);
  458. *status = 404;
  459. *title = ast_strdup("Not Found");
  460. return ast_http_error(404, "Not Found", NULL, "The requested URL was not found on this server.");
  461. }
  462. post_dir = ast_strdupa(post_map->to);
  463. post_map = NULL;
  464. AST_RWLIST_UNLOCK(&post_mappings);
  465. ast_debug(1, "Going to post files to dir %s\n", post_dir);
  466. message = parse_message(f); /* Takes ownership and will close f */
  467. if (!message) {
  468. ast_log(LOG_ERROR, "Error parsing MIME data\n");
  469. *status = 400;
  470. *title = ast_strdup("Bad Request");
  471. return ast_http_error(400, "Bad Request", NULL, "The was an error parsing the request.");
  472. }
  473. if (!(message_count = process_message(message, post_dir))) {
  474. ast_log(LOG_ERROR, "Invalid MIME data, found no parts!\n");
  475. *status = 400;
  476. *title = ast_strdup("Bad Request");
  477. return ast_http_error(400, "Bad Request", NULL, "The was an error parsing the request.");
  478. }
  479. *status = 200;
  480. *title = ast_strdup("OK");
  481. return ast_http_error(200, "OK", NULL, "File successfully uploaded.");
  482. }
  483. #endif /* ENABLE_UPLOADS */
  484. /*
  485. * Decode special characters in http uri.
  486. * We have ast_uri_decode to handle %XX sequences, but spaces
  487. * are encoded as a '+' so we need to replace them beforehand.
  488. */
  489. static void http_decode(char *s)
  490. {
  491. char *t;
  492. for (t = s; *t; t++) {
  493. if (*t == '+')
  494. *t = ' ';
  495. }
  496. ast_uri_decode(s);
  497. }
  498. static struct ast_str *handle_uri(struct ast_tcptls_session_instance *ser, char *uri, int *status,
  499. char **title, int *contentlength, struct ast_variable **cookies,
  500. unsigned int *static_content)
  501. {
  502. char *c;
  503. struct ast_str *out = NULL;
  504. char *params = uri;
  505. struct ast_http_uri *urih=NULL;
  506. int l;
  507. struct ast_variable *vars=NULL, *v, *prev = NULL;
  508. struct http_uri_redirect *redirect;
  509. strsep(&params, "?");
  510. /* Extract arguments from the request and store them in variables. */
  511. if (params) {
  512. char *var, *val;
  513. while ((val = strsep(&params, "&"))) {
  514. var = strsep(&val, "=");
  515. if (val)
  516. http_decode(val);
  517. else
  518. val = "";
  519. http_decode(var);
  520. if ((v = ast_variable_new(var, val, ""))) {
  521. if (vars)
  522. prev->next = v;
  523. else
  524. vars = v;
  525. prev = v;
  526. }
  527. }
  528. }
  529. /*
  530. * Append the cookies to the variables (the only reason to have them
  531. * at the end is to avoid another pass of the cookies list to find
  532. * the tail).
  533. */
  534. if (prev)
  535. prev->next = *cookies;
  536. else
  537. vars = *cookies;
  538. *cookies = NULL;
  539. http_decode(uri);
  540. AST_RWLIST_RDLOCK(&uri_redirects);
  541. AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
  542. if (!strcasecmp(uri, redirect->target)) {
  543. char buf[512];
  544. snprintf(buf, sizeof(buf), "Location: %s\r\n", redirect->dest);
  545. out = ast_http_error((*status = 302),
  546. (*title = ast_strdup("Moved Temporarily")),
  547. buf, "Redirecting...");
  548. break;
  549. }
  550. }
  551. AST_RWLIST_UNLOCK(&uri_redirects);
  552. if (redirect)
  553. goto cleanup;
  554. /* We want requests to start with the (optional) prefix and '/' */
  555. l = strlen(prefix);
  556. if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
  557. uri += l + 1;
  558. /* scan registered uris to see if we match one. */
  559. AST_RWLIST_RDLOCK(&uris);
  560. AST_RWLIST_TRAVERSE(&uris, urih, entry) {
  561. l = strlen(urih->uri);
  562. c = uri + l; /* candidate */
  563. if (strncasecmp(urih->uri, uri, l) /* no match */
  564. || (*c && *c != '/')) /* substring */
  565. continue;
  566. if (*c == '/')
  567. c++;
  568. if (!*c || urih->has_subtree) {
  569. uri = c;
  570. break;
  571. }
  572. }
  573. if (!urih)
  574. AST_RWLIST_UNLOCK(&uris);
  575. }
  576. if (urih) {
  577. if (urih->static_content)
  578. *static_content = 1;
  579. out = urih->callback(ser, uri, vars, status, title, contentlength);
  580. AST_RWLIST_UNLOCK(&uris);
  581. } else {
  582. out = ast_http_error(404, "Not Found", NULL,
  583. "The requested URL was not found on this server.");
  584. *status = 404;
  585. *title = ast_strdup("Not Found");
  586. }
  587. cleanup:
  588. ast_variables_destroy(vars);
  589. return out;
  590. }
  591. #ifdef DO_SSL
  592. #if defined(HAVE_FUNOPEN)
  593. #define HOOK_T int
  594. #define LEN_T int
  595. #else
  596. #define HOOK_T ssize_t
  597. #define LEN_T size_t
  598. #endif
  599. /*!
  600. * replacement read/write functions for SSL support.
  601. * We use wrappers rather than SSL_read/SSL_write directly so
  602. * we can put in some debugging.
  603. */
  604. /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
  605. {
  606. int i = SSL_read(cookie, buf, len-1);
  607. #if 0
  608. if (i >= 0)
  609. buf[i] = '\0';
  610. ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
  611. #endif
  612. return i;
  613. }
  614. static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
  615. {
  616. #if 0
  617. char *s = alloca(len+1);
  618. strncpy(s, buf, len);
  619. s[len] = '\0';
  620. ast_verbose("ssl write size %d <%s>\n", (int)len, s);
  621. #endif
  622. return SSL_write(cookie, buf, len);
  623. }
  624. static int ssl_close(void *cookie)
  625. {
  626. close(SSL_get_fd(cookie));
  627. SSL_shutdown(cookie);
  628. SSL_free(cookie);
  629. return 0;
  630. }*/
  631. #endif /* DO_SSL */
  632. static struct ast_variable *parse_cookies(char *cookies)
  633. {
  634. char *cur;
  635. struct ast_variable *vars = NULL, *var;
  636. /* Skip Cookie: */
  637. cookies += 8;
  638. while ((cur = strsep(&cookies, ";"))) {
  639. char *name, *val;
  640. name = val = cur;
  641. strsep(&val, "=");
  642. if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
  643. continue;
  644. }
  645. name = ast_strip(name);
  646. val = ast_strip_quoted(val, "\"", "\"");
  647. if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
  648. continue;
  649. }
  650. if (option_debug) {
  651. ast_log(LOG_DEBUG, "mmm ... cookie! Name: '%s' Value: '%s'\n", name, val);
  652. }
  653. var = ast_variable_new(name, val, __FILE__);
  654. var->next = vars;
  655. vars = var;
  656. }
  657. return vars;
  658. }
  659. static void *httpd_helper_thread(void *data)
  660. {
  661. char buf[4096];
  662. char cookie[4096];
  663. struct ast_tcptls_session_instance *ser = data;
  664. struct ast_variable *vars=NULL, *headers = NULL;
  665. char *uri, *title=NULL;
  666. int status = 200, contentlength = 0;
  667. struct ast_str *out = NULL;
  668. unsigned int static_content = 0;
  669. if (!fgets(buf, sizeof(buf), ser->f))
  670. goto done;
  671. uri = ast_skip_nonblanks(buf); /* Skip method */
  672. if (*uri)
  673. *uri++ = '\0';
  674. uri = ast_skip_blanks(uri); /* Skip white space */
  675. if (*uri) { /* terminate at the first blank */
  676. char *c = ast_skip_nonblanks(uri);
  677. if (*c)
  678. *c = '\0';
  679. }
  680. /* process "Cookie: " lines */
  681. while (fgets(cookie, sizeof(cookie), ser->f)) {
  682. /* Trim trailing characters */
  683. ast_trim_blanks(cookie);
  684. if (ast_strlen_zero(cookie))
  685. break;
  686. if (strncasecmp(cookie, "Cookie: ", 8)) {
  687. char *name, *value;
  688. struct ast_variable *var;
  689. value = ast_strdupa(cookie);
  690. name = strsep(&value, ":");
  691. if (!value)
  692. continue;
  693. value = ast_skip_blanks(value);
  694. if (ast_strlen_zero(value))
  695. continue;
  696. var = ast_variable_new(name, value, "");
  697. if (!var)
  698. continue;
  699. var->next = headers;
  700. headers = var;
  701. continue;
  702. }
  703. if (vars) {
  704. ast_variables_destroy(vars);
  705. }
  706. vars = parse_cookies(cookie);
  707. }
  708. if (!*uri) {
  709. out = ast_http_error(400, "Bad Request", NULL, "Invalid Request");
  710. } else if (!strcasecmp(buf, "post")) {
  711. #ifdef ENABLE_UPLOADS
  712. out = handle_post(ser, uri, &status, &title, &contentlength, headers, vars);
  713. #else
  714. out = ast_http_error(501, "Not Implemented", NULL,
  715. "Attempt to use unimplemented / unsupported method");
  716. #endif /* ENABLE_UPLOADS */
  717. } else if (strcasecmp(buf, "get")) {
  718. out = ast_http_error(501, "Not Implemented", NULL,
  719. "Attempt to use unimplemented / unsupported method");
  720. } else { /* try to serve it */
  721. out = handle_uri(ser, uri, &status, &title, &contentlength, &vars, &static_content);
  722. }
  723. /* If they aren't mopped up already, clean up the cookies */
  724. if (vars)
  725. ast_variables_destroy(vars);
  726. /* Clean up all the header information pulled as well */
  727. if (headers)
  728. ast_variables_destroy(headers);
  729. if (out) {
  730. struct timeval tv = ast_tvnow();
  731. char timebuf[256];
  732. struct ast_tm tm;
  733. ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S %Z", ast_localtime(&tv, &tm, "GMT"));
  734. fprintf(ser->f, "HTTP/1.1 %d %s\r\n"
  735. "Server: Asterisk/%s\r\n"
  736. "Date: %s\r\n"
  737. "Connection: close\r\n"
  738. "%s",
  739. status, title ? title : "OK", ast_get_version(), timebuf,
  740. static_content ? "" : "Cache-Control: no-cache, no-store\r\n");
  741. /* We set the no-cache headers only for dynamic content.
  742. * If you want to make sure the static file you requested is not from cache,
  743. * append a random variable to your GET request. Ex: 'something.html?r=109987734'
  744. */
  745. if (!contentlength) { /* opaque body ? just dump it hoping it is properly formatted */
  746. fprintf(ser->f, "%s", out->str);
  747. } else {
  748. char *tmp = strstr(out->str, "\r\n\r\n");
  749. if (tmp) {
  750. fprintf(ser->f, "Content-length: %d\r\n", contentlength);
  751. /* first write the header, then the body */
  752. if (fwrite(out->str, 1, (tmp + 4 - out->str), ser->f) != tmp + 4 - out->str) {
  753. ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
  754. }
  755. if (fwrite(tmp + 4, 1, contentlength, ser->f) != contentlength ) {
  756. ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
  757. }
  758. }
  759. }
  760. ast_free(out);
  761. }
  762. if (title)
  763. ast_free(title);
  764. done:
  765. fclose(ser->f);
  766. ao2_ref(ser, -1);
  767. ser = NULL;
  768. return NULL;
  769. }
  770. /*!
  771. * \brief Add a new URI redirect
  772. * The entries in the redirect list are sorted by length, just like the list
  773. * of URI handlers.
  774. */
  775. static void add_redirect(const char *value)
  776. {
  777. char *target, *dest;
  778. struct http_uri_redirect *redirect, *cur;
  779. unsigned int target_len;
  780. unsigned int total_len;
  781. dest = ast_strdupa(value);
  782. dest = ast_skip_blanks(dest);
  783. target = strsep(&dest, " ");
  784. target = ast_skip_blanks(target);
  785. target = strsep(&target, " "); /* trim trailing whitespace */
  786. if (!dest) {
  787. ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
  788. return;
  789. }
  790. target_len = strlen(target) + 1;
  791. total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
  792. if (!(redirect = ast_calloc(1, total_len)))
  793. return;
  794. redirect->dest = redirect->target + target_len;
  795. strcpy(redirect->target, target);
  796. strcpy(redirect->dest, dest);
  797. AST_RWLIST_WRLOCK(&uri_redirects);
  798. target_len--; /* So we can compare directly with strlen() */
  799. if ( AST_RWLIST_EMPTY(&uri_redirects)
  800. || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
  801. AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
  802. AST_RWLIST_UNLOCK(&uri_redirects);
  803. return;
  804. }
  805. AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
  806. if ( AST_RWLIST_NEXT(cur, entry)
  807. && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
  808. AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
  809. AST_RWLIST_UNLOCK(&uri_redirects);
  810. return;
  811. }
  812. }
  813. AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
  814. AST_RWLIST_UNLOCK(&uri_redirects);
  815. }
  816. #ifdef ENABLE_UPLOADS
  817. static void destroy_post_mapping(struct ast_http_post_mapping *post_map)
  818. {
  819. if (post_map->from)
  820. ast_free(post_map->from);
  821. if (post_map->to)
  822. ast_free(post_map->to);
  823. ast_free(post_map);
  824. }
  825. static void destroy_post_mappings(void)
  826. {
  827. struct ast_http_post_mapping *post_map;
  828. AST_RWLIST_WRLOCK(&post_mappings);
  829. while ((post_map = AST_RWLIST_REMOVE_HEAD(&post_mappings, entry)))
  830. destroy_post_mapping(post_map);
  831. AST_RWLIST_UNLOCK(&post_mappings);
  832. }
  833. static void add_post_mapping(const char *from, const char *to)
  834. {
  835. struct ast_http_post_mapping *post_map;
  836. if (!(post_map = ast_calloc(1, sizeof(*post_map))))
  837. return;
  838. if (!(post_map->from = ast_strdup(from))) {
  839. destroy_post_mapping(post_map);
  840. return;
  841. }
  842. if (!(post_map->to = ast_strdup(to))) {
  843. destroy_post_mapping(post_map);
  844. return;
  845. }
  846. AST_RWLIST_WRLOCK(&post_mappings);
  847. AST_RWLIST_INSERT_TAIL(&post_mappings, post_map, entry);
  848. AST_RWLIST_UNLOCK(&post_mappings);
  849. }
  850. #endif /* ENABLE_UPLOADS */
  851. static int __ast_http_load(int reload)
  852. {
  853. struct ast_config *cfg;
  854. struct ast_variable *v;
  855. int enabled=0;
  856. int newenablestatic=0;
  857. struct hostent *hp;
  858. struct ast_hostent ahp;
  859. char newprefix[MAX_PREFIX] = "";
  860. int have_sslbindaddr = 0;
  861. struct http_uri_redirect *redirect;
  862. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  863. if ((cfg = ast_config_load("http.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
  864. return 0;
  865. /* default values */
  866. memset(&http_desc.sin, 0, sizeof(http_desc.sin));
  867. http_desc.sin.sin_port = htons(8088);
  868. memset(&https_desc.sin, 0, sizeof(https_desc.sin));
  869. https_desc.sin.sin_port = htons(8089);
  870. http_tls_cfg.enabled = 0;
  871. if (http_tls_cfg.certfile)
  872. ast_free(http_tls_cfg.certfile);
  873. http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
  874. if (http_tls_cfg.cipher)
  875. ast_free(http_tls_cfg.cipher);
  876. http_tls_cfg.cipher = ast_strdup("");
  877. AST_RWLIST_WRLOCK(&uri_redirects);
  878. while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry)))
  879. ast_free(redirect);
  880. AST_RWLIST_UNLOCK(&uri_redirects);
  881. #ifdef ENABLE_UPLOADS
  882. destroy_post_mappings();
  883. #endif /* ENABLE_UPLOADS */
  884. if (cfg) {
  885. v = ast_variable_browse(cfg, "general");
  886. for (; v; v = v->next) {
  887. if (!strcasecmp(v->name, "enabled"))
  888. enabled = ast_true(v->value);
  889. else if (!strcasecmp(v->name, "sslenable"))
  890. http_tls_cfg.enabled = ast_true(v->value);
  891. else if (!strcasecmp(v->name, "sslbindport"))
  892. https_desc.sin.sin_port = htons(atoi(v->value));
  893. else if (!strcasecmp(v->name, "sslcert")) {
  894. ast_free(http_tls_cfg.certfile);
  895. http_tls_cfg.certfile = ast_strdup(v->value);
  896. } else if (!strcasecmp(v->name, "sslcipher")) {
  897. ast_free(http_tls_cfg.cipher);
  898. http_tls_cfg.cipher = ast_strdup(v->value);
  899. }
  900. else if (!strcasecmp(v->name, "enablestatic"))
  901. newenablestatic = ast_true(v->value);
  902. else if (!strcasecmp(v->name, "bindport"))
  903. http_desc.sin.sin_port = htons(atoi(v->value));
  904. else if (!strcasecmp(v->name, "sslbindaddr")) {
  905. if ((hp = ast_gethostbyname(v->value, &ahp))) {
  906. memcpy(&https_desc.sin.sin_addr, hp->h_addr, sizeof(https_desc.sin.sin_addr));
  907. have_sslbindaddr = 1;
  908. } else {
  909. ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
  910. }
  911. } else if (!strcasecmp(v->name, "bindaddr")) {
  912. if ((hp = ast_gethostbyname(v->value, &ahp))) {
  913. memcpy(&http_desc.sin.sin_addr, hp->h_addr, sizeof(http_desc.sin.sin_addr));
  914. } else {
  915. ast_log(LOG_WARNING, "Invalid bind address '%s'\n", v->value);
  916. }
  917. } else if (!strcasecmp(v->name, "prefix")) {
  918. if (!ast_strlen_zero(v->value)) {
  919. newprefix[0] = '/';
  920. ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
  921. } else {
  922. newprefix[0] = '\0';
  923. }
  924. } else if (!strcasecmp(v->name, "redirect")) {
  925. add_redirect(v->value);
  926. } else {
  927. ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
  928. }
  929. }
  930. #ifdef ENABLE_UPLOADS
  931. for (v = ast_variable_browse(cfg, "post_mappings"); v; v = v->next)
  932. add_post_mapping(v->name, v->value);
  933. #endif /* ENABLE_UPLOADS */
  934. ast_config_destroy(cfg);
  935. }
  936. if (!have_sslbindaddr)
  937. https_desc.sin.sin_addr = http_desc.sin.sin_addr;
  938. if (enabled)
  939. http_desc.sin.sin_family = https_desc.sin.sin_family = AF_INET;
  940. if (strcmp(prefix, newprefix))
  941. ast_copy_string(prefix, newprefix, sizeof(prefix));
  942. enablestatic = newenablestatic;
  943. ast_tcptls_server_start(&http_desc);
  944. if (ast_ssl_setup(https_desc.tls_cfg))
  945. ast_tcptls_server_start(&https_desc);
  946. return 0;
  947. }
  948. static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  949. {
  950. struct ast_http_uri *urih;
  951. struct http_uri_redirect *redirect;
  952. #ifdef ENABLE_UPLOADS
  953. struct ast_http_post_mapping *post_map;
  954. #endif /* ENABLE_UPLOADS */
  955. switch (cmd) {
  956. case CLI_INIT:
  957. e->command = "http show status";
  958. e->usage =
  959. "Usage: http show status\n"
  960. " Lists status of internal HTTP engine\n";
  961. return NULL;
  962. case CLI_GENERATE:
  963. return NULL;
  964. }
  965. if (a->argc != 3)
  966. return CLI_SHOWUSAGE;
  967. ast_cli(a->fd, "HTTP Server Status:\n");
  968. ast_cli(a->fd, "Prefix: %s\n", prefix);
  969. if (!http_desc.oldsin.sin_family)
  970. ast_cli(a->fd, "Server Disabled\n\n");
  971. else {
  972. ast_cli(a->fd, "Server Enabled and Bound to %s:%d\n\n",
  973. ast_inet_ntoa(http_desc.oldsin.sin_addr),
  974. ntohs(http_desc.oldsin.sin_port));
  975. if (http_tls_cfg.enabled)
  976. ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s:%d\n\n",
  977. ast_inet_ntoa(https_desc.oldsin.sin_addr),
  978. ntohs(https_desc.oldsin.sin_port));
  979. }
  980. ast_cli(a->fd, "Enabled URI's:\n");
  981. AST_RWLIST_RDLOCK(&uris);
  982. if (AST_RWLIST_EMPTY(&uris)) {
  983. ast_cli(a->fd, "None.\n");
  984. } else {
  985. AST_RWLIST_TRAVERSE(&uris, urih, entry)
  986. ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
  987. }
  988. AST_RWLIST_UNLOCK(&uris);
  989. ast_cli(a->fd, "\nEnabled Redirects:\n");
  990. AST_RWLIST_RDLOCK(&uri_redirects);
  991. AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
  992. ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
  993. if (AST_RWLIST_EMPTY(&uri_redirects))
  994. ast_cli(a->fd, " None.\n");
  995. AST_RWLIST_UNLOCK(&uri_redirects);
  996. #ifdef ENABLE_UPLOADS
  997. ast_cli(a->fd, "\nPOST mappings:\n");
  998. AST_RWLIST_RDLOCK(&post_mappings);
  999. AST_LIST_TRAVERSE(&post_mappings, post_map, entry) {
  1000. ast_cli(a->fd, "%s/%s => %s\n", prefix, post_map->from, post_map->to);
  1001. }
  1002. ast_cli(a->fd, "%s\n", AST_LIST_EMPTY(&post_mappings) ? "None.\n" : "");
  1003. AST_RWLIST_UNLOCK(&post_mappings);
  1004. #endif /* ENABLE_UPLOADS */
  1005. return CLI_SUCCESS;
  1006. }
  1007. int ast_http_reload(void)
  1008. {
  1009. return __ast_http_load(1);
  1010. }
  1011. static struct ast_cli_entry cli_http[] = {
  1012. AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
  1013. };
  1014. int ast_http_init(void)
  1015. {
  1016. #ifdef ENABLE_UPLOADS
  1017. g_mime_init(0);
  1018. #endif /* ENABLE_UPLOADS */
  1019. ast_http_uri_link(&statusuri);
  1020. ast_http_uri_link(&staticuri);
  1021. ast_cli_register_multiple(cli_http, sizeof(cli_http) / sizeof(struct ast_cli_entry));
  1022. return __ast_http_load(0);
  1023. }