http.c 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  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. * GMime http://spruce.sourceforge.net/gmime/
  28. *
  29. * \ref AstHTTP - AMI over the http protocol
  30. */
  31. /*! \li \ref http.c uses the configuration file \ref http.conf
  32. * \addtogroup configuration_file
  33. */
  34. /*! \page http.conf http.conf
  35. * \verbinclude http.conf.sample
  36. */
  37. /*** MODULEINFO
  38. <support_level>core</support_level>
  39. ***/
  40. #include "asterisk.h"
  41. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  42. #include <time.h>
  43. #include <sys/time.h>
  44. #include <sys/stat.h>
  45. #include <sys/signal.h>
  46. #include <fcntl.h>
  47. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  48. #include "asterisk/cli.h"
  49. #include "asterisk/tcptls.h"
  50. #include "asterisk/http.h"
  51. #include "asterisk/utils.h"
  52. #include "asterisk/strings.h"
  53. #include "asterisk/config.h"
  54. #include "asterisk/stringfields.h"
  55. #include "asterisk/ast_version.h"
  56. #include "asterisk/manager.h"
  57. #include "asterisk/_private.h"
  58. #include "asterisk/astobj2.h"
  59. #include "asterisk/netsock2.h"
  60. #include "asterisk/json.h"
  61. #define MAX_PREFIX 80
  62. #define DEFAULT_PORT 8088
  63. #define DEFAULT_TLS_PORT 8089
  64. #define DEFAULT_SESSION_LIMIT 100
  65. /*! (ms) Idle time waiting for data. */
  66. #define DEFAULT_SESSION_INACTIVITY 30000
  67. /*! (ms) Min timeout for initial HTTP request to start coming in. */
  68. #define MIN_INITIAL_REQUEST_TIMEOUT 10000
  69. /*! (ms) Idle time between HTTP requests */
  70. #define DEFAULT_SESSION_KEEP_ALIVE 0
  71. /*! Maximum application/json or application/x-www-form-urlencoded body content length. */
  72. #if !defined(LOW_MEMORY)
  73. #define MAX_CONTENT_LENGTH 4096
  74. #else
  75. #define MAX_CONTENT_LENGTH 1024
  76. #endif /* !defined(LOW_MEMORY) */
  77. /*! Maximum line length for HTTP requests. */
  78. #if !defined(LOW_MEMORY)
  79. #define MAX_HTTP_LINE_LENGTH 4096
  80. #else
  81. #define MAX_HTTP_LINE_LENGTH 1024
  82. #endif /* !defined(LOW_MEMORY) */
  83. /* See http.h for more information about the SSL implementation */
  84. #if defined(HAVE_OPENSSL) && (defined(HAVE_FUNOPEN) || defined(HAVE_FOPENCOOKIE))
  85. #define DO_SSL /* comment in/out if you want to support ssl */
  86. #endif
  87. static int session_limit = DEFAULT_SESSION_LIMIT;
  88. static int session_inactivity = DEFAULT_SESSION_INACTIVITY;
  89. static int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
  90. static int session_count = 0;
  91. static struct ast_tls_config http_tls_cfg;
  92. static void *httpd_helper_thread(void *arg);
  93. /*!
  94. * we have up to two accepting threads, one for http, one for https
  95. */
  96. static struct ast_tcptls_session_args http_desc = {
  97. .accept_fd = -1,
  98. .master = AST_PTHREADT_NULL,
  99. .tls_cfg = NULL,
  100. .poll_timeout = -1,
  101. .name = "http server",
  102. .accept_fn = ast_tcptls_server_root,
  103. .worker_fn = httpd_helper_thread,
  104. };
  105. static struct ast_tcptls_session_args https_desc = {
  106. .accept_fd = -1,
  107. .master = AST_PTHREADT_NULL,
  108. .tls_cfg = &http_tls_cfg,
  109. .poll_timeout = -1,
  110. .name = "https server",
  111. .accept_fn = ast_tcptls_server_root,
  112. .worker_fn = httpd_helper_thread,
  113. };
  114. static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
  115. /* all valid URIs must be prepended by the string in prefix. */
  116. static char prefix[MAX_PREFIX];
  117. static int enablestatic;
  118. /*! \brief Limit the kinds of files we're willing to serve up */
  119. static struct {
  120. const char *ext;
  121. const char *mtype;
  122. } mimetypes[] = {
  123. { "png", "image/png" },
  124. { "xml", "text/xml" },
  125. { "jpg", "image/jpeg" },
  126. { "js", "application/x-javascript" },
  127. { "wav", "audio/x-wav" },
  128. { "mp3", "audio/mpeg" },
  129. { "svg", "image/svg+xml" },
  130. { "svgz", "image/svg+xml" },
  131. { "gif", "image/gif" },
  132. { "html", "text/html" },
  133. { "htm", "text/html" },
  134. { "css", "text/css" },
  135. { "cnf", "text/plain" },
  136. { "cfg", "text/plain" },
  137. { "bin", "application/octet-stream" },
  138. { "sbn", "application/octet-stream" },
  139. { "ld", "application/octet-stream" },
  140. };
  141. struct http_uri_redirect {
  142. AST_LIST_ENTRY(http_uri_redirect) entry;
  143. char *dest;
  144. char target[0];
  145. };
  146. static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
  147. static const struct ast_cfhttp_methods_text {
  148. enum ast_http_method method;
  149. const char *text;
  150. } ast_http_methods_text[] = {
  151. { AST_HTTP_UNKNOWN, "UNKNOWN" },
  152. { AST_HTTP_GET, "GET" },
  153. { AST_HTTP_POST, "POST" },
  154. { AST_HTTP_HEAD, "HEAD" },
  155. { AST_HTTP_PUT, "PUT" },
  156. { AST_HTTP_DELETE, "DELETE" },
  157. { AST_HTTP_OPTIONS, "OPTIONS" },
  158. };
  159. const char *ast_get_http_method(enum ast_http_method method)
  160. {
  161. int x;
  162. for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
  163. if (ast_http_methods_text[x].method == method) {
  164. return ast_http_methods_text[x].text;
  165. }
  166. }
  167. return NULL;
  168. }
  169. const char *ast_http_ftype2mtype(const char *ftype)
  170. {
  171. int x;
  172. if (ftype) {
  173. for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
  174. if (!strcasecmp(ftype, mimetypes[x].ext)) {
  175. return mimetypes[x].mtype;
  176. }
  177. }
  178. }
  179. return NULL;
  180. }
  181. uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
  182. {
  183. uint32_t mngid = 0;
  184. struct ast_variable *v, *cookies;
  185. cookies = ast_http_get_cookies(headers);
  186. for (v = cookies; v; v = v->next) {
  187. if (!strcasecmp(v->name, "mansession_id")) {
  188. sscanf(v->value, "%30x", &mngid);
  189. break;
  190. }
  191. }
  192. ast_variables_destroy(cookies);
  193. return mngid;
  194. }
  195. void ast_http_prefix(char *buf, int len)
  196. {
  197. if (buf) {
  198. ast_copy_string(buf, prefix, len);
  199. }
  200. }
  201. static int static_callback(struct ast_tcptls_session_instance *ser,
  202. const struct ast_http_uri *urih, const char *uri,
  203. enum ast_http_method method, struct ast_variable *get_vars,
  204. struct ast_variable *headers)
  205. {
  206. char *path;
  207. const char *ftype;
  208. const char *mtype;
  209. char wkspace[80];
  210. struct stat st;
  211. int len;
  212. int fd;
  213. struct ast_str *http_header;
  214. struct timeval tv;
  215. struct ast_tm tm;
  216. char timebuf[80], etag[23];
  217. struct ast_variable *v;
  218. int not_modified = 0;
  219. if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
  220. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  221. return 0;
  222. }
  223. /* Yuck. I'm not really sold on this, but if you don't deliver static content it makes your configuration
  224. substantially more challenging, but this seems like a rather irritating feature creep on Asterisk. */
  225. if (!enablestatic || ast_strlen_zero(uri)) {
  226. goto out403;
  227. }
  228. /* Disallow any funny filenames at all (checking first character only??) */
  229. if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
  230. goto out403;
  231. }
  232. if (strstr(uri, "/..")) {
  233. goto out403;
  234. }
  235. if ((ftype = strrchr(uri, '.'))) {
  236. ftype++;
  237. }
  238. if (!(mtype = ast_http_ftype2mtype(ftype))) {
  239. snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
  240. mtype = wkspace;
  241. }
  242. /* Cap maximum length */
  243. if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
  244. goto out403;
  245. }
  246. path = ast_alloca(len);
  247. sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
  248. if (stat(path, &st)) {
  249. goto out404;
  250. }
  251. if (S_ISDIR(st.st_mode)) {
  252. goto out404;
  253. }
  254. if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
  255. goto out403;
  256. }
  257. fd = open(path, O_RDONLY);
  258. if (fd < 0) {
  259. goto out403;
  260. }
  261. /* make "Etag:" http header value */
  262. snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
  263. /* make "Last-Modified:" http header value */
  264. tv.tv_sec = st.st_mtime;
  265. tv.tv_usec = 0;
  266. ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
  267. /* check received "If-None-Match" request header and Etag value for file */
  268. for (v = headers; v; v = v->next) {
  269. if (!strcasecmp(v->name, "If-None-Match")) {
  270. if (!strcasecmp(v->value, etag)) {
  271. not_modified = 1;
  272. }
  273. break;
  274. }
  275. }
  276. http_header = ast_str_create(255);
  277. if (!http_header) {
  278. ast_http_request_close_on_completion(ser);
  279. ast_http_error(ser, 500, "Server Error", "Out of memory");
  280. close(fd);
  281. return 0;
  282. }
  283. ast_str_set(&http_header, 0, "Content-type: %s\r\n"
  284. "ETag: %s\r\n"
  285. "Last-Modified: %s\r\n",
  286. mtype,
  287. etag,
  288. timebuf);
  289. /* ast_http_send() frees http_header, so we don't need to do it before returning */
  290. if (not_modified) {
  291. ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
  292. } else {
  293. ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
  294. }
  295. close(fd);
  296. return 0;
  297. out404:
  298. ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
  299. return 0;
  300. out403:
  301. ast_http_request_close_on_completion(ser);
  302. ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
  303. return 0;
  304. }
  305. static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
  306. const struct ast_http_uri *urih, const char *uri,
  307. enum ast_http_method method, struct ast_variable *get_vars,
  308. struct ast_variable *headers)
  309. {
  310. struct ast_str *out;
  311. struct ast_variable *v, *cookies = NULL;
  312. if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
  313. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  314. return 0;
  315. }
  316. out = ast_str_create(512);
  317. if (!out) {
  318. ast_http_request_close_on_completion(ser);
  319. ast_http_error(ser, 500, "Server Error", "Out of memory");
  320. return 0;
  321. }
  322. ast_str_append(&out, 0,
  323. "<title>Asterisk HTTP Status</title>\r\n"
  324. "<body bgcolor=\"#ffffff\">\r\n"
  325. "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
  326. "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
  327. ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
  328. ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
  329. ast_sockaddr_stringify_addr(&http_desc.old_address));
  330. ast_str_append(&out, 0, "<tr><td><i>Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
  331. ast_sockaddr_stringify_port(&http_desc.old_address));
  332. if (http_tls_cfg.enabled) {
  333. ast_str_append(&out, 0, "<tr><td><i>SSL Bind Port</i></td><td><b>%s</b></td></tr>\r\n",
  334. ast_sockaddr_stringify_port(&https_desc.old_address));
  335. }
  336. ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  337. for (v = get_vars; v; v = v->next) {
  338. ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
  339. }
  340. ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  341. cookies = ast_http_get_cookies(headers);
  342. for (v = cookies; v; v = v->next) {
  343. ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
  344. }
  345. ast_variables_destroy(cookies);
  346. 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");
  347. ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
  348. return 0;
  349. }
  350. static struct ast_http_uri statusuri = {
  351. .callback = httpstatus_callback,
  352. .description = "Asterisk HTTP General Status",
  353. .uri = "httpstatus",
  354. .has_subtree = 0,
  355. .data = NULL,
  356. .key = __FILE__,
  357. };
  358. static struct ast_http_uri staticuri = {
  359. .callback = static_callback,
  360. .description = "Asterisk HTTP Static Delivery",
  361. .uri = "static",
  362. .has_subtree = 1,
  363. .data = NULL,
  364. .key= __FILE__,
  365. };
  366. enum http_private_flags {
  367. /*! TRUE if the HTTP request has a body. */
  368. HTTP_FLAG_HAS_BODY = (1 << 0),
  369. /*! TRUE if the HTTP request body has been read. */
  370. HTTP_FLAG_BODY_READ = (1 << 1),
  371. /*! TRUE if the HTTP request must close when completed. */
  372. HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2),
  373. };
  374. /*! HTTP tcptls worker_fn private data. */
  375. struct http_worker_private_data {
  376. /*! Body length or -1 if chunked. Valid if HTTP_FLAG_HAS_BODY is TRUE. */
  377. int body_length;
  378. /*! HTTP body tracking flags */
  379. struct ast_flags flags;
  380. };
  381. void ast_http_send(struct ast_tcptls_session_instance *ser,
  382. enum ast_http_method method, int status_code, const char *status_title,
  383. struct ast_str *http_header, struct ast_str *out, int fd,
  384. unsigned int static_content)
  385. {
  386. struct timeval now = ast_tvnow();
  387. struct ast_tm tm;
  388. char timebuf[80];
  389. int content_length = 0;
  390. int close_connection;
  391. if (!ser || !ser->f) {
  392. /* The connection is not open. */
  393. ast_free(http_header);
  394. ast_free(out);
  395. return;
  396. }
  397. /*
  398. * We shouldn't be sending non-final status codes to this
  399. * function because we may close the connection before
  400. * returning.
  401. */
  402. ast_assert(200 <= status_code);
  403. if (session_keep_alive <= 0) {
  404. close_connection = 1;
  405. } else {
  406. struct http_worker_private_data *request;
  407. request = ser->private_data;
  408. if (!request
  409. || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)
  410. || ast_http_body_discard(ser)) {
  411. close_connection = 1;
  412. } else {
  413. close_connection = 0;
  414. }
  415. }
  416. ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
  417. /* calc content length */
  418. if (out) {
  419. content_length += ast_str_strlen(out);
  420. }
  421. if (fd) {
  422. content_length += lseek(fd, 0, SEEK_END);
  423. lseek(fd, 0, SEEK_SET);
  424. }
  425. /* send http header */
  426. fprintf(ser->f,
  427. "HTTP/1.1 %d %s\r\n"
  428. "Server: Asterisk/%s\r\n"
  429. "Date: %s\r\n"
  430. "%s"
  431. "%s"
  432. "%s"
  433. "Content-Length: %d\r\n"
  434. "\r\n",
  435. status_code, status_title ? status_title : "OK",
  436. ast_get_version(),
  437. timebuf,
  438. close_connection ? "Connection: close\r\n" : "",
  439. static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
  440. http_header ? ast_str_buffer(http_header) : "",
  441. content_length
  442. );
  443. /* send content */
  444. if (method != AST_HTTP_HEAD || status_code >= 400) {
  445. if (out && ast_str_strlen(out)) {
  446. if (fwrite(ast_str_buffer(out), ast_str_strlen(out), 1, ser->f) != 1) {
  447. ast_log(LOG_ERROR, "fwrite() failed: %s\n", strerror(errno));
  448. close_connection = 1;
  449. }
  450. }
  451. if (fd) {
  452. char buf[256];
  453. int len;
  454. while ((len = read(fd, buf, sizeof(buf))) > 0) {
  455. if (fwrite(buf, len, 1, ser->f) != 1) {
  456. ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
  457. close_connection = 1;
  458. break;
  459. }
  460. }
  461. }
  462. }
  463. ast_free(http_header);
  464. ast_free(out);
  465. if (close_connection) {
  466. ast_debug(1, "HTTP closing session. status_code:%d\n", status_code);
  467. ast_tcptls_close_session_file(ser);
  468. } else {
  469. ast_debug(1, "HTTP keeping session open. status_code:%d\n", status_code);
  470. }
  471. }
  472. void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
  473. const unsigned long nonce, const unsigned long opaque, int stale,
  474. const char *text)
  475. {
  476. struct ast_str *http_headers = ast_str_create(128);
  477. struct ast_str *out = ast_str_create(512);
  478. if (!http_headers || !out) {
  479. ast_free(http_headers);
  480. ast_free(out);
  481. if (ser && ser->f) {
  482. ast_debug(1, "HTTP closing session. Auth OOM\n");
  483. ast_tcptls_close_session_file(ser);
  484. }
  485. return;
  486. }
  487. ast_str_set(&http_headers, 0,
  488. "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
  489. "Content-type: text/html\r\n",
  490. realm ? realm : "Asterisk",
  491. nonce,
  492. opaque,
  493. stale ? ", stale=true" : "");
  494. ast_str_set(&out, 0,
  495. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
  496. "<html><head>\r\n"
  497. "<title>401 Unauthorized</title>\r\n"
  498. "</head><body>\r\n"
  499. "<h1>401 Unauthorized</h1>\r\n"
  500. "<p>%s</p>\r\n"
  501. "<hr />\r\n"
  502. "<address>Asterisk Server</address>\r\n"
  503. "</body></html>\r\n",
  504. text ? text : "");
  505. ast_http_send(ser, AST_HTTP_UNKNOWN, 401, "Unauthorized", http_headers, out, 0, 0);
  506. }
  507. void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code, const char *status_title, const char *text)
  508. {
  509. struct ast_str *http_headers = ast_str_create(40);
  510. struct ast_str *out = ast_str_create(256);
  511. if (!http_headers || !out) {
  512. ast_free(http_headers);
  513. ast_free(out);
  514. if (ser && ser->f) {
  515. ast_debug(1, "HTTP closing session. error OOM\n");
  516. ast_tcptls_close_session_file(ser);
  517. }
  518. return;
  519. }
  520. ast_str_set(&http_headers, 0, "Content-type: text/html\r\n");
  521. ast_str_set(&out, 0,
  522. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
  523. "<html><head>\r\n"
  524. "<title>%d %s</title>\r\n"
  525. "</head><body>\r\n"
  526. "<h1>%s</h1>\r\n"
  527. "<p>%s</p>\r\n"
  528. "<hr />\r\n"
  529. "<address>Asterisk Server</address>\r\n"
  530. "</body></html>\r\n",
  531. status_code, status_title, status_title, text);
  532. ast_http_send(ser, AST_HTTP_UNKNOWN, status_code, status_title, http_headers, out, 0, 0);
  533. }
  534. /*!
  535. * \brief Link the new uri into the list.
  536. *
  537. * They are sorted by length of
  538. * the string, not alphabetically. Duplicate entries are not replaced,
  539. * but the insertion order (using <= and not just <) makes sure that
  540. * more recent insertions hide older ones.
  541. * On a lookup, we just scan the list and stop at the first matching entry.
  542. */
  543. int ast_http_uri_link(struct ast_http_uri *urih)
  544. {
  545. struct ast_http_uri *uri;
  546. int len = strlen(urih->uri);
  547. AST_RWLIST_WRLOCK(&uris);
  548. if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
  549. AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
  550. AST_RWLIST_UNLOCK(&uris);
  551. return 0;
  552. }
  553. AST_RWLIST_TRAVERSE(&uris, uri, entry) {
  554. if (AST_RWLIST_NEXT(uri, entry) &&
  555. strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
  556. AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
  557. AST_RWLIST_UNLOCK(&uris);
  558. return 0;
  559. }
  560. }
  561. AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
  562. AST_RWLIST_UNLOCK(&uris);
  563. return 0;
  564. }
  565. void ast_http_uri_unlink(struct ast_http_uri *urih)
  566. {
  567. AST_RWLIST_WRLOCK(&uris);
  568. AST_RWLIST_REMOVE(&uris, urih, entry);
  569. AST_RWLIST_UNLOCK(&uris);
  570. }
  571. void ast_http_uri_unlink_all_with_key(const char *key)
  572. {
  573. struct ast_http_uri *urih;
  574. AST_RWLIST_WRLOCK(&uris);
  575. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
  576. if (!strcmp(urih->key, key)) {
  577. AST_RWLIST_REMOVE_CURRENT(entry);
  578. if (urih->dmallocd) {
  579. ast_free(urih->data);
  580. }
  581. if (urih->mallocd) {
  582. ast_free(urih);
  583. }
  584. }
  585. }
  586. AST_RWLIST_TRAVERSE_SAFE_END;
  587. AST_RWLIST_UNLOCK(&uris);
  588. }
  589. /*!
  590. * \brief Retrieves the header with the given field name.
  591. *
  592. * \param headers Headers to search.
  593. * \param field_name Name of the header to find.
  594. * \return Associated header value.
  595. * \return \c NULL if header is not present.
  596. */
  597. static const char *get_header(struct ast_variable *headers, const char *field_name)
  598. {
  599. struct ast_variable *v;
  600. for (v = headers; v; v = v->next) {
  601. if (!strcasecmp(v->name, field_name)) {
  602. return v->value;
  603. }
  604. }
  605. return NULL;
  606. }
  607. /*!
  608. * \brief Retrieves the content type specified in the "Content-Type" header.
  609. *
  610. * This function only returns the "type/subtype" and any trailing parameter is
  611. * not included.
  612. *
  613. * \note the return value is an allocated string that needs to be freed.
  614. *
  615. * \retval the content type/subtype or NULL if the header is not found.
  616. */
  617. static char *get_content_type(struct ast_variable *headers)
  618. {
  619. const char *content_type = get_header(headers, "Content-Type");
  620. const char *param;
  621. size_t size;
  622. if (!content_type) {
  623. return NULL;
  624. }
  625. param = strchr(content_type, ';');
  626. size = param ? param - content_type : strlen(content_type);
  627. return ast_strndup(content_type, size);
  628. }
  629. /*!
  630. * \brief Returns the value of the Content-Length header.
  631. *
  632. * \param headers HTTP headers.
  633. *
  634. * \retval length Value of the Content-Length header.
  635. * \retval 0 if header is not present.
  636. * \retval -1 if header is invalid.
  637. */
  638. static int get_content_length(struct ast_variable *headers)
  639. {
  640. const char *content_length = get_header(headers, "Content-Length");
  641. int length;
  642. if (!content_length) {
  643. /* Missing content length; assume zero */
  644. return 0;
  645. }
  646. length = 0;
  647. if (sscanf(content_length, "%30d", &length) != 1) {
  648. /* Invalid Content-Length value */
  649. length = -1;
  650. }
  651. return length;
  652. }
  653. /*!
  654. * \brief Returns the value of the Transfer-Encoding header.
  655. *
  656. * \param headers HTTP headers.
  657. * \retval string Value of the Transfer-Encoding header.
  658. * \retval NULL if header is not present.
  659. */
  660. static const char *get_transfer_encoding(struct ast_variable *headers)
  661. {
  662. return get_header(headers, "Transfer-Encoding");
  663. }
  664. /*!
  665. * \internal
  666. * \brief Determine if the HTTP peer wants the connection closed.
  667. *
  668. * \param headers List of HTTP headers
  669. *
  670. * \retval 0 keep connection open.
  671. * \retval -1 close connection.
  672. */
  673. static int http_check_connection_close(struct ast_variable *headers)
  674. {
  675. const char *connection = get_header(headers, "Connection");
  676. int close_connection = 0;
  677. if (connection && !strcasecmp(connection, "close")) {
  678. close_connection = -1;
  679. }
  680. return close_connection;
  681. }
  682. void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
  683. {
  684. struct http_worker_private_data *request = ser->private_data;
  685. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  686. }
  687. /*!
  688. * \internal
  689. * \brief Initialize the request tracking information in case of early failure.
  690. * \since 12.4.0
  691. *
  692. * \param request Request tracking information.
  693. *
  694. * \return Nothing
  695. */
  696. static void http_request_tracking_init(struct http_worker_private_data *request)
  697. {
  698. ast_set_flags_to(&request->flags,
  699. HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
  700. /* Assume close in case request fails early */
  701. HTTP_FLAG_CLOSE_ON_COMPLETION);
  702. }
  703. /*!
  704. * \internal
  705. * \brief Setup the HTTP request tracking information.
  706. * \since 12.4.0
  707. *
  708. * \param ser HTTP TCP/TLS session object.
  709. * \param headers List of HTTP headers.
  710. *
  711. * \retval 0 on success.
  712. * \retval -1 on error.
  713. */
  714. static int http_request_tracking_setup(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  715. {
  716. struct http_worker_private_data *request = ser->private_data;
  717. const char *transfer_encoding;
  718. ast_set_flags_to(&request->flags,
  719. HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
  720. http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
  721. transfer_encoding = get_transfer_encoding(headers);
  722. if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
  723. request->body_length = -1;
  724. ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
  725. return 0;
  726. }
  727. request->body_length = get_content_length(headers);
  728. if (0 < request->body_length) {
  729. ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
  730. } else if (request->body_length < 0) {
  731. /* Invalid Content-Length */
  732. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  733. ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
  734. return -1;
  735. }
  736. return 0;
  737. }
  738. void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
  739. {
  740. struct http_worker_private_data *request;
  741. request = ser->private_data;
  742. if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
  743. || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
  744. /* No body to read. */
  745. return;
  746. }
  747. ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
  748. if (!read_success) {
  749. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  750. }
  751. }
  752. /*!
  753. * \internal
  754. * \brief Read the next length bytes from the HTTP body.
  755. * \since 12.4.0
  756. *
  757. * \param ser HTTP TCP/TLS session object.
  758. * \param buf Where to put the contents reading.
  759. * \param length How much contents to read.
  760. * \param what_getting Name of the contents reading.
  761. *
  762. * \retval 0 on success.
  763. * \retval -1 on error.
  764. */
  765. static int http_body_read_contents(struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
  766. {
  767. int res;
  768. /* Stay in fread until get all the expected data or timeout. */
  769. res = fread(buf, length, 1, ser->f);
  770. if (res < 1) {
  771. ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d)\n",
  772. what_getting, length);
  773. return -1;
  774. }
  775. return 0;
  776. }
  777. /*!
  778. * \internal
  779. * \brief Read and discard the next length bytes from the HTTP body.
  780. * \since 12.4.0
  781. *
  782. * \param ser HTTP TCP/TLS session object.
  783. * \param length How much contents to discard
  784. * \param what_getting Name of the contents discarding.
  785. *
  786. * \retval 0 on success.
  787. * \retval -1 on error.
  788. */
  789. static int http_body_discard_contents(struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
  790. {
  791. int res;
  792. char buf[MAX_HTTP_LINE_LENGTH];/* Discard buffer */
  793. /* Stay in fread until get all the expected data or timeout. */
  794. while (sizeof(buf) < length) {
  795. res = fread(buf, sizeof(buf), 1, ser->f);
  796. if (res < 1) {
  797. ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %zu of remaining %d)\n",
  798. what_getting, sizeof(buf), length);
  799. return -1;
  800. }
  801. length -= sizeof(buf);
  802. }
  803. res = fread(buf, length, 1, ser->f);
  804. if (res < 1) {
  805. ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d of remaining %d)\n",
  806. what_getting, length, length);
  807. return -1;
  808. }
  809. return 0;
  810. }
  811. /*!
  812. * \internal
  813. * \brief decode chunked mode hexadecimal value
  814. *
  815. * \param s string to decode
  816. * \param len length of string
  817. *
  818. * \retval length on success.
  819. * \retval -1 on error.
  820. */
  821. static int chunked_atoh(const char *s, int len)
  822. {
  823. int value = 0;
  824. char c;
  825. if (*s < '0') {
  826. /* zero value must be 0\n not just \n */
  827. return -1;
  828. }
  829. while (len--) {
  830. c = *s++;
  831. if (c == '\x0D') {
  832. return value;
  833. }
  834. if (c == ';') {
  835. /* We have a chunk-extension that we don't care about. */
  836. while (len--) {
  837. if (*s++ == '\x0D') {
  838. return value;
  839. }
  840. }
  841. break;
  842. }
  843. value <<= 4;
  844. if (c >= '0' && c <= '9') {
  845. value += c - '0';
  846. continue;
  847. }
  848. if (c >= 'a' && c <= 'f') {
  849. value += 10 + c - 'a';
  850. continue;
  851. }
  852. if (c >= 'A' && c <= 'F') {
  853. value += 10 + c - 'A';
  854. continue;
  855. }
  856. /* invalid character */
  857. return -1;
  858. }
  859. /* end of string */
  860. return -1;
  861. }
  862. /*!
  863. * \internal
  864. * \brief Read and convert the chunked body header length.
  865. * \since 12.4.0
  866. *
  867. * \param ser HTTP TCP/TLS session object.
  868. *
  869. * \retval length Size of chunk to expect.
  870. * \retval -1 on error.
  871. */
  872. static int http_body_get_chunk_length(struct ast_tcptls_session_instance *ser)
  873. {
  874. int length;
  875. char header_line[MAX_HTTP_LINE_LENGTH];
  876. /* get the line of hexadecimal giving chunk-size w/ optional chunk-extension */
  877. if (!fgets(header_line, sizeof(header_line), ser->f)) {
  878. ast_log(LOG_WARNING, "Short HTTP read of chunked header\n");
  879. return -1;
  880. }
  881. length = chunked_atoh(header_line, strlen(header_line));
  882. if (length < 0) {
  883. ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
  884. return -1;
  885. }
  886. return length;
  887. }
  888. /*!
  889. * \internal
  890. * \brief Read and check the chunk contents line termination.
  891. * \since 12.4.0
  892. *
  893. * \param ser HTTP TCP/TLS session object.
  894. *
  895. * \retval 0 on success.
  896. * \retval -1 on error.
  897. */
  898. static int http_body_check_chunk_sync(struct ast_tcptls_session_instance *ser)
  899. {
  900. int res;
  901. char chunk_sync[2];
  902. /* Stay in fread until get the expected CRLF or timeout. */
  903. res = fread(chunk_sync, sizeof(chunk_sync), 1, ser->f);
  904. if (res < 1) {
  905. ast_log(LOG_WARNING, "Short HTTP chunk sync read (Wanted %zu)\n",
  906. sizeof(chunk_sync));
  907. return -1;
  908. }
  909. if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
  910. ast_log(LOG_WARNING, "HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
  911. (unsigned char) chunk_sync[0], (unsigned char) chunk_sync[1]);
  912. return -1;
  913. }
  914. return 0;
  915. }
  916. /*!
  917. * \internal
  918. * \brief Read and discard any chunked trailer entity-header lines.
  919. * \since 12.4.0
  920. *
  921. * \param ser HTTP TCP/TLS session object.
  922. *
  923. * \retval 0 on success.
  924. * \retval -1 on error.
  925. */
  926. static int http_body_discard_chunk_trailer_headers(struct ast_tcptls_session_instance *ser)
  927. {
  928. char header_line[MAX_HTTP_LINE_LENGTH];
  929. for (;;) {
  930. if (!fgets(header_line, sizeof(header_line), ser->f)) {
  931. ast_log(LOG_WARNING, "Short HTTP read of chunked trailer header\n");
  932. return -1;
  933. }
  934. /* Trim trailing whitespace */
  935. ast_trim_blanks(header_line);
  936. if (ast_strlen_zero(header_line)) {
  937. /* A blank line ends the chunked-body */
  938. break;
  939. }
  940. }
  941. return 0;
  942. }
  943. int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
  944. {
  945. struct http_worker_private_data *request;
  946. request = ser->private_data;
  947. if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
  948. || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
  949. /* No body to read or it has already been read. */
  950. return 0;
  951. }
  952. ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
  953. ast_debug(1, "HTTP discarding unused request body\n");
  954. ast_assert(request->body_length != 0);
  955. if (0 < request->body_length) {
  956. if (http_body_discard_contents(ser, request->body_length, "body")) {
  957. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  958. return -1;
  959. }
  960. return 0;
  961. }
  962. /* parse chunked-body */
  963. for (;;) {
  964. int length;
  965. length = http_body_get_chunk_length(ser);
  966. if (length < 0) {
  967. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  968. return -1;
  969. }
  970. if (length == 0) {
  971. /* parsed last-chunk */
  972. break;
  973. }
  974. if (http_body_discard_contents(ser, length, "chunk-data")
  975. || http_body_check_chunk_sync(ser)) {
  976. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  977. return -1;
  978. }
  979. }
  980. /* Read and discard any trailer entity-header lines. */
  981. if (http_body_discard_chunk_trailer_headers(ser)) {
  982. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  983. return -1;
  984. }
  985. return 0;
  986. }
  987. /*!
  988. * \brief Returns the contents (body) of the HTTP request
  989. *
  990. * \param return_length ptr to int that returns content length
  991. * \param ser HTTP TCP/TLS session object
  992. * \param headers List of HTTP headers
  993. * \return ptr to content (zero terminated) or NULL on failure
  994. * \note Since returned ptr is malloc'd, it should be free'd by caller
  995. */
  996. static char *ast_http_get_contents(int *return_length,
  997. struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  998. {
  999. struct http_worker_private_data *request;
  1000. int content_length;
  1001. int bufsize;
  1002. char *buf;
  1003. request = ser->private_data;
  1004. if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)) {
  1005. /* no content - not an error */
  1006. return NULL;
  1007. }
  1008. if (ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
  1009. /* Already read the body. Cannot read again. Assume no content. */
  1010. ast_assert(0);
  1011. return NULL;
  1012. }
  1013. ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
  1014. ast_debug(2, "HTTP consuming request body\n");
  1015. ast_assert(request->body_length != 0);
  1016. if (0 < request->body_length) {
  1017. /* handle regular non-chunked content */
  1018. content_length = request->body_length;
  1019. if (content_length > MAX_CONTENT_LENGTH) {
  1020. ast_log(LOG_WARNING, "Excessively long HTTP content. (%d > %d)\n",
  1021. content_length, MAX_CONTENT_LENGTH);
  1022. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1023. errno = EFBIG;
  1024. return NULL;
  1025. }
  1026. buf = ast_malloc(content_length + 1);
  1027. if (!buf) {
  1028. /* Malloc sets ENOMEM */
  1029. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1030. return NULL;
  1031. }
  1032. if (http_body_read_contents(ser, buf, content_length, "body")) {
  1033. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1034. errno = EIO;
  1035. ast_free(buf);
  1036. return NULL;
  1037. }
  1038. buf[content_length] = 0;
  1039. *return_length = content_length;
  1040. return buf;
  1041. }
  1042. /* pre-allocate buffer */
  1043. bufsize = 250;
  1044. buf = ast_malloc(bufsize);
  1045. if (!buf) {
  1046. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1047. return NULL;
  1048. }
  1049. /* parse chunked-body */
  1050. content_length = 0;
  1051. for (;;) {
  1052. int chunk_length;
  1053. chunk_length = http_body_get_chunk_length(ser);
  1054. if (chunk_length < 0) {
  1055. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1056. errno = EIO;
  1057. ast_free(buf);
  1058. return NULL;
  1059. }
  1060. if (chunk_length == 0) {
  1061. /* parsed last-chunk */
  1062. break;
  1063. }
  1064. if (content_length + chunk_length > MAX_CONTENT_LENGTH) {
  1065. ast_log(LOG_WARNING,
  1066. "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
  1067. content_length, chunk_length, MAX_CONTENT_LENGTH);
  1068. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1069. errno = EFBIG;
  1070. ast_free(buf);
  1071. return NULL;
  1072. }
  1073. /* insure buffer is large enough +1 */
  1074. if (content_length + chunk_length >= bufsize) {
  1075. char *new_buf;
  1076. /* Increase bufsize until it can handle the expected data. */
  1077. do {
  1078. bufsize *= 2;
  1079. } while (content_length + chunk_length >= bufsize);
  1080. new_buf = ast_realloc(buf, bufsize);
  1081. if (!new_buf) {
  1082. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1083. ast_free(buf);
  1084. return NULL;
  1085. }
  1086. buf = new_buf;
  1087. }
  1088. if (http_body_read_contents(ser, buf + content_length, chunk_length, "chunk-data")
  1089. || http_body_check_chunk_sync(ser)) {
  1090. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1091. errno = EIO;
  1092. ast_free(buf);
  1093. return NULL;
  1094. }
  1095. content_length += chunk_length;
  1096. }
  1097. /*
  1098. * Read and discard any trailer entity-header lines
  1099. * which we don't care about.
  1100. *
  1101. * XXX In the future we may need to add the trailer headers
  1102. * to the passed in headers list rather than discarding them.
  1103. */
  1104. if (http_body_discard_chunk_trailer_headers(ser)) {
  1105. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1106. errno = EIO;
  1107. ast_free(buf);
  1108. return NULL;
  1109. }
  1110. buf[content_length] = 0;
  1111. *return_length = content_length;
  1112. return buf;
  1113. }
  1114. struct ast_json *ast_http_get_json(
  1115. struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  1116. {
  1117. int content_length = 0;
  1118. struct ast_json *body;
  1119. RAII_VAR(char *, buf, NULL, ast_free);
  1120. RAII_VAR(char *, type, get_content_type(headers), ast_free);
  1121. /* Use errno to distinguish errors from no body */
  1122. errno = 0;
  1123. if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
  1124. /* Content type is not JSON. Don't read the body. */
  1125. return NULL;
  1126. }
  1127. buf = ast_http_get_contents(&content_length, ser, headers);
  1128. if (!buf || !content_length) {
  1129. /*
  1130. * errno already set
  1131. * or it is not an error to have zero content
  1132. */
  1133. return NULL;
  1134. }
  1135. body = ast_json_load_buf(buf, content_length, NULL);
  1136. if (!body) {
  1137. /* Failed to parse JSON; treat as an I/O error */
  1138. errno = EIO;
  1139. return NULL;
  1140. }
  1141. return body;
  1142. }
  1143. /*
  1144. * get post variables from client Request Entity-Body, if content type is
  1145. * application/x-www-form-urlencoded
  1146. */
  1147. struct ast_variable *ast_http_get_post_vars(
  1148. struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  1149. {
  1150. int content_length = 0;
  1151. struct ast_variable *v, *post_vars=NULL, *prev = NULL;
  1152. char *var, *val;
  1153. RAII_VAR(char *, buf, NULL, ast_free);
  1154. RAII_VAR(char *, type, get_content_type(headers), ast_free);
  1155. /* Use errno to distinguish errors from no params */
  1156. errno = 0;
  1157. if (ast_strlen_zero(type) ||
  1158. strcasecmp(type, "application/x-www-form-urlencoded")) {
  1159. /* Content type is not form data. Don't read the body. */
  1160. return NULL;
  1161. }
  1162. buf = ast_http_get_contents(&content_length, ser, headers);
  1163. if (!buf || !content_length) {
  1164. /*
  1165. * errno already set
  1166. * or it is not an error to have zero content
  1167. */
  1168. return NULL;
  1169. }
  1170. while ((val = strsep(&buf, "&"))) {
  1171. var = strsep(&val, "=");
  1172. if (val) {
  1173. ast_uri_decode(val, ast_uri_http_legacy);
  1174. } else {
  1175. val = "";
  1176. }
  1177. ast_uri_decode(var, ast_uri_http_legacy);
  1178. if ((v = ast_variable_new(var, val, ""))) {
  1179. if (post_vars) {
  1180. prev->next = v;
  1181. } else {
  1182. post_vars = v;
  1183. }
  1184. prev = v;
  1185. }
  1186. }
  1187. return post_vars;
  1188. }
  1189. static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
  1190. enum ast_http_method method, struct ast_variable *headers)
  1191. {
  1192. char *c;
  1193. int res = 0;
  1194. char *params = uri;
  1195. struct ast_http_uri *urih = NULL;
  1196. int l;
  1197. struct ast_variable *get_vars = NULL, *v, *prev = NULL;
  1198. struct http_uri_redirect *redirect;
  1199. ast_debug(2, "HTTP Request URI is %s \n", uri);
  1200. strsep(&params, "?");
  1201. /* Extract arguments from the request and store them in variables. */
  1202. if (params) {
  1203. char *var, *val;
  1204. while ((val = strsep(&params, "&"))) {
  1205. var = strsep(&val, "=");
  1206. if (val) {
  1207. ast_uri_decode(val, ast_uri_http_legacy);
  1208. } else {
  1209. val = "";
  1210. }
  1211. ast_uri_decode(var, ast_uri_http_legacy);
  1212. if ((v = ast_variable_new(var, val, ""))) {
  1213. if (get_vars) {
  1214. prev->next = v;
  1215. } else {
  1216. get_vars = v;
  1217. }
  1218. prev = v;
  1219. }
  1220. }
  1221. }
  1222. AST_RWLIST_RDLOCK(&uri_redirects);
  1223. AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
  1224. if (!strcasecmp(uri, redirect->target)) {
  1225. struct ast_str *http_header = ast_str_create(128);
  1226. if (!http_header) {
  1227. ast_http_request_close_on_completion(ser);
  1228. ast_http_error(ser, 500, "Server Error", "Out of memory");
  1229. break;
  1230. }
  1231. ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
  1232. ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
  1233. break;
  1234. }
  1235. }
  1236. AST_RWLIST_UNLOCK(&uri_redirects);
  1237. if (redirect) {
  1238. goto cleanup;
  1239. }
  1240. /* We want requests to start with the (optional) prefix and '/' */
  1241. l = strlen(prefix);
  1242. if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
  1243. uri += l + 1;
  1244. /* scan registered uris to see if we match one. */
  1245. AST_RWLIST_RDLOCK(&uris);
  1246. AST_RWLIST_TRAVERSE(&uris, urih, entry) {
  1247. l = strlen(urih->uri);
  1248. c = uri + l; /* candidate */
  1249. ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
  1250. if (strncasecmp(urih->uri, uri, l) /* no match */
  1251. || (*c && *c != '/')) { /* substring */
  1252. continue;
  1253. }
  1254. if (*c == '/') {
  1255. c++;
  1256. }
  1257. if (!*c || urih->has_subtree) {
  1258. uri = c;
  1259. break;
  1260. }
  1261. }
  1262. AST_RWLIST_UNLOCK(&uris);
  1263. }
  1264. if (urih) {
  1265. ast_debug(1, "Match made with [%s]\n", urih->uri);
  1266. if (!urih->no_decode_uri) {
  1267. ast_uri_decode(uri, ast_uri_http_legacy);
  1268. }
  1269. res = urih->callback(ser, urih, uri, method, get_vars, headers);
  1270. } else {
  1271. ast_debug(1, "Requested URI [%s] has no handler\n", uri);
  1272. ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
  1273. }
  1274. cleanup:
  1275. ast_variables_destroy(get_vars);
  1276. return res;
  1277. }
  1278. #ifdef DO_SSL
  1279. #if defined(HAVE_FUNOPEN)
  1280. #define HOOK_T int
  1281. #define LEN_T int
  1282. #else
  1283. #define HOOK_T ssize_t
  1284. #define LEN_T size_t
  1285. #endif
  1286. /*!
  1287. * replacement read/write functions for SSL support.
  1288. * We use wrappers rather than SSL_read/SSL_write directly so
  1289. * we can put in some debugging.
  1290. */
  1291. /*static HOOK_T ssl_read(void *cookie, char *buf, LEN_T len)
  1292. {
  1293. int i = SSL_read(cookie, buf, len-1);
  1294. #if 0
  1295. if (i >= 0)
  1296. buf[i] = '\0';
  1297. ast_verbose("ssl read size %d returns %d <%s>\n", (int)len, i, buf);
  1298. #endif
  1299. return i;
  1300. }
  1301. static HOOK_T ssl_write(void *cookie, const char *buf, LEN_T len)
  1302. {
  1303. #if 0
  1304. char *s = ast_alloca(len+1);
  1305. strncpy(s, buf, len);
  1306. s[len] = '\0';
  1307. ast_verbose("ssl write size %d <%s>\n", (int)len, s);
  1308. #endif
  1309. return SSL_write(cookie, buf, len);
  1310. }
  1311. static int ssl_close(void *cookie)
  1312. {
  1313. close(SSL_get_fd(cookie));
  1314. SSL_shutdown(cookie);
  1315. SSL_free(cookie);
  1316. return 0;
  1317. }*/
  1318. #endif /* DO_SSL */
  1319. static struct ast_variable *parse_cookies(const char *cookies)
  1320. {
  1321. char *parse = ast_strdupa(cookies);
  1322. char *cur;
  1323. struct ast_variable *vars = NULL, *var;
  1324. while ((cur = strsep(&parse, ";"))) {
  1325. char *name, *val;
  1326. name = val = cur;
  1327. strsep(&val, "=");
  1328. if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
  1329. continue;
  1330. }
  1331. name = ast_strip(name);
  1332. val = ast_strip_quoted(val, "\"", "\"");
  1333. if (ast_strlen_zero(name) || ast_strlen_zero(val)) {
  1334. continue;
  1335. }
  1336. ast_debug(1, "HTTP Cookie, Name: '%s' Value: '%s'\n", name, val);
  1337. var = ast_variable_new(name, val, __FILE__);
  1338. var->next = vars;
  1339. vars = var;
  1340. }
  1341. return vars;
  1342. }
  1343. /* get cookie from Request headers */
  1344. struct ast_variable *ast_http_get_cookies(struct ast_variable *headers)
  1345. {
  1346. struct ast_variable *v, *cookies = NULL;
  1347. for (v = headers; v; v = v->next) {
  1348. if (!strcasecmp(v->name, "Cookie")) {
  1349. ast_variables_destroy(cookies);
  1350. cookies = parse_cookies(v->value);
  1351. }
  1352. }
  1353. return cookies;
  1354. }
  1355. static struct ast_http_auth *auth_create(const char *userid, const char *password)
  1356. {
  1357. struct ast_http_auth *auth;
  1358. size_t userid_len;
  1359. size_t password_len;
  1360. if (!userid || !password) {
  1361. ast_log(LOG_ERROR, "Invalid userid/password\n");
  1362. return NULL;
  1363. }
  1364. userid_len = strlen(userid) + 1;
  1365. password_len = strlen(password) + 1;
  1366. /* Allocate enough room to store everything in one memory block */
  1367. auth = ao2_alloc(sizeof(*auth) + userid_len + password_len, NULL);
  1368. if (!auth) {
  1369. return NULL;
  1370. }
  1371. /* Put the userid right after the struct */
  1372. auth->userid = (char *)(auth + 1);
  1373. strcpy(auth->userid, userid);
  1374. /* Put the password right after the userid */
  1375. auth->password = auth->userid + userid_len;
  1376. strcpy(auth->password, password);
  1377. return auth;
  1378. }
  1379. #define BASIC_PREFIX "Basic "
  1380. #define BASIC_LEN 6 /*!< strlen(BASIC_PREFIX) */
  1381. struct ast_http_auth *ast_http_get_auth(struct ast_variable *headers)
  1382. {
  1383. struct ast_variable *v;
  1384. for (v = headers; v; v = v->next) {
  1385. const char *base64;
  1386. char decoded[256] = {};
  1387. char *username;
  1388. char *password;
  1389. #ifdef AST_DEVMODE
  1390. int cnt;
  1391. #endif /* AST_DEVMODE */
  1392. if (strcasecmp("Authorization", v->name) != 0) {
  1393. continue;
  1394. }
  1395. if (!ast_begins_with(v->value, BASIC_PREFIX)) {
  1396. ast_log(LOG_DEBUG,
  1397. "Unsupported Authorization scheme\n");
  1398. continue;
  1399. }
  1400. /* Basic auth header parsing. RFC 2617, section 2.
  1401. * credentials = "Basic" basic-credentials
  1402. * basic-credentials = base64-user-pass
  1403. * base64-user-pass = <base64 encoding of user-pass,
  1404. * except not limited to 76 char/line>
  1405. * user-pass = userid ":" password
  1406. */
  1407. base64 = v->value + BASIC_LEN;
  1408. /* This will truncate "userid:password" lines to
  1409. * sizeof(decoded). The array is long enough that this shouldn't
  1410. * be a problem */
  1411. #ifdef AST_DEVMODE
  1412. cnt =
  1413. #endif /* AST_DEVMODE */
  1414. ast_base64decode((unsigned char*)decoded, base64,
  1415. sizeof(decoded) - 1);
  1416. ast_assert(cnt < sizeof(decoded));
  1417. /* Split the string at the colon */
  1418. password = decoded;
  1419. username = strsep(&password, ":");
  1420. if (!password) {
  1421. ast_log(LOG_WARNING, "Invalid Authorization header\n");
  1422. return NULL;
  1423. }
  1424. return auth_create(username, password);
  1425. }
  1426. return NULL;
  1427. }
  1428. /*! Limit the number of request headers in case the sender is being ridiculous. */
  1429. #define MAX_HTTP_REQUEST_HEADERS 100
  1430. /*!
  1431. * \internal
  1432. * \brief Read the request headers.
  1433. * \since 12.4.0
  1434. *
  1435. * \param ser HTTP TCP/TLS session object.
  1436. * \param headers Where to put the request headers list pointer.
  1437. *
  1438. * \retval 0 on success.
  1439. * \retval -1 on error.
  1440. */
  1441. static int http_request_headers_get(struct ast_tcptls_session_instance *ser, struct ast_variable **headers)
  1442. {
  1443. struct ast_variable *tail = *headers;
  1444. int remaining_headers;
  1445. char header_line[MAX_HTTP_LINE_LENGTH];
  1446. remaining_headers = MAX_HTTP_REQUEST_HEADERS;
  1447. for (;;) {
  1448. char *name;
  1449. char *value;
  1450. if (!fgets(header_line, sizeof(header_line), ser->f)) {
  1451. ast_http_error(ser, 400, "Bad Request", "Timeout");
  1452. return -1;
  1453. }
  1454. /* Trim trailing characters */
  1455. ast_trim_blanks(header_line);
  1456. if (ast_strlen_zero(header_line)) {
  1457. /* A blank line ends the request header section. */
  1458. break;
  1459. }
  1460. value = header_line;
  1461. name = strsep(&value, ":");
  1462. if (!value) {
  1463. continue;
  1464. }
  1465. value = ast_skip_blanks(value);
  1466. if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
  1467. continue;
  1468. }
  1469. ast_trim_blanks(name);
  1470. if (!remaining_headers--) {
  1471. /* Too many headers. */
  1472. ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
  1473. return -1;
  1474. }
  1475. if (!*headers) {
  1476. *headers = ast_variable_new(name, value, __FILE__);
  1477. tail = *headers;
  1478. } else {
  1479. tail->next = ast_variable_new(name, value, __FILE__);
  1480. tail = tail->next;
  1481. }
  1482. if (!tail) {
  1483. /*
  1484. * Variable allocation failure.
  1485. * Try to make some room.
  1486. */
  1487. ast_variables_destroy(*headers);
  1488. *headers = NULL;
  1489. ast_http_error(ser, 500, "Server Error", "Out of memory");
  1490. return -1;
  1491. }
  1492. }
  1493. return 0;
  1494. }
  1495. /*!
  1496. * \internal
  1497. * \brief Process a HTTP request.
  1498. * \since 12.4.0
  1499. *
  1500. * \param ser HTTP TCP/TLS session object.
  1501. *
  1502. * \retval 0 Continue and process the next HTTP request.
  1503. * \retval -1 Fatal HTTP connection error. Force the HTTP connection closed.
  1504. */
  1505. static int httpd_process_request(struct ast_tcptls_session_instance *ser)
  1506. {
  1507. RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
  1508. char *uri;
  1509. char *method;
  1510. const char *transfer_encoding;
  1511. struct http_worker_private_data *request;
  1512. enum ast_http_method http_method = AST_HTTP_UNKNOWN;
  1513. int res;
  1514. char request_line[MAX_HTTP_LINE_LENGTH];
  1515. if (!fgets(request_line, sizeof(request_line), ser->f)) {
  1516. return -1;
  1517. }
  1518. /* Re-initialize the request body tracking data. */
  1519. request = ser->private_data;
  1520. http_request_tracking_init(request);
  1521. /* Get method */
  1522. method = ast_skip_blanks(request_line);
  1523. uri = ast_skip_nonblanks(method);
  1524. if (*uri) {
  1525. *uri++ = '\0';
  1526. }
  1527. if (!strcasecmp(method,"GET")) {
  1528. http_method = AST_HTTP_GET;
  1529. } else if (!strcasecmp(method,"POST")) {
  1530. http_method = AST_HTTP_POST;
  1531. } else if (!strcasecmp(method,"HEAD")) {
  1532. http_method = AST_HTTP_HEAD;
  1533. } else if (!strcasecmp(method,"PUT")) {
  1534. http_method = AST_HTTP_PUT;
  1535. } else if (!strcasecmp(method,"DELETE")) {
  1536. http_method = AST_HTTP_DELETE;
  1537. } else if (!strcasecmp(method,"OPTIONS")) {
  1538. http_method = AST_HTTP_OPTIONS;
  1539. }
  1540. uri = ast_skip_blanks(uri); /* Skip white space */
  1541. if (*uri) { /* terminate at the first blank */
  1542. char *c = ast_skip_nonblanks(uri);
  1543. if (*c) {
  1544. *c = '\0';
  1545. }
  1546. } else {
  1547. ast_http_error(ser, 400, "Bad Request", "Invalid Request");
  1548. return -1;
  1549. }
  1550. /* process "Request Headers" lines */
  1551. if (http_request_headers_get(ser, &headers)) {
  1552. return -1;
  1553. }
  1554. transfer_encoding = get_transfer_encoding(headers);
  1555. /* Transfer encoding defaults to identity */
  1556. if (!transfer_encoding) {
  1557. transfer_encoding = "identity";
  1558. }
  1559. /*
  1560. * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
  1561. * codings we don't understand.
  1562. */
  1563. if (strcasecmp(transfer_encoding, "identity") != 0 &&
  1564. strcasecmp(transfer_encoding, "chunked") != 0) {
  1565. /* Transfer encodings not supported */
  1566. ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
  1567. return -1;
  1568. }
  1569. if (http_request_tracking_setup(ser, headers)
  1570. || handle_uri(ser, uri, http_method, headers)
  1571. || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
  1572. res = -1;
  1573. } else {
  1574. res = 0;
  1575. }
  1576. return res;
  1577. }
  1578. static void *httpd_helper_thread(void *data)
  1579. {
  1580. struct ast_tcptls_session_instance *ser = data;
  1581. struct protoent *p;
  1582. int flags;
  1583. int timeout;
  1584. if (!ser || !ser->f) {
  1585. ao2_cleanup(ser);
  1586. return NULL;
  1587. }
  1588. if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
  1589. ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
  1590. session_limit);
  1591. goto done;
  1592. }
  1593. ast_debug(1, "HTTP opening session. Top level\n");
  1594. /*
  1595. * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
  1596. * This is necessary to prevent delays (caused by buffering) as we
  1597. * write to the socket in bits and pieces.
  1598. */
  1599. p = getprotobyname("tcp");
  1600. if (p) {
  1601. int arg = 1;
  1602. if (setsockopt(ser->fd, p->p_proto, TCP_NODELAY, (char *) &arg, sizeof(arg) ) < 0) {
  1603. ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
  1604. ast_log(LOG_WARNING, "Some HTTP requests may be slow to respond.\n");
  1605. }
  1606. } else {
  1607. ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection, getprotobyname(\"tcp\") failed\n");
  1608. ast_log(LOG_WARNING, "Some HTTP requests may be slow to respond.\n");
  1609. }
  1610. /* make sure socket is non-blocking */
  1611. flags = fcntl(ser->fd, F_GETFL);
  1612. flags |= O_NONBLOCK;
  1613. fcntl(ser->fd, F_SETFL, flags);
  1614. /* Setup HTTP worker private data to keep track of request body reading. */
  1615. ao2_cleanup(ser->private_data);
  1616. ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
  1617. AO2_ALLOC_OPT_LOCK_NOLOCK);
  1618. if (!ser->private_data) {
  1619. ast_http_error(ser, 500, "Server Error", "Out of memory");
  1620. goto done;
  1621. }
  1622. http_request_tracking_init(ser->private_data);
  1623. /* Determine initial HTTP request wait timeout. */
  1624. timeout = session_keep_alive;
  1625. if (timeout <= 0) {
  1626. /* Persistent connections not enabled. */
  1627. timeout = session_inactivity;
  1628. }
  1629. if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
  1630. timeout = MIN_INITIAL_REQUEST_TIMEOUT;
  1631. }
  1632. /* We can let the stream wait for data to arrive. */
  1633. ast_tcptls_stream_set_exclusive_input(ser->stream_cookie, 1);
  1634. for (;;) {
  1635. int ch;
  1636. /* Wait for next potential HTTP request message. */
  1637. ast_tcptls_stream_set_timeout_inactivity(ser->stream_cookie, timeout);
  1638. ch = fgetc(ser->f);
  1639. if (ch == EOF || ungetc(ch, ser->f) == EOF) {
  1640. /* Between request idle timeout */
  1641. ast_debug(1, "HTTP idle timeout or peer closed connection.\n");
  1642. break;
  1643. }
  1644. ast_tcptls_stream_set_timeout_inactivity(ser->stream_cookie, session_inactivity);
  1645. if (httpd_process_request(ser) || !ser->f || feof(ser->f)) {
  1646. /* Break the connection or the connection closed */
  1647. break;
  1648. }
  1649. timeout = session_keep_alive;
  1650. if (timeout <= 0) {
  1651. /* Persistent connections not enabled. */
  1652. break;
  1653. }
  1654. }
  1655. done:
  1656. ast_atomic_fetchadd_int(&session_count, -1);
  1657. if (ser->f) {
  1658. ast_debug(1, "HTTP closing session. Top level\n");
  1659. ast_tcptls_close_session_file(ser);
  1660. }
  1661. ao2_ref(ser, -1);
  1662. return NULL;
  1663. }
  1664. /*!
  1665. * \brief Add a new URI redirect
  1666. * The entries in the redirect list are sorted by length, just like the list
  1667. * of URI handlers.
  1668. */
  1669. static void add_redirect(const char *value)
  1670. {
  1671. char *target, *dest;
  1672. struct http_uri_redirect *redirect, *cur;
  1673. unsigned int target_len;
  1674. unsigned int total_len;
  1675. dest = ast_strdupa(value);
  1676. dest = ast_skip_blanks(dest);
  1677. target = strsep(&dest, " ");
  1678. target = ast_skip_blanks(target);
  1679. target = strsep(&target, " "); /* trim trailing whitespace */
  1680. if (!dest) {
  1681. ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
  1682. return;
  1683. }
  1684. target_len = strlen(target) + 1;
  1685. total_len = sizeof(*redirect) + target_len + strlen(dest) + 1;
  1686. if (!(redirect = ast_calloc(1, total_len))) {
  1687. return;
  1688. }
  1689. redirect->dest = redirect->target + target_len;
  1690. strcpy(redirect->target, target);
  1691. strcpy(redirect->dest, dest);
  1692. AST_RWLIST_WRLOCK(&uri_redirects);
  1693. target_len--; /* So we can compare directly with strlen() */
  1694. if (AST_RWLIST_EMPTY(&uri_redirects)
  1695. || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
  1696. AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
  1697. AST_RWLIST_UNLOCK(&uri_redirects);
  1698. return;
  1699. }
  1700. AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
  1701. if (AST_RWLIST_NEXT(cur, entry)
  1702. && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
  1703. AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
  1704. AST_RWLIST_UNLOCK(&uri_redirects);
  1705. return;
  1706. }
  1707. }
  1708. AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
  1709. AST_RWLIST_UNLOCK(&uri_redirects);
  1710. }
  1711. static int __ast_http_load(int reload)
  1712. {
  1713. struct ast_config *cfg;
  1714. struct ast_variable *v;
  1715. int enabled=0;
  1716. int newenablestatic=0;
  1717. char newprefix[MAX_PREFIX] = "";
  1718. struct http_uri_redirect *redirect;
  1719. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  1720. uint32_t bindport = DEFAULT_PORT;
  1721. RAII_VAR(struct ast_sockaddr *, addrs, NULL, ast_free);
  1722. int num_addrs = 0;
  1723. int http_tls_was_enabled = 0;
  1724. cfg = ast_config_load2("http.conf", "http", config_flags);
  1725. if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
  1726. return 0;
  1727. }
  1728. http_tls_was_enabled = (reload && http_tls_cfg.enabled);
  1729. http_tls_cfg.enabled = 0;
  1730. if (http_tls_cfg.certfile) {
  1731. ast_free(http_tls_cfg.certfile);
  1732. }
  1733. http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
  1734. if (http_tls_cfg.pvtfile) {
  1735. ast_free(http_tls_cfg.pvtfile);
  1736. }
  1737. http_tls_cfg.pvtfile = ast_strdup("");
  1738. if (http_tls_cfg.cipher) {
  1739. ast_free(http_tls_cfg.cipher);
  1740. }
  1741. http_tls_cfg.cipher = ast_strdup("");
  1742. AST_RWLIST_WRLOCK(&uri_redirects);
  1743. while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
  1744. ast_free(redirect);
  1745. }
  1746. AST_RWLIST_UNLOCK(&uri_redirects);
  1747. ast_sockaddr_setnull(&https_desc.local_address);
  1748. session_limit = DEFAULT_SESSION_LIMIT;
  1749. session_inactivity = DEFAULT_SESSION_INACTIVITY;
  1750. session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
  1751. v = ast_variable_browse(cfg, "general");
  1752. for (; v; v = v->next) {
  1753. /* read tls config options while preventing unsupported options from being set */
  1754. if (strcasecmp(v->name, "tlscafile")
  1755. && strcasecmp(v->name, "tlscapath")
  1756. && strcasecmp(v->name, "tlscadir")
  1757. && strcasecmp(v->name, "tlsverifyclient")
  1758. && strcasecmp(v->name, "tlsdontverifyserver")
  1759. && strcasecmp(v->name, "tlsclientmethod")
  1760. && strcasecmp(v->name, "sslclientmethod")
  1761. && strcasecmp(v->name, "tlscipher")
  1762. && strcasecmp(v->name, "sslcipher")
  1763. && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
  1764. continue;
  1765. }
  1766. if (!strcasecmp(v->name, "enabled")) {
  1767. enabled = ast_true(v->value);
  1768. } else if (!strcasecmp(v->name, "enablestatic")) {
  1769. newenablestatic = ast_true(v->value);
  1770. } else if (!strcasecmp(v->name, "bindport")) {
  1771. if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
  1772. &bindport, DEFAULT_PORT, 0, 65535)) {
  1773. ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
  1774. v->value, DEFAULT_PORT);
  1775. }
  1776. } else if (!strcasecmp(v->name, "bindaddr")) {
  1777. if (!(num_addrs = ast_sockaddr_resolve(&addrs, v->value, 0, AST_AF_UNSPEC))) {
  1778. ast_log(LOG_WARNING, "Invalid bind address %s\n", v->value);
  1779. }
  1780. } else if (!strcasecmp(v->name, "prefix")) {
  1781. if (!ast_strlen_zero(v->value)) {
  1782. newprefix[0] = '/';
  1783. ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
  1784. } else {
  1785. newprefix[0] = '\0';
  1786. }
  1787. } else if (!strcasecmp(v->name, "redirect")) {
  1788. add_redirect(v->value);
  1789. } else if (!strcasecmp(v->name, "sessionlimit")) {
  1790. if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
  1791. &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
  1792. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
  1793. v->name, v->value, v->lineno);
  1794. }
  1795. } else if (!strcasecmp(v->name, "session_inactivity")) {
  1796. if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
  1797. &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
  1798. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
  1799. v->name, v->value, v->lineno);
  1800. }
  1801. } else if (!strcasecmp(v->name, "session_keep_alive")) {
  1802. if (sscanf(v->value, "%30d", &session_keep_alive) != 1
  1803. || session_keep_alive < 0) {
  1804. session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
  1805. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
  1806. v->name, v->value, v->lineno);
  1807. }
  1808. } else {
  1809. ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
  1810. }
  1811. }
  1812. ast_config_destroy(cfg);
  1813. if (strcmp(prefix, newprefix)) {
  1814. ast_copy_string(prefix, newprefix, sizeof(prefix));
  1815. }
  1816. enablestatic = newenablestatic;
  1817. if (num_addrs && enabled) {
  1818. int i;
  1819. for (i = 0; i < num_addrs; ++i) {
  1820. ast_sockaddr_copy(&http_desc.local_address, &addrs[i]);
  1821. if (!ast_sockaddr_port(&http_desc.local_address)) {
  1822. ast_sockaddr_set_port(&http_desc.local_address, bindport);
  1823. }
  1824. ast_tcptls_server_start(&http_desc);
  1825. if (http_desc.accept_fd == -1) {
  1826. ast_log(LOG_WARNING, "Failed to start HTTP server for address %s\n", ast_sockaddr_stringify(&addrs[i]));
  1827. ast_sockaddr_setnull(&http_desc.local_address);
  1828. } else {
  1829. ast_verb(1, "Bound HTTP server to address %s\n", ast_sockaddr_stringify(&addrs[i]));
  1830. break;
  1831. }
  1832. }
  1833. /* When no specific TLS bindaddr is specified, we just use
  1834. * the non-TLS bindaddress here.
  1835. */
  1836. if (ast_sockaddr_isnull(&https_desc.local_address) && http_desc.accept_fd != -1) {
  1837. ast_sockaddr_copy(&https_desc.local_address, &https_desc.local_address);
  1838. /* Of course, we can't use the same port though.
  1839. * Since no bind address was specified, we just use the
  1840. * default TLS port
  1841. */
  1842. ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
  1843. }
  1844. }
  1845. if (http_tls_was_enabled && !http_tls_cfg.enabled) {
  1846. ast_tcptls_server_stop(&https_desc);
  1847. } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
  1848. /* We can get here either because a TLS-specific address was specified
  1849. * or because we copied the non-TLS address here. In the case where
  1850. * we read an explicit address from the config, there may have been
  1851. * no port specified, so we'll just use the default TLS port.
  1852. */
  1853. if (!ast_sockaddr_port(&https_desc.local_address)) {
  1854. ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
  1855. }
  1856. if (ast_ssl_setup(https_desc.tls_cfg)) {
  1857. ast_tcptls_server_start(&https_desc);
  1858. }
  1859. }
  1860. return 0;
  1861. }
  1862. static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1863. {
  1864. struct ast_http_uri *urih;
  1865. struct http_uri_redirect *redirect;
  1866. switch (cmd) {
  1867. case CLI_INIT:
  1868. e->command = "http show status";
  1869. e->usage =
  1870. "Usage: http show status\n"
  1871. " Lists status of internal HTTP engine\n";
  1872. return NULL;
  1873. case CLI_GENERATE:
  1874. return NULL;
  1875. }
  1876. if (a->argc != 3) {
  1877. return CLI_SHOWUSAGE;
  1878. }
  1879. ast_cli(a->fd, "HTTP Server Status:\n");
  1880. ast_cli(a->fd, "Prefix: %s\n", prefix);
  1881. if (ast_sockaddr_isnull(&http_desc.old_address)) {
  1882. ast_cli(a->fd, "Server Disabled\n\n");
  1883. } else {
  1884. ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
  1885. ast_sockaddr_stringify(&http_desc.old_address));
  1886. if (http_tls_cfg.enabled) {
  1887. ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
  1888. ast_sockaddr_stringify(&https_desc.old_address));
  1889. }
  1890. }
  1891. ast_cli(a->fd, "Enabled URI's:\n");
  1892. AST_RWLIST_RDLOCK(&uris);
  1893. if (AST_RWLIST_EMPTY(&uris)) {
  1894. ast_cli(a->fd, "None.\n");
  1895. } else {
  1896. AST_RWLIST_TRAVERSE(&uris, urih, entry)
  1897. ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
  1898. }
  1899. AST_RWLIST_UNLOCK(&uris);
  1900. ast_cli(a->fd, "\nEnabled Redirects:\n");
  1901. AST_RWLIST_RDLOCK(&uri_redirects);
  1902. AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
  1903. ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
  1904. if (AST_RWLIST_EMPTY(&uri_redirects)) {
  1905. ast_cli(a->fd, " None.\n");
  1906. }
  1907. AST_RWLIST_UNLOCK(&uri_redirects);
  1908. return CLI_SUCCESS;
  1909. }
  1910. int ast_http_reload(void)
  1911. {
  1912. return __ast_http_load(1);
  1913. }
  1914. static struct ast_cli_entry cli_http[] = {
  1915. AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
  1916. };
  1917. static void http_shutdown(void)
  1918. {
  1919. struct http_uri_redirect *redirect;
  1920. ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
  1921. ast_tcptls_server_stop(&http_desc);
  1922. if (http_tls_cfg.enabled) {
  1923. ast_tcptls_server_stop(&https_desc);
  1924. }
  1925. ast_free(http_tls_cfg.certfile);
  1926. ast_free(http_tls_cfg.pvtfile);
  1927. ast_free(http_tls_cfg.cipher);
  1928. ast_http_uri_unlink(&statusuri);
  1929. ast_http_uri_unlink(&staticuri);
  1930. AST_RWLIST_WRLOCK(&uri_redirects);
  1931. while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
  1932. ast_free(redirect);
  1933. }
  1934. AST_RWLIST_UNLOCK(&uri_redirects);
  1935. }
  1936. int ast_http_init(void)
  1937. {
  1938. ast_http_uri_link(&statusuri);
  1939. ast_http_uri_link(&staticuri);
  1940. ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
  1941. ast_register_atexit(http_shutdown);
  1942. return __ast_http_load(0);
  1943. }