http.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682
  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. #include <time.h>
  42. #include <sys/time.h>
  43. #include <sys/stat.h>
  44. #include <signal.h>
  45. #include <fcntl.h>
  46. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  47. #include "asterisk/cli.h"
  48. #include "asterisk/tcptls.h"
  49. #include "asterisk/http.h"
  50. #include "asterisk/utils.h"
  51. #include "asterisk/strings.h"
  52. #include "asterisk/config.h"
  53. #include "asterisk/stringfields.h"
  54. #include "asterisk/ast_version.h"
  55. #include "asterisk/manager.h"
  56. #include "asterisk/module.h"
  57. #include "asterisk/astobj2.h"
  58. #include "asterisk/netsock2.h"
  59. #include "asterisk/json.h"
  60. #define MAX_PREFIX 80
  61. #define DEFAULT_PORT 8088
  62. #define DEFAULT_TLS_PORT 8089
  63. #define DEFAULT_SESSION_LIMIT 100
  64. /*! (ms) Idle time waiting for data. */
  65. #define DEFAULT_SESSION_INACTIVITY 30000
  66. /*! (ms) Min timeout for initial HTTP request to start coming in. */
  67. #define MIN_INITIAL_REQUEST_TIMEOUT 10000
  68. /*! (ms) Idle time between HTTP requests */
  69. #define DEFAULT_SESSION_KEEP_ALIVE 15000
  70. /*! Max size for the http server name */
  71. #define MAX_SERVER_NAME_LENGTH 128
  72. /*! Max size for the http response header */
  73. #define DEFAULT_RESPONSE_HEADER_LENGTH 512
  74. /*! Maximum application/json or application/x-www-form-urlencoded body content length. */
  75. #if !defined(LOW_MEMORY)
  76. #define MAX_CONTENT_LENGTH 40960
  77. #else
  78. #define MAX_CONTENT_LENGTH 1024
  79. #endif /* !defined(LOW_MEMORY) */
  80. /*! Initial response body length. */
  81. #if !defined(LOW_MEMORY)
  82. #define INITIAL_RESPONSE_BODY_BUFFER 1024
  83. #else
  84. #define INITIAL_RESPONSE_BODY_BUFFER 512
  85. #endif /* !defined(LOW_MEMORY) */
  86. /*! Maximum line length for HTTP requests. */
  87. #if !defined(LOW_MEMORY)
  88. #define MAX_HTTP_LINE_LENGTH 4096
  89. #else
  90. #define MAX_HTTP_LINE_LENGTH 1024
  91. #endif /* !defined(LOW_MEMORY) */
  92. static char http_server_name[MAX_SERVER_NAME_LENGTH];
  93. static int session_limit = DEFAULT_SESSION_LIMIT;
  94. static int session_inactivity = DEFAULT_SESSION_INACTIVITY;
  95. static int session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
  96. static int session_count = 0;
  97. static struct ast_tls_config http_tls_cfg;
  98. static void *httpd_helper_thread(void *arg);
  99. /*!
  100. * For standard configuration we have up to two accepting threads,
  101. * one for http, one for https. If TEST_FRAMEWORK is enabled it's
  102. * possible to have more than one running http server.
  103. */
  104. struct ast_http_server {
  105. struct ast_tcptls_session_args args;
  106. char *name;
  107. char *address;
  108. };
  109. /*!
  110. * The default configured HTTP server
  111. */
  112. struct ast_http_server *global_http_server = NULL;
  113. static struct ast_tcptls_session_args https_desc = {
  114. .accept_fd = -1,
  115. .master = AST_PTHREADT_NULL,
  116. .tls_cfg = &http_tls_cfg,
  117. .poll_timeout = -1,
  118. .name = "https server",
  119. .accept_fn = ast_tcptls_server_root,
  120. .worker_fn = httpd_helper_thread,
  121. };
  122. static AST_RWLIST_HEAD_STATIC(uris, ast_http_uri); /*!< list of supported handlers */
  123. /* all valid URIs must be prepended by the string in prefix. */
  124. static char prefix[MAX_PREFIX];
  125. static int static_uri_enabled;
  126. static int status_uri_enabled;
  127. /*! \brief Limit the kinds of files we're willing to serve up */
  128. static struct {
  129. const char *ext;
  130. const char *mtype;
  131. } mimetypes[] = {
  132. { "png", "image/png" },
  133. { "xml", "text/xml" },
  134. { "jpg", "image/jpeg" },
  135. { "js", "application/x-javascript" },
  136. { "wav", "audio/x-wav" },
  137. { "mp3", "audio/mpeg" },
  138. { "svg", "image/svg+xml" },
  139. { "svgz", "image/svg+xml" },
  140. { "gif", "image/gif" },
  141. { "html", "text/html" },
  142. { "htm", "text/html" },
  143. { "css", "text/css" },
  144. { "cnf", "text/plain" },
  145. { "cfg", "text/plain" },
  146. { "bin", "application/octet-stream" },
  147. { "sbn", "application/octet-stream" },
  148. { "ld", "application/octet-stream" },
  149. };
  150. struct http_uri_redirect {
  151. AST_LIST_ENTRY(http_uri_redirect) entry;
  152. char *dest;
  153. char target[0];
  154. };
  155. static AST_RWLIST_HEAD_STATIC(uri_redirects, http_uri_redirect);
  156. static const struct ast_cfhttp_methods_text {
  157. enum ast_http_method method;
  158. const char *text;
  159. } ast_http_methods_text[] = {
  160. { AST_HTTP_UNKNOWN, "UNKNOWN" },
  161. { AST_HTTP_GET, "GET" },
  162. { AST_HTTP_POST, "POST" },
  163. { AST_HTTP_HEAD, "HEAD" },
  164. { AST_HTTP_PUT, "PUT" },
  165. { AST_HTTP_DELETE, "DELETE" },
  166. { AST_HTTP_OPTIONS, "OPTIONS" },
  167. };
  168. const char *ast_get_http_method(enum ast_http_method method)
  169. {
  170. int x;
  171. for (x = 0; x < ARRAY_LEN(ast_http_methods_text); x++) {
  172. if (ast_http_methods_text[x].method == method) {
  173. return ast_http_methods_text[x].text;
  174. }
  175. }
  176. return NULL;
  177. }
  178. const char *ast_http_ftype2mtype(const char *ftype)
  179. {
  180. int x;
  181. if (ftype) {
  182. for (x = 0; x < ARRAY_LEN(mimetypes); x++) {
  183. if (!strcasecmp(ftype, mimetypes[x].ext)) {
  184. return mimetypes[x].mtype;
  185. }
  186. }
  187. }
  188. return NULL;
  189. }
  190. uint32_t ast_http_manid_from_vars(struct ast_variable *headers)
  191. {
  192. uint32_t mngid = 0;
  193. struct ast_variable *v, *cookies;
  194. cookies = ast_http_get_cookies(headers);
  195. for (v = cookies; v; v = v->next) {
  196. if (!strcasecmp(v->name, "mansession_id")) {
  197. sscanf(v->value, "%30x", &mngid);
  198. break;
  199. }
  200. }
  201. ast_variables_destroy(cookies);
  202. return mngid;
  203. }
  204. void ast_http_prefix(char *buf, int len)
  205. {
  206. if (buf) {
  207. ast_copy_string(buf, prefix, len);
  208. }
  209. }
  210. static int static_callback(struct ast_tcptls_session_instance *ser,
  211. const struct ast_http_uri *urih, const char *uri,
  212. enum ast_http_method method, struct ast_variable *get_vars,
  213. struct ast_variable *headers)
  214. {
  215. char *path;
  216. const char *ftype;
  217. const char *mtype;
  218. char wkspace[80];
  219. struct stat st;
  220. int len;
  221. int fd;
  222. struct ast_str *http_header;
  223. struct timeval tv;
  224. struct ast_tm tm;
  225. char timebuf[80], etag[23];
  226. struct ast_variable *v;
  227. int not_modified = 0;
  228. if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
  229. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  230. return 0;
  231. }
  232. /* Yuck. I'm not really sold on this, but if you don't deliver static content it
  233. * makes your configuration substantially more challenging, but this seems like a
  234. * rather irritating feature creep on Asterisk.
  235. *
  236. * XXX: It is not clear to me what this comment means or if it is any longer
  237. * relevant. */
  238. if (ast_strlen_zero(uri)) {
  239. goto out403;
  240. }
  241. /* Disallow any funny filenames at all (checking first character only??) */
  242. if ((uri[0] < 33) || strchr("./|~@#$%^&*() \t", uri[0])) {
  243. goto out403;
  244. }
  245. if (strstr(uri, "/..")) {
  246. goto out403;
  247. }
  248. if ((ftype = strrchr(uri, '.'))) {
  249. ftype++;
  250. }
  251. if (!(mtype = ast_http_ftype2mtype(ftype))) {
  252. snprintf(wkspace, sizeof(wkspace), "text/%s", S_OR(ftype, "plain"));
  253. mtype = wkspace;
  254. }
  255. /* Cap maximum length */
  256. if ((len = strlen(uri) + strlen(ast_config_AST_DATA_DIR) + strlen("/static-http/") + 5) > 1024) {
  257. goto out403;
  258. }
  259. path = ast_alloca(len);
  260. sprintf(path, "%s/static-http/%s", ast_config_AST_DATA_DIR, uri);
  261. if (stat(path, &st)) {
  262. goto out404;
  263. }
  264. if (S_ISDIR(st.st_mode)) {
  265. goto out404;
  266. }
  267. if (strstr(path, "/private/") && !astman_is_authed(ast_http_manid_from_vars(headers))) {
  268. goto out403;
  269. }
  270. fd = open(path, O_RDONLY);
  271. if (fd < 0) {
  272. goto out403;
  273. }
  274. /* make "Etag:" http header value */
  275. snprintf(etag, sizeof(etag), "\"%ld\"", (long)st.st_mtime);
  276. /* make "Last-Modified:" http header value */
  277. tv.tv_sec = st.st_mtime;
  278. tv.tv_usec = 0;
  279. ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&tv, &tm, "GMT"));
  280. /* check received "If-None-Match" request header and Etag value for file */
  281. for (v = headers; v; v = v->next) {
  282. if (!strcasecmp(v->name, "If-None-Match")) {
  283. if (!strcasecmp(v->value, etag)) {
  284. not_modified = 1;
  285. }
  286. break;
  287. }
  288. }
  289. http_header = ast_str_create(255);
  290. if (!http_header) {
  291. ast_http_request_close_on_completion(ser);
  292. ast_http_error(ser, 500, "Server Error", "Out of memory");
  293. close(fd);
  294. return 0;
  295. }
  296. ast_str_set(&http_header, 0, "Content-type: %s\r\n"
  297. "ETag: %s\r\n"
  298. "Last-Modified: %s\r\n",
  299. mtype,
  300. etag,
  301. timebuf);
  302. /* ast_http_send() frees http_header, so we don't need to do it before returning */
  303. if (not_modified) {
  304. ast_http_send(ser, method, 304, "Not Modified", http_header, NULL, 0, 1);
  305. } else {
  306. ast_http_send(ser, method, 200, NULL, http_header, NULL, fd, 1); /* static content flag is set */
  307. }
  308. close(fd);
  309. return 0;
  310. out404:
  311. ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
  312. return 0;
  313. out403:
  314. ast_http_request_close_on_completion(ser);
  315. ast_http_error(ser, 403, "Access Denied", "You do not have permission to access the requested URL.");
  316. return 0;
  317. }
  318. static int httpstatus_callback(struct ast_tcptls_session_instance *ser,
  319. const struct ast_http_uri *urih, const char *uri,
  320. enum ast_http_method method, struct ast_variable *get_vars,
  321. struct ast_variable *headers)
  322. {
  323. struct ast_str *out;
  324. struct ast_variable *v, *cookies = NULL;
  325. if (method != AST_HTTP_GET && method != AST_HTTP_HEAD) {
  326. ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
  327. return 0;
  328. }
  329. out = ast_str_create(512);
  330. if (!out) {
  331. ast_http_request_close_on_completion(ser);
  332. ast_http_error(ser, 500, "Server Error", "Out of memory");
  333. return 0;
  334. }
  335. ast_str_append(&out, 0,
  336. "<html><title>Asterisk HTTP Status</title>\r\n"
  337. "<body bgcolor=\"#ffffff\">\r\n"
  338. "<table bgcolor=\"#f1f1f1\" align=\"center\"><tr><td bgcolor=\"#e0e0ff\" colspan=\"2\" width=\"500\">\r\n"
  339. "<h2>&nbsp;&nbsp;Asterisk&trade; HTTP Status</h2></td></tr>\r\n");
  340. ast_str_append(&out, 0, "<tr><td><i>Server</i></td><td><b>%s</b></td></tr>\r\n", http_server_name);
  341. ast_str_append(&out, 0, "<tr><td><i>Prefix</i></td><td><b>%s</b></td></tr>\r\n", prefix);
  342. if (global_http_server) {
  343. ast_str_append(&out, 0, "<tr><td><i>Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
  344. ast_sockaddr_stringify(&global_http_server->args.old_address));
  345. }
  346. if (http_tls_cfg.enabled) {
  347. ast_str_append(&out, 0, "<tr><td><i>TLS Bind Address</i></td><td><b>%s</b></td></tr>\r\n",
  348. ast_sockaddr_stringify(&https_desc.old_address));
  349. }
  350. ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  351. for (v = get_vars; v; v = v->next) {
  352. ast_str_append(&out, 0, "<tr><td><i>Submitted GET Variable '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
  353. }
  354. ast_str_append(&out, 0, "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
  355. cookies = ast_http_get_cookies(headers);
  356. for (v = cookies; v; v = v->next) {
  357. ast_str_append(&out, 0, "<tr><td><i>Cookie '%s'</i></td><td>%s</td></tr>\r\n", v->name, v->value);
  358. }
  359. ast_variables_destroy(cookies);
  360. ast_str_append(&out, 0, "</table><center><font size=\"-1\"><i>Asterisk and Digium are registered trademarks of Digium, Inc.</i></font></center></body></html>\r\n");
  361. ast_http_send(ser, method, 200, NULL, NULL, out, 0, 0);
  362. return 0;
  363. }
  364. static struct ast_http_uri status_uri = {
  365. .callback = httpstatus_callback,
  366. .description = "Asterisk HTTP General Status",
  367. .uri = "httpstatus",
  368. .has_subtree = 0,
  369. .data = NULL,
  370. .key = __FILE__,
  371. };
  372. static struct ast_http_uri static_uri = {
  373. .callback = static_callback,
  374. .description = "Asterisk HTTP Static Delivery",
  375. .uri = "static",
  376. .has_subtree = 1,
  377. .data = NULL,
  378. .key= __FILE__,
  379. };
  380. enum http_private_flags {
  381. /*! TRUE if the HTTP request has a body. */
  382. HTTP_FLAG_HAS_BODY = (1 << 0),
  383. /*! TRUE if the HTTP request body has been read. */
  384. HTTP_FLAG_BODY_READ = (1 << 1),
  385. /*! TRUE if the HTTP request must close when completed. */
  386. HTTP_FLAG_CLOSE_ON_COMPLETION = (1 << 2),
  387. };
  388. /*! HTTP tcptls worker_fn private data. */
  389. struct http_worker_private_data {
  390. /*! Body length or -1 if chunked. Valid if HTTP_FLAG_HAS_BODY is TRUE. */
  391. int body_length;
  392. /*! HTTP body tracking flags */
  393. struct ast_flags flags;
  394. };
  395. void ast_http_send(struct ast_tcptls_session_instance *ser,
  396. enum ast_http_method method, int status_code, const char *status_title,
  397. struct ast_str *http_header, struct ast_str *out, int fd,
  398. unsigned int static_content)
  399. {
  400. struct timeval now = ast_tvnow();
  401. struct ast_tm tm;
  402. char timebuf[80];
  403. char buf[256];
  404. int len;
  405. int content_length = 0;
  406. int close_connection;
  407. struct ast_str *server_header_field = ast_str_create(MAX_SERVER_NAME_LENGTH);
  408. int send_content;
  409. if (!ser || !server_header_field) {
  410. /* The connection is not open. */
  411. ast_free(http_header);
  412. ast_free(out);
  413. ast_free(server_header_field);
  414. return;
  415. }
  416. if(!ast_strlen_zero(http_server_name)) {
  417. ast_str_set(&server_header_field,
  418. 0,
  419. "Server: %s\r\n",
  420. http_server_name);
  421. }
  422. /*
  423. * We shouldn't be sending non-final status codes to this
  424. * function because we may close the connection before
  425. * returning.
  426. */
  427. ast_assert(200 <= status_code);
  428. if (session_keep_alive <= 0) {
  429. close_connection = 1;
  430. } else {
  431. struct http_worker_private_data *request;
  432. request = ser->private_data;
  433. if (!request
  434. || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)
  435. || ast_http_body_discard(ser)) {
  436. close_connection = 1;
  437. } else {
  438. close_connection = 0;
  439. }
  440. }
  441. ast_strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %H:%M:%S GMT", ast_localtime(&now, &tm, "GMT"));
  442. /* calc content length */
  443. if (out) {
  444. content_length += ast_str_strlen(out);
  445. }
  446. if (fd) {
  447. content_length += lseek(fd, 0, SEEK_END);
  448. lseek(fd, 0, SEEK_SET);
  449. }
  450. send_content = method != AST_HTTP_HEAD || status_code >= 400;
  451. /* send http header */
  452. if (ast_iostream_printf(ser->stream,
  453. "HTTP/1.1 %d %s\r\n"
  454. "%s"
  455. "Date: %s\r\n"
  456. "%s"
  457. "%s"
  458. "%s"
  459. "Content-Length: %d\r\n"
  460. "\r\n"
  461. "%s",
  462. status_code, status_title ? status_title : "OK",
  463. ast_str_buffer(server_header_field),
  464. timebuf,
  465. close_connection ? "Connection: close\r\n" : "",
  466. static_content ? "" : "Cache-Control: no-cache, no-store\r\n",
  467. http_header ? ast_str_buffer(http_header) : "",
  468. content_length,
  469. send_content && out && ast_str_strlen(out) ? ast_str_buffer(out) : ""
  470. ) <= 0) {
  471. ast_debug(1, "ast_iostream_printf() failed: %s\n", strerror(errno));
  472. close_connection = 1;
  473. } else if (send_content && fd) {
  474. /* send file content */
  475. while ((len = read(fd, buf, sizeof(buf))) > 0) {
  476. if (ast_iostream_write(ser->stream, buf, len) != len) {
  477. ast_debug(1, "ast_iostream_write() failed: %s\n", strerror(errno));
  478. close_connection = 1;
  479. break;
  480. }
  481. }
  482. }
  483. ast_free(http_header);
  484. ast_free(out);
  485. ast_free(server_header_field);
  486. if (close_connection) {
  487. ast_debug(1, "HTTP closing session. status_code:%d\n", status_code);
  488. ast_tcptls_close_session_file(ser);
  489. } else {
  490. ast_debug(1, "HTTP keeping session open. status_code:%d\n", status_code);
  491. }
  492. }
  493. void ast_http_create_response(struct ast_tcptls_session_instance *ser, int status_code,
  494. const char *status_title, struct ast_str *http_header_data, const char *text)
  495. {
  496. char server_name[MAX_SERVER_NAME_LENGTH];
  497. struct ast_str *server_address = ast_str_create(MAX_SERVER_NAME_LENGTH);
  498. struct ast_str *out = ast_str_create(INITIAL_RESPONSE_BODY_BUFFER);
  499. if (!http_header_data || !server_address || !out) {
  500. ast_free(http_header_data);
  501. ast_free(server_address);
  502. ast_free(out);
  503. if (ser) {
  504. ast_debug(1, "HTTP closing session. OOM.\n");
  505. ast_tcptls_close_session_file(ser);
  506. }
  507. return;
  508. }
  509. if(!ast_strlen_zero(http_server_name)) {
  510. ast_xml_escape(http_server_name, server_name, sizeof(server_name));
  511. ast_str_set(&server_address,
  512. 0,
  513. "<address>%s</address>\r\n",
  514. server_name);
  515. }
  516. ast_str_set(&out,
  517. 0,
  518. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
  519. "<html><head>\r\n"
  520. "<title>%d %s</title>\r\n"
  521. "</head><body>\r\n"
  522. "<h1>%s</h1>\r\n"
  523. "<p>%s</p>\r\n"
  524. "<hr />\r\n"
  525. "%s"
  526. "</body></html>\r\n",
  527. status_code,
  528. status_title,
  529. status_title,
  530. text ? text : "",
  531. ast_str_buffer(server_address));
  532. ast_free(server_address);
  533. ast_http_send(ser,
  534. AST_HTTP_UNKNOWN,
  535. status_code,
  536. status_title,
  537. http_header_data,
  538. out,
  539. 0,
  540. 0);
  541. }
  542. void ast_http_auth(struct ast_tcptls_session_instance *ser, const char *realm,
  543. const unsigned long nonce, const unsigned long opaque, int stale,
  544. const char *text)
  545. {
  546. int status_code = 401;
  547. char *status_title = "Unauthorized";
  548. struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
  549. if (http_header_data) {
  550. ast_str_set(&http_header_data,
  551. 0,
  552. "WWW-authenticate: Digest algorithm=MD5, realm=\"%s\", nonce=\"%08lx\", qop=\"auth\", opaque=\"%08lx\"%s\r\n"
  553. "Content-type: text/html\r\n",
  554. realm ? realm : "Asterisk",
  555. nonce,
  556. opaque,
  557. stale ? ", stale=true" : "");
  558. }
  559. ast_http_create_response(ser,
  560. status_code,
  561. status_title,
  562. http_header_data,
  563. text);
  564. }
  565. void ast_http_error(struct ast_tcptls_session_instance *ser, int status_code,
  566. const char *status_title, const char *text)
  567. {
  568. struct ast_str *http_header_data = ast_str_create(DEFAULT_RESPONSE_HEADER_LENGTH);
  569. if (http_header_data) {
  570. ast_str_set(&http_header_data, 0, "Content-type: text/html\r\n");
  571. }
  572. ast_http_create_response(ser,
  573. status_code,
  574. status_title,
  575. http_header_data,
  576. text);
  577. }
  578. /*!
  579. * \brief Link the new uri into the list.
  580. *
  581. * They are sorted by length of
  582. * the string, not alphabetically. Duplicate entries are not replaced,
  583. * but the insertion order (using <= and not just <) makes sure that
  584. * more recent insertions hide older ones.
  585. * On a lookup, we just scan the list and stop at the first matching entry.
  586. */
  587. int ast_http_uri_link(struct ast_http_uri *urih)
  588. {
  589. struct ast_http_uri *uri;
  590. int len = strlen(urih->uri);
  591. AST_RWLIST_WRLOCK(&uris);
  592. urih->prefix = prefix;
  593. if ( AST_RWLIST_EMPTY(&uris) || strlen(AST_RWLIST_FIRST(&uris)->uri) <= len ) {
  594. AST_RWLIST_INSERT_HEAD(&uris, urih, entry);
  595. AST_RWLIST_UNLOCK(&uris);
  596. return 0;
  597. }
  598. AST_RWLIST_TRAVERSE(&uris, uri, entry) {
  599. if (AST_RWLIST_NEXT(uri, entry) &&
  600. strlen(AST_RWLIST_NEXT(uri, entry)->uri) <= len) {
  601. AST_RWLIST_INSERT_AFTER(&uris, uri, urih, entry);
  602. AST_RWLIST_UNLOCK(&uris);
  603. return 0;
  604. }
  605. }
  606. AST_RWLIST_INSERT_TAIL(&uris, urih, entry);
  607. AST_RWLIST_UNLOCK(&uris);
  608. return 0;
  609. }
  610. void ast_http_uri_unlink(struct ast_http_uri *urih)
  611. {
  612. AST_RWLIST_WRLOCK(&uris);
  613. AST_RWLIST_REMOVE(&uris, urih, entry);
  614. AST_RWLIST_UNLOCK(&uris);
  615. }
  616. void ast_http_uri_unlink_all_with_key(const char *key)
  617. {
  618. struct ast_http_uri *urih;
  619. AST_RWLIST_WRLOCK(&uris);
  620. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&uris, urih, entry) {
  621. if (!strcmp(urih->key, key)) {
  622. AST_RWLIST_REMOVE_CURRENT(entry);
  623. if (urih->dmallocd) {
  624. ast_free(urih->data);
  625. }
  626. if (urih->mallocd) {
  627. ast_free(urih);
  628. }
  629. }
  630. }
  631. AST_RWLIST_TRAVERSE_SAFE_END;
  632. AST_RWLIST_UNLOCK(&uris);
  633. }
  634. /*!
  635. * \brief Retrieves the header with the given field name.
  636. *
  637. * \param headers Headers to search.
  638. * \param field_name Name of the header to find.
  639. * \return Associated header value.
  640. * \retval NULL if header is not present.
  641. */
  642. static const char *get_header(struct ast_variable *headers, const char *field_name)
  643. {
  644. struct ast_variable *v;
  645. for (v = headers; v; v = v->next) {
  646. if (!strcasecmp(v->name, field_name)) {
  647. return v->value;
  648. }
  649. }
  650. return NULL;
  651. }
  652. /*!
  653. * \brief Retrieves the content type specified in the "Content-Type" header.
  654. *
  655. * This function only returns the "type/subtype" and any trailing parameter is
  656. * not included.
  657. *
  658. * \note the return value is an allocated string that needs to be freed.
  659. *
  660. * \return the content type/subtype
  661. * \retval NULL if the header is not found.
  662. */
  663. static char *get_content_type(struct ast_variable *headers)
  664. {
  665. const char *content_type = get_header(headers, "Content-Type");
  666. const char *param;
  667. size_t size;
  668. if (!content_type) {
  669. return NULL;
  670. }
  671. param = strchr(content_type, ';');
  672. size = param ? param - content_type : strlen(content_type);
  673. return ast_strndup(content_type, size);
  674. }
  675. /*!
  676. * \brief Returns the value of the Content-Length header.
  677. *
  678. * \param headers HTTP headers.
  679. *
  680. * \return length Value of the Content-Length header.
  681. * \retval 0 if header is not present.
  682. * \retval -1 if header is invalid.
  683. */
  684. static int get_content_length(struct ast_variable *headers)
  685. {
  686. const char *content_length = get_header(headers, "Content-Length");
  687. int length;
  688. if (!content_length) {
  689. /* Missing content length; assume zero */
  690. return 0;
  691. }
  692. length = 0;
  693. if (sscanf(content_length, "%30d", &length) != 1) {
  694. /* Invalid Content-Length value */
  695. length = -1;
  696. }
  697. return length;
  698. }
  699. /*!
  700. * \brief Returns the value of the Transfer-Encoding header.
  701. *
  702. * \param headers HTTP headers.
  703. * \return string Value of the Transfer-Encoding header.
  704. * \retval NULL if header is not present.
  705. */
  706. static const char *get_transfer_encoding(struct ast_variable *headers)
  707. {
  708. return get_header(headers, "Transfer-Encoding");
  709. }
  710. /*!
  711. * \internal
  712. * \brief Determine if the HTTP peer wants the connection closed.
  713. *
  714. * \param headers List of HTTP headers
  715. *
  716. * \retval 0 keep connection open.
  717. * \retval -1 close connection.
  718. */
  719. static int http_check_connection_close(struct ast_variable *headers)
  720. {
  721. const char *connection = get_header(headers, "Connection");
  722. int close_connection = 0;
  723. if (connection && !strcasecmp(connection, "close")) {
  724. close_connection = -1;
  725. }
  726. return close_connection;
  727. }
  728. void ast_http_request_close_on_completion(struct ast_tcptls_session_instance *ser)
  729. {
  730. struct http_worker_private_data *request = ser->private_data;
  731. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  732. }
  733. /*!
  734. * \internal
  735. * \brief Initialize the request tracking information in case of early failure.
  736. * \since 12.4.0
  737. *
  738. * \param request Request tracking information.
  739. */
  740. static void http_request_tracking_init(struct http_worker_private_data *request)
  741. {
  742. ast_set_flags_to(&request->flags,
  743. HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
  744. /* Assume close in case request fails early */
  745. HTTP_FLAG_CLOSE_ON_COMPLETION);
  746. }
  747. /*!
  748. * \internal
  749. * \brief Setup the HTTP request tracking information.
  750. * \since 12.4.0
  751. *
  752. * \param ser HTTP TCP/TLS session object.
  753. * \param headers List of HTTP headers.
  754. *
  755. * \retval 0 on success.
  756. * \retval -1 on error.
  757. */
  758. static int http_request_tracking_setup(struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  759. {
  760. struct http_worker_private_data *request = ser->private_data;
  761. const char *transfer_encoding;
  762. ast_set_flags_to(&request->flags,
  763. HTTP_FLAG_HAS_BODY | HTTP_FLAG_BODY_READ | HTTP_FLAG_CLOSE_ON_COMPLETION,
  764. http_check_connection_close(headers) ? HTTP_FLAG_CLOSE_ON_COMPLETION : 0);
  765. transfer_encoding = get_transfer_encoding(headers);
  766. if (transfer_encoding && !strcasecmp(transfer_encoding, "chunked")) {
  767. request->body_length = -1;
  768. ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
  769. return 0;
  770. }
  771. request->body_length = get_content_length(headers);
  772. if (0 < request->body_length) {
  773. ast_set_flag(&request->flags, HTTP_FLAG_HAS_BODY);
  774. } else if (request->body_length < 0) {
  775. /* Invalid Content-Length */
  776. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  777. ast_http_error(ser, 400, "Bad Request", "Invalid Content-Length in request!");
  778. return -1;
  779. }
  780. return 0;
  781. }
  782. void ast_http_body_read_status(struct ast_tcptls_session_instance *ser, int read_success)
  783. {
  784. struct http_worker_private_data *request;
  785. request = ser->private_data;
  786. if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
  787. || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
  788. /* No body to read. */
  789. return;
  790. }
  791. ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
  792. if (!read_success) {
  793. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  794. }
  795. }
  796. /*!
  797. * \internal
  798. * \brief Read the next length bytes from the HTTP body.
  799. * \since 12.4.0
  800. *
  801. * \param ser HTTP TCP/TLS session object.
  802. * \param buf Where to put the contents reading.
  803. * \param length How much contents to read.
  804. * \param what_getting Name of the contents reading.
  805. *
  806. * \retval 0 on success.
  807. * \retval -1 on error.
  808. */
  809. static int http_body_read_contents(struct ast_tcptls_session_instance *ser, char *buf, int length, const char *what_getting)
  810. {
  811. int res;
  812. int total = 0;
  813. /* Stream is in exclusive mode so we get it all if possible. */
  814. while (total != length) {
  815. res = ast_iostream_read(ser->stream, buf + total, length - total);
  816. if (res <= 0) {
  817. break;
  818. }
  819. total += res;
  820. }
  821. if (total != length) {
  822. ast_log(LOG_WARNING, "Wrong HTTP content read. Request %s (Wanted %d, Read %d)\n",
  823. what_getting, length, res);
  824. return -1;
  825. }
  826. return 0;
  827. }
  828. /*!
  829. * \internal
  830. * \brief Read and discard the next length bytes from the HTTP body.
  831. * \since 12.4.0
  832. *
  833. * \param ser HTTP TCP/TLS session object.
  834. * \param length How much contents to discard
  835. * \param what_getting Name of the contents discarding.
  836. *
  837. * \retval 0 on success.
  838. * \retval -1 on error.
  839. */
  840. static int http_body_discard_contents(struct ast_tcptls_session_instance *ser, int length, const char *what_getting)
  841. {
  842. ssize_t res;
  843. res = ast_iostream_discard(ser->stream, length);
  844. if (res < length) {
  845. ast_log(LOG_WARNING, "Short HTTP request %s (Wanted %d but got %zd)\n",
  846. what_getting, length, res);
  847. return -1;
  848. }
  849. return 0;
  850. }
  851. /*!
  852. * \internal
  853. * \brief decode chunked mode hexadecimal value
  854. *
  855. * \param s string to decode
  856. * \param len length of string
  857. *
  858. * \return length on success.
  859. * \retval -1 on error.
  860. */
  861. static int chunked_atoh(const char *s, int len)
  862. {
  863. int value = 0;
  864. char c;
  865. if (*s < '0') {
  866. /* zero value must be 0\n not just \n */
  867. return -1;
  868. }
  869. while (len--) {
  870. c = *s++;
  871. if (c == '\x0D') {
  872. return value;
  873. }
  874. if (c == ';') {
  875. /* We have a chunk-extension that we don't care about. */
  876. while (len--) {
  877. if (*s++ == '\x0D') {
  878. return value;
  879. }
  880. }
  881. break;
  882. }
  883. value <<= 4;
  884. if (c >= '0' && c <= '9') {
  885. value += c - '0';
  886. continue;
  887. }
  888. if (c >= 'a' && c <= 'f') {
  889. value += 10 + c - 'a';
  890. continue;
  891. }
  892. if (c >= 'A' && c <= 'F') {
  893. value += 10 + c - 'A';
  894. continue;
  895. }
  896. /* invalid character */
  897. return -1;
  898. }
  899. /* end of string */
  900. return -1;
  901. }
  902. /*!
  903. * \internal
  904. * \brief Read and convert the chunked body header length.
  905. * \since 12.4.0
  906. *
  907. * \param ser HTTP TCP/TLS session object.
  908. *
  909. * \return length Size of chunk to expect.
  910. * \retval -1 on error.
  911. */
  912. static int http_body_get_chunk_length(struct ast_tcptls_session_instance *ser)
  913. {
  914. int length;
  915. char header_line[MAX_HTTP_LINE_LENGTH];
  916. /* get the line of hexadecimal giving chunk-size w/ optional chunk-extension */
  917. if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
  918. ast_log(LOG_WARNING, "Short HTTP read of chunked header\n");
  919. return -1;
  920. }
  921. length = chunked_atoh(header_line, strlen(header_line));
  922. if (length < 0) {
  923. ast_log(LOG_WARNING, "Invalid HTTP chunk size\n");
  924. return -1;
  925. }
  926. return length;
  927. }
  928. /*!
  929. * \internal
  930. * \brief Read and check the chunk contents line termination.
  931. * \since 12.4.0
  932. *
  933. * \param ser HTTP TCP/TLS session object.
  934. *
  935. * \retval 0 on success.
  936. * \retval -1 on error.
  937. */
  938. static int http_body_check_chunk_sync(struct ast_tcptls_session_instance *ser)
  939. {
  940. int res;
  941. char chunk_sync[2];
  942. /* Stay in fread until get the expected CRLF or timeout. */
  943. res = ast_iostream_read(ser->stream, chunk_sync, sizeof(chunk_sync));
  944. if (res < sizeof(chunk_sync)) {
  945. ast_log(LOG_WARNING, "Short HTTP chunk sync read (Wanted %zu)\n",
  946. sizeof(chunk_sync));
  947. return -1;
  948. }
  949. if (chunk_sync[0] != 0x0D || chunk_sync[1] != 0x0A) {
  950. ast_log(LOG_WARNING, "HTTP chunk sync bytes wrong (0x%02hhX, 0x%02hhX)\n",
  951. (unsigned char) chunk_sync[0], (unsigned char) chunk_sync[1]);
  952. return -1;
  953. }
  954. return 0;
  955. }
  956. /*!
  957. * \internal
  958. * \brief Read and discard any chunked trailer entity-header lines.
  959. * \since 12.4.0
  960. *
  961. * \param ser HTTP TCP/TLS session object.
  962. *
  963. * \retval 0 on success.
  964. * \retval -1 on error.
  965. */
  966. static int http_body_discard_chunk_trailer_headers(struct ast_tcptls_session_instance *ser)
  967. {
  968. char header_line[MAX_HTTP_LINE_LENGTH];
  969. for (;;) {
  970. if (ast_iostream_gets(ser->stream, header_line, sizeof(header_line)) <= 0) {
  971. ast_log(LOG_WARNING, "Short HTTP read of chunked trailer header\n");
  972. return -1;
  973. }
  974. /* Trim trailing whitespace */
  975. ast_trim_blanks(header_line);
  976. if (ast_strlen_zero(header_line)) {
  977. /* A blank line ends the chunked-body */
  978. break;
  979. }
  980. }
  981. return 0;
  982. }
  983. int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
  984. {
  985. struct http_worker_private_data *request;
  986. request = ser->private_data;
  987. if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)
  988. || ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
  989. /* No body to read or it has already been read. */
  990. return 0;
  991. }
  992. ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
  993. ast_debug(1, "HTTP discarding unused request body\n");
  994. ast_assert(request->body_length != 0);
  995. if (0 < request->body_length) {
  996. if (http_body_discard_contents(ser, request->body_length, "body")) {
  997. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  998. return -1;
  999. }
  1000. return 0;
  1001. }
  1002. /* parse chunked-body */
  1003. for (;;) {
  1004. int length;
  1005. length = http_body_get_chunk_length(ser);
  1006. if (length < 0) {
  1007. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1008. return -1;
  1009. }
  1010. if (length == 0) {
  1011. /* parsed last-chunk */
  1012. break;
  1013. }
  1014. if (http_body_discard_contents(ser, length, "chunk-data")
  1015. || http_body_check_chunk_sync(ser)) {
  1016. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1017. return -1;
  1018. }
  1019. }
  1020. /* Read and discard any trailer entity-header lines. */
  1021. if (http_body_discard_chunk_trailer_headers(ser)) {
  1022. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1023. return -1;
  1024. }
  1025. return 0;
  1026. }
  1027. /*!
  1028. * \brief Returns the contents (body) of the HTTP request
  1029. *
  1030. * \param return_length ptr to int that returns content length
  1031. * \param ser HTTP TCP/TLS session object
  1032. * \param headers List of HTTP headers
  1033. * \return ptr to content (zero terminated)
  1034. * \retval NULL on failure
  1035. * \note Since returned ptr is malloc'd, it should be free'd by caller
  1036. */
  1037. static char *ast_http_get_contents(int *return_length,
  1038. struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  1039. {
  1040. struct http_worker_private_data *request;
  1041. int content_length;
  1042. int bufsize;
  1043. char *buf;
  1044. request = ser->private_data;
  1045. if (!ast_test_flag(&request->flags, HTTP_FLAG_HAS_BODY)) {
  1046. /* no content - not an error */
  1047. return NULL;
  1048. }
  1049. if (ast_test_flag(&request->flags, HTTP_FLAG_BODY_READ)) {
  1050. /* Already read the body. Cannot read again. Assume no content. */
  1051. ast_assert(0);
  1052. return NULL;
  1053. }
  1054. ast_set_flag(&request->flags, HTTP_FLAG_BODY_READ);
  1055. ast_debug(2, "HTTP consuming request body\n");
  1056. ast_assert(request->body_length != 0);
  1057. if (0 < request->body_length) {
  1058. /* handle regular non-chunked content */
  1059. content_length = request->body_length;
  1060. if (content_length > MAX_CONTENT_LENGTH) {
  1061. ast_log(LOG_WARNING, "Excessively long HTTP content. (%d > %d)\n",
  1062. content_length, MAX_CONTENT_LENGTH);
  1063. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1064. errno = EFBIG;
  1065. return NULL;
  1066. }
  1067. buf = ast_malloc(content_length + 1);
  1068. if (!buf) {
  1069. /* Malloc sets ENOMEM */
  1070. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1071. return NULL;
  1072. }
  1073. if (http_body_read_contents(ser, buf, content_length, "body")) {
  1074. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1075. errno = EIO;
  1076. ast_free(buf);
  1077. return NULL;
  1078. }
  1079. buf[content_length] = 0;
  1080. *return_length = content_length;
  1081. return buf;
  1082. }
  1083. /* pre-allocate buffer */
  1084. bufsize = 250;
  1085. buf = ast_malloc(bufsize);
  1086. if (!buf) {
  1087. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1088. return NULL;
  1089. }
  1090. /* parse chunked-body */
  1091. content_length = 0;
  1092. for (;;) {
  1093. int chunk_length;
  1094. chunk_length = http_body_get_chunk_length(ser);
  1095. if (chunk_length < 0) {
  1096. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1097. errno = EIO;
  1098. ast_free(buf);
  1099. return NULL;
  1100. }
  1101. if (chunk_length == 0) {
  1102. /* parsed last-chunk */
  1103. break;
  1104. }
  1105. if (content_length + chunk_length > MAX_CONTENT_LENGTH) {
  1106. ast_log(LOG_WARNING,
  1107. "Excessively long HTTP accumulated chunked body. (%d + %d > %d)\n",
  1108. content_length, chunk_length, MAX_CONTENT_LENGTH);
  1109. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1110. errno = EFBIG;
  1111. ast_free(buf);
  1112. return NULL;
  1113. }
  1114. /* insure buffer is large enough +1 */
  1115. if (content_length + chunk_length >= bufsize) {
  1116. char *new_buf;
  1117. /* Increase bufsize until it can handle the expected data. */
  1118. do {
  1119. bufsize *= 2;
  1120. } while (content_length + chunk_length >= bufsize);
  1121. new_buf = ast_realloc(buf, bufsize);
  1122. if (!new_buf) {
  1123. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1124. ast_free(buf);
  1125. return NULL;
  1126. }
  1127. buf = new_buf;
  1128. }
  1129. if (http_body_read_contents(ser, buf + content_length, chunk_length, "chunk-data")
  1130. || http_body_check_chunk_sync(ser)) {
  1131. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1132. errno = EIO;
  1133. ast_free(buf);
  1134. return NULL;
  1135. }
  1136. content_length += chunk_length;
  1137. }
  1138. /*
  1139. * Read and discard any trailer entity-header lines
  1140. * which we don't care about.
  1141. *
  1142. * XXX In the future we may need to add the trailer headers
  1143. * to the passed in headers list rather than discarding them.
  1144. */
  1145. if (http_body_discard_chunk_trailer_headers(ser)) {
  1146. ast_set_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION);
  1147. errno = EIO;
  1148. ast_free(buf);
  1149. return NULL;
  1150. }
  1151. buf[content_length] = 0;
  1152. *return_length = content_length;
  1153. return buf;
  1154. }
  1155. struct ast_json *ast_http_get_json(
  1156. struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  1157. {
  1158. int content_length = 0;
  1159. struct ast_json *body;
  1160. RAII_VAR(char *, buf, NULL, ast_free);
  1161. RAII_VAR(char *, type, get_content_type(headers), ast_free);
  1162. /* Use errno to distinguish errors from no body */
  1163. errno = 0;
  1164. if (ast_strlen_zero(type) || strcasecmp(type, "application/json")) {
  1165. /* Content type is not JSON. Don't read the body. */
  1166. return NULL;
  1167. }
  1168. buf = ast_http_get_contents(&content_length, ser, headers);
  1169. if (!buf || !content_length) {
  1170. /*
  1171. * errno already set
  1172. * or it is not an error to have zero content
  1173. */
  1174. return NULL;
  1175. }
  1176. body = ast_json_load_buf(buf, content_length, NULL);
  1177. if (!body) {
  1178. /* Failed to parse JSON; treat as an I/O error */
  1179. errno = EIO;
  1180. return NULL;
  1181. }
  1182. return body;
  1183. }
  1184. /*
  1185. * get post variables from client Request Entity-Body, if content type is
  1186. * application/x-www-form-urlencoded
  1187. */
  1188. struct ast_variable *ast_http_get_post_vars(
  1189. struct ast_tcptls_session_instance *ser, struct ast_variable *headers)
  1190. {
  1191. int content_length = 0;
  1192. struct ast_variable *v, *post_vars=NULL, *prev = NULL;
  1193. char *var, *val;
  1194. RAII_VAR(char *, buf, NULL, ast_free);
  1195. RAII_VAR(char *, type, get_content_type(headers), ast_free);
  1196. /* Use errno to distinguish errors from no params */
  1197. errno = 0;
  1198. if (ast_strlen_zero(type) ||
  1199. strcasecmp(type, "application/x-www-form-urlencoded")) {
  1200. /* Content type is not form data. Don't read the body. */
  1201. return NULL;
  1202. }
  1203. buf = ast_http_get_contents(&content_length, ser, headers);
  1204. if (!buf || !content_length) {
  1205. /*
  1206. * errno already set
  1207. * or it is not an error to have zero content
  1208. */
  1209. return NULL;
  1210. }
  1211. while ((val = strsep(&buf, "&"))) {
  1212. var = strsep(&val, "=");
  1213. if (val) {
  1214. ast_uri_decode(val, ast_uri_http_legacy);
  1215. } else {
  1216. val = "";
  1217. }
  1218. ast_uri_decode(var, ast_uri_http_legacy);
  1219. if ((v = ast_variable_new(var, val, ""))) {
  1220. if (post_vars) {
  1221. prev->next = v;
  1222. } else {
  1223. post_vars = v;
  1224. }
  1225. prev = v;
  1226. }
  1227. }
  1228. return post_vars;
  1229. }
  1230. static int handle_uri(struct ast_tcptls_session_instance *ser, char *uri,
  1231. enum ast_http_method method, struct ast_variable *headers)
  1232. {
  1233. char *c;
  1234. int res = 0;
  1235. char *params = uri;
  1236. struct ast_http_uri *urih = NULL;
  1237. int l;
  1238. struct ast_variable *get_vars = NULL, *v, *prev = NULL;
  1239. struct http_uri_redirect *redirect;
  1240. ast_debug(2, "HTTP Request URI is %s \n", uri);
  1241. strsep(&params, "?");
  1242. /* Extract arguments from the request and store them in variables. */
  1243. if (params) {
  1244. char *var, *val;
  1245. while ((val = strsep(&params, "&"))) {
  1246. var = strsep(&val, "=");
  1247. if (val) {
  1248. ast_uri_decode(val, ast_uri_http_legacy);
  1249. } else {
  1250. val = "";
  1251. }
  1252. ast_uri_decode(var, ast_uri_http_legacy);
  1253. if ((v = ast_variable_new(var, val, ""))) {
  1254. if (get_vars) {
  1255. prev->next = v;
  1256. } else {
  1257. get_vars = v;
  1258. }
  1259. prev = v;
  1260. }
  1261. }
  1262. }
  1263. AST_RWLIST_RDLOCK(&uri_redirects);
  1264. AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry) {
  1265. if (!strcasecmp(uri, redirect->target)) {
  1266. struct ast_str *http_header = ast_str_create(128);
  1267. if (!http_header) {
  1268. ast_http_request_close_on_completion(ser);
  1269. ast_http_error(ser, 500, "Server Error", "Out of memory");
  1270. break;
  1271. }
  1272. ast_str_set(&http_header, 0, "Location: %s\r\n", redirect->dest);
  1273. ast_http_send(ser, method, 302, "Moved Temporarily", http_header, NULL, 0, 0);
  1274. break;
  1275. }
  1276. }
  1277. AST_RWLIST_UNLOCK(&uri_redirects);
  1278. if (redirect) {
  1279. goto cleanup;
  1280. }
  1281. /* We want requests to start with the (optional) prefix and '/' */
  1282. l = strlen(prefix);
  1283. if (!strncasecmp(uri, prefix, l) && uri[l] == '/') {
  1284. uri += l + 1;
  1285. /* scan registered uris to see if we match one. */
  1286. AST_RWLIST_RDLOCK(&uris);
  1287. AST_RWLIST_TRAVERSE(&uris, urih, entry) {
  1288. l = strlen(urih->uri);
  1289. c = uri + l; /* candidate */
  1290. ast_debug(2, "match request [%s] with handler [%s] len %d\n", uri, urih->uri, l);
  1291. if (strncasecmp(urih->uri, uri, l) /* no match */
  1292. || (*c && *c != '/')) { /* substring */
  1293. continue;
  1294. }
  1295. if (*c == '/') {
  1296. c++;
  1297. }
  1298. if (!*c || urih->has_subtree) {
  1299. uri = c;
  1300. break;
  1301. }
  1302. }
  1303. AST_RWLIST_UNLOCK(&uris);
  1304. }
  1305. if (urih) {
  1306. ast_debug(1, "Match made with [%s]\n", urih->uri);
  1307. if (!urih->no_decode_uri) {
  1308. ast_uri_decode(uri, ast_uri_http_legacy);
  1309. }
  1310. res = urih->callback(ser, urih, uri, method, get_vars, headers);
  1311. } else {
  1312. ast_debug(1, "Requested URI [%s] has no handler\n", uri);
  1313. ast_http_error(ser, 404, "Not Found", "The requested URL was not found on this server.");
  1314. }
  1315. cleanup:
  1316. ast_variables_destroy(get_vars);
  1317. return res;
  1318. }
  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. int ast_http_response_status_line(const char *buf, const char *version, int code)
  1429. {
  1430. int status_code;
  1431. size_t size = strlen(version);
  1432. if (strncmp(buf, version, size) || buf[size] != ' ') {
  1433. ast_log(LOG_ERROR, "HTTP version not supported - "
  1434. "expected %s\n", version);
  1435. return -1;
  1436. }
  1437. /* skip to status code (version + space) */
  1438. buf += size + 1;
  1439. if (sscanf(buf, "%d", &status_code) != 1) {
  1440. ast_log(LOG_ERROR, "Could not read HTTP status code - "
  1441. "%s\n", buf);
  1442. return -1;
  1443. }
  1444. return status_code;
  1445. }
  1446. static void remove_excess_lws(char *s)
  1447. {
  1448. char *p, *res = s;
  1449. char *buf = ast_malloc(strlen(s) + 1);
  1450. char *buf_end;
  1451. if (!buf) {
  1452. return;
  1453. }
  1454. buf_end = buf;
  1455. while (*s && *(s = ast_skip_blanks(s))) {
  1456. p = s;
  1457. s = ast_skip_nonblanks(s);
  1458. if (buf_end != buf) {
  1459. *buf_end++ = ' ';
  1460. }
  1461. memcpy(buf_end, p, s - p);
  1462. buf_end += s - p;
  1463. }
  1464. *buf_end = '\0';
  1465. /* safe since buf will always be less than or equal to res */
  1466. strcpy(res, buf);
  1467. ast_free(buf);
  1468. }
  1469. int ast_http_header_parse(char *buf, char **name, char **value)
  1470. {
  1471. ast_trim_blanks(buf);
  1472. if (ast_strlen_zero(buf)) {
  1473. return -1;
  1474. }
  1475. *value = buf;
  1476. *name = strsep(value, ":");
  1477. if (!*value) {
  1478. return 1;
  1479. }
  1480. *value = ast_skip_blanks(*value);
  1481. if (ast_strlen_zero(*value) || ast_strlen_zero(*name)) {
  1482. return 1;
  1483. }
  1484. remove_excess_lws(*value);
  1485. return 0;
  1486. }
  1487. int ast_http_header_match(const char *name, const char *expected_name,
  1488. const char *value, const char *expected_value)
  1489. {
  1490. if (strcasecmp(name, expected_name)) {
  1491. /* no value to validate if names don't match */
  1492. return 0;
  1493. }
  1494. if (strcasecmp(value, expected_value)) {
  1495. ast_log(LOG_ERROR, "Invalid header value - expected %s "
  1496. "received %s", value, expected_value);
  1497. return -1;
  1498. }
  1499. return 1;
  1500. }
  1501. int ast_http_header_match_in(const char *name, const char *expected_name,
  1502. const char *value, const char *expected_value)
  1503. {
  1504. if (strcasecmp(name, expected_name)) {
  1505. /* no value to validate if names don't match */
  1506. return 0;
  1507. }
  1508. if (!strcasestr(expected_value, value)) {
  1509. ast_log(LOG_ERROR, "Header '%s' - could not locate '%s' "
  1510. "in '%s'\n", name, value, expected_value);
  1511. return -1;
  1512. }
  1513. return 1;
  1514. }
  1515. /*! Limit the number of request headers in case the sender is being ridiculous. */
  1516. #define MAX_HTTP_REQUEST_HEADERS 100
  1517. /*!
  1518. * \internal
  1519. * \brief Read the request headers.
  1520. * \since 12.4.0
  1521. *
  1522. * \param ser HTTP TCP/TLS session object.
  1523. * \param headers Where to put the request headers list pointer.
  1524. *
  1525. * \retval 0 on success.
  1526. * \retval -1 on error.
  1527. */
  1528. static int http_request_headers_get(struct ast_tcptls_session_instance *ser, struct ast_variable **headers)
  1529. {
  1530. struct ast_variable *tail = *headers;
  1531. int remaining_headers;
  1532. char header_line[MAX_HTTP_LINE_LENGTH];
  1533. remaining_headers = MAX_HTTP_REQUEST_HEADERS;
  1534. for (;;) {
  1535. ssize_t len;
  1536. char *name;
  1537. char *value;
  1538. len = ast_iostream_gets(ser->stream, header_line, sizeof(header_line));
  1539. if (len <= 0) {
  1540. ast_http_error(ser, 400, "Bad Request", "Timeout");
  1541. return -1;
  1542. }
  1543. if (header_line[len - 1] != '\n') {
  1544. /* We didn't get a full line */
  1545. ast_http_error(ser, 400, "Bad Request",
  1546. (len == sizeof(header_line) - 1) ? "Header line too long" : "Timeout");
  1547. return -1;
  1548. }
  1549. /* Trim trailing characters */
  1550. ast_trim_blanks(header_line);
  1551. if (ast_strlen_zero(header_line)) {
  1552. /* A blank line ends the request header section. */
  1553. break;
  1554. }
  1555. value = header_line;
  1556. name = strsep(&value, ":");
  1557. if (!value) {
  1558. continue;
  1559. }
  1560. value = ast_skip_blanks(value);
  1561. if (ast_strlen_zero(value) || ast_strlen_zero(name)) {
  1562. continue;
  1563. }
  1564. ast_trim_blanks(name);
  1565. if (!remaining_headers--) {
  1566. /* Too many headers. */
  1567. ast_http_error(ser, 413, "Request Entity Too Large", "Too many headers");
  1568. return -1;
  1569. }
  1570. if (!*headers) {
  1571. *headers = ast_variable_new(name, value, __FILE__);
  1572. tail = *headers;
  1573. } else {
  1574. tail->next = ast_variable_new(name, value, __FILE__);
  1575. tail = tail->next;
  1576. }
  1577. if (!tail) {
  1578. /*
  1579. * Variable allocation failure.
  1580. * Try to make some room.
  1581. */
  1582. ast_variables_destroy(*headers);
  1583. *headers = NULL;
  1584. ast_http_error(ser, 500, "Server Error", "Out of memory");
  1585. return -1;
  1586. }
  1587. }
  1588. return 0;
  1589. }
  1590. /*!
  1591. * \internal
  1592. * \brief Process a HTTP request.
  1593. * \since 12.4.0
  1594. *
  1595. * \param ser HTTP TCP/TLS session object.
  1596. *
  1597. * \retval 0 Continue and process the next HTTP request.
  1598. * \retval -1 Fatal HTTP connection error. Force the HTTP connection closed.
  1599. */
  1600. static int httpd_process_request(struct ast_tcptls_session_instance *ser)
  1601. {
  1602. RAII_VAR(struct ast_variable *, headers, NULL, ast_variables_destroy);
  1603. char *uri;
  1604. char *method;
  1605. const char *transfer_encoding;
  1606. struct http_worker_private_data *request;
  1607. enum ast_http_method http_method = AST_HTTP_UNKNOWN;
  1608. int res;
  1609. ssize_t len;
  1610. char request_line[MAX_HTTP_LINE_LENGTH];
  1611. len = ast_iostream_gets(ser->stream, request_line, sizeof(request_line));
  1612. if (len <= 0) {
  1613. return -1;
  1614. }
  1615. /* Re-initialize the request body tracking data. */
  1616. request = ser->private_data;
  1617. http_request_tracking_init(request);
  1618. if (request_line[len - 1] != '\n') {
  1619. /* We didn't get a full line */
  1620. ast_http_error(ser, 400, "Bad Request",
  1621. (len == sizeof(request_line) - 1) ? "Request line too long" : "Timeout");
  1622. return -1;
  1623. }
  1624. /* Get method */
  1625. method = ast_skip_blanks(request_line);
  1626. uri = ast_skip_nonblanks(method);
  1627. if (*uri) {
  1628. *uri++ = '\0';
  1629. }
  1630. if (!strcasecmp(method,"GET")) {
  1631. http_method = AST_HTTP_GET;
  1632. } else if (!strcasecmp(method,"POST")) {
  1633. http_method = AST_HTTP_POST;
  1634. } else if (!strcasecmp(method,"HEAD")) {
  1635. http_method = AST_HTTP_HEAD;
  1636. } else if (!strcasecmp(method,"PUT")) {
  1637. http_method = AST_HTTP_PUT;
  1638. } else if (!strcasecmp(method,"DELETE")) {
  1639. http_method = AST_HTTP_DELETE;
  1640. } else if (!strcasecmp(method,"OPTIONS")) {
  1641. http_method = AST_HTTP_OPTIONS;
  1642. }
  1643. uri = ast_skip_blanks(uri); /* Skip white space */
  1644. if (*uri) { /* terminate at the first blank */
  1645. char *c = ast_skip_nonblanks(uri);
  1646. if (*c) {
  1647. *c = '\0';
  1648. }
  1649. } else {
  1650. ast_http_error(ser, 400, "Bad Request", "Invalid Request");
  1651. return -1;
  1652. }
  1653. if (ast_shutdown_final()) {
  1654. ast_http_error(ser, 503, "Service Unavailable", "Shutdown in progress");
  1655. return -1;
  1656. }
  1657. /* process "Request Headers" lines */
  1658. if (http_request_headers_get(ser, &headers)) {
  1659. return -1;
  1660. }
  1661. transfer_encoding = get_transfer_encoding(headers);
  1662. /* Transfer encoding defaults to identity */
  1663. if (!transfer_encoding) {
  1664. transfer_encoding = "identity";
  1665. }
  1666. /*
  1667. * RFC 2616, section 3.6, we should respond with a 501 for any transfer-
  1668. * codings we don't understand.
  1669. */
  1670. if (strcasecmp(transfer_encoding, "identity") != 0 &&
  1671. strcasecmp(transfer_encoding, "chunked") != 0) {
  1672. /* Transfer encodings not supported */
  1673. ast_http_error(ser, 501, "Unimplemented", "Unsupported Transfer-Encoding.");
  1674. return -1;
  1675. }
  1676. if (http_request_tracking_setup(ser, headers)
  1677. || handle_uri(ser, uri, http_method, headers)
  1678. || ast_test_flag(&request->flags, HTTP_FLAG_CLOSE_ON_COMPLETION)) {
  1679. res = -1;
  1680. } else {
  1681. res = 0;
  1682. }
  1683. return res;
  1684. }
  1685. static void *httpd_helper_thread(void *data)
  1686. {
  1687. struct ast_tcptls_session_instance *ser = data;
  1688. int timeout;
  1689. int arg = 1;
  1690. if (!ser) {
  1691. ao2_cleanup(ser);
  1692. return NULL;
  1693. }
  1694. if (ast_atomic_fetchadd_int(&session_count, +1) >= session_limit) {
  1695. ast_log(LOG_WARNING, "HTTP session count exceeded %d sessions.\n",
  1696. session_limit);
  1697. goto done;
  1698. }
  1699. ast_debug(1, "HTTP opening session. Top level\n");
  1700. /*
  1701. * Here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
  1702. * This is necessary to prevent delays (caused by buffering) as we
  1703. * write to the socket in bits and pieces.
  1704. */
  1705. if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
  1706. ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on HTTP connection: %s\n", strerror(errno));
  1707. }
  1708. ast_iostream_nonblock(ser->stream);
  1709. /* Setup HTTP worker private data to keep track of request body reading. */
  1710. ao2_cleanup(ser->private_data);
  1711. ser->private_data = ao2_alloc_options(sizeof(struct http_worker_private_data), NULL,
  1712. AO2_ALLOC_OPT_LOCK_NOLOCK);
  1713. if (!ser->private_data) {
  1714. ast_http_error(ser, 500, "Server Error", "Out of memory");
  1715. goto done;
  1716. }
  1717. http_request_tracking_init(ser->private_data);
  1718. /* Determine initial HTTP request wait timeout. */
  1719. timeout = session_keep_alive;
  1720. if (timeout <= 0) {
  1721. /* Persistent connections not enabled. */
  1722. timeout = session_inactivity;
  1723. }
  1724. if (timeout < MIN_INITIAL_REQUEST_TIMEOUT) {
  1725. timeout = MIN_INITIAL_REQUEST_TIMEOUT;
  1726. }
  1727. /* We can let the stream wait for data to arrive. */
  1728. ast_iostream_set_exclusive_input(ser->stream, 1);
  1729. for (;;) {
  1730. /* Wait for next potential HTTP request message. */
  1731. ast_iostream_set_timeout_idle_inactivity(ser->stream, timeout, session_inactivity);
  1732. if (httpd_process_request(ser)) {
  1733. /* Break the connection or the connection closed */
  1734. break;
  1735. }
  1736. if (!ser->stream) {
  1737. /* Web-socket or similar that took the connection */
  1738. break;
  1739. }
  1740. timeout = session_keep_alive;
  1741. if (timeout <= 0) {
  1742. /* Persistent connections not enabled. */
  1743. break;
  1744. }
  1745. }
  1746. done:
  1747. ast_atomic_fetchadd_int(&session_count, -1);
  1748. ast_debug(1, "HTTP closing session. Top level\n");
  1749. ast_tcptls_close_session_file(ser);
  1750. ao2_ref(ser, -1);
  1751. return NULL;
  1752. }
  1753. /*!
  1754. * \brief Add a new URI redirect
  1755. * The entries in the redirect list are sorted by length, just like the list
  1756. * of URI handlers.
  1757. */
  1758. static void add_redirect(const char *value)
  1759. {
  1760. char *target, *dest;
  1761. struct http_uri_redirect *redirect, *cur;
  1762. unsigned int target_len;
  1763. unsigned int total_len;
  1764. size_t dest_len;
  1765. dest = ast_strdupa(value);
  1766. dest = ast_skip_blanks(dest);
  1767. target = strsep(&dest, " ");
  1768. target = ast_skip_blanks(target);
  1769. target = strsep(&target, " "); /* trim trailing whitespace */
  1770. if (!dest) {
  1771. ast_log(LOG_WARNING, "Invalid redirect '%s'\n", value);
  1772. return;
  1773. }
  1774. target_len = strlen(target) + 1;
  1775. dest_len = strlen(dest) + 1;
  1776. total_len = sizeof(*redirect) + target_len + dest_len;
  1777. if (!(redirect = ast_calloc(1, total_len))) {
  1778. return;
  1779. }
  1780. redirect->dest = redirect->target + target_len;
  1781. strcpy(redirect->target, target);
  1782. ast_copy_string(redirect->dest, dest, dest_len);
  1783. AST_RWLIST_WRLOCK(&uri_redirects);
  1784. target_len--; /* So we can compare directly with strlen() */
  1785. if (AST_RWLIST_EMPTY(&uri_redirects)
  1786. || strlen(AST_RWLIST_FIRST(&uri_redirects)->target) <= target_len ) {
  1787. AST_RWLIST_INSERT_HEAD(&uri_redirects, redirect, entry);
  1788. AST_RWLIST_UNLOCK(&uri_redirects);
  1789. return;
  1790. }
  1791. AST_RWLIST_TRAVERSE(&uri_redirects, cur, entry) {
  1792. if (AST_RWLIST_NEXT(cur, entry)
  1793. && strlen(AST_RWLIST_NEXT(cur, entry)->target) <= target_len ) {
  1794. AST_RWLIST_INSERT_AFTER(&uri_redirects, cur, redirect, entry);
  1795. AST_RWLIST_UNLOCK(&uri_redirects);
  1796. return;
  1797. }
  1798. }
  1799. AST_RWLIST_INSERT_TAIL(&uri_redirects, redirect, entry);
  1800. AST_RWLIST_UNLOCK(&uri_redirects);
  1801. }
  1802. /*! \brief Number of HTTP server buckets */
  1803. #define HTTP_SERVER_BUCKETS 5
  1804. struct ao2_container *http_servers = NULL;
  1805. AO2_STRING_FIELD_HASH_FN(ast_http_server, address);
  1806. AO2_STRING_FIELD_CMP_FN(ast_http_server, address);
  1807. static void http_server_destroy(void *obj)
  1808. {
  1809. struct ast_http_server *server = obj;
  1810. ast_tcptls_server_stop(&server->args);
  1811. ast_verb(1, "Stopped http server '%s' listening at '%s'\n", server->name, server->address);
  1812. ast_free(server->name);
  1813. ast_free(server->address);
  1814. }
  1815. static struct ast_http_server *http_server_create(const char *name, const char *address,
  1816. const struct ast_sockaddr *addr)
  1817. {
  1818. struct ast_http_server *server;
  1819. server = ao2_alloc(sizeof(*server), http_server_destroy);
  1820. if (!server) {
  1821. ast_log(LOG_ERROR, "Unable to allocate HTTP server '%s' at address '%s'\n",
  1822. name, address);
  1823. return NULL;
  1824. }
  1825. if (!(server->address = ast_strdup(address)) || !(server->name = ast_strdup(name))) {
  1826. ast_log(LOG_ERROR, "Unable to complete setup for HTTP server '%s' at address '%s'\n",
  1827. name, address);
  1828. ao2_ref(server, -1);
  1829. return NULL;
  1830. }
  1831. server->args.accept_fd = -1;
  1832. server->args.master = AST_PTHREADT_NULL;
  1833. server->args.tls_cfg = NULL;
  1834. server->args.poll_timeout = -1;
  1835. server->args.name = server->name;
  1836. server->args.accept_fn = ast_tcptls_server_root;
  1837. server->args.worker_fn = httpd_helper_thread;
  1838. ast_sockaddr_copy(&server->args.local_address, addr);
  1839. return server;
  1840. }
  1841. static int http_server_start(struct ast_http_server *server)
  1842. {
  1843. if (server->args.accept_fd != -1) {
  1844. /* Already running */
  1845. return 0;
  1846. }
  1847. ast_tcptls_server_start(&server->args);
  1848. if (server->args.accept_fd == -1) {
  1849. ast_log(LOG_WARNING, "Failed to start HTTP server '%s' at address '%s'\n",
  1850. server->name, server->address);
  1851. return -1;
  1852. }
  1853. if (!ao2_link_flags(http_servers, server, OBJ_NOLOCK)) {
  1854. ast_log(LOG_WARNING, "Failed to link HTTP server '%s' at address '%s'\n",
  1855. server->name, server->address);
  1856. return -1;
  1857. }
  1858. ast_verb(1, "Bound HTTP server '%s' to address %s\n", server->name, server->address);
  1859. return 0;
  1860. }
  1861. /*!
  1862. * \brief Discard/Drop a HTTP server
  1863. *
  1864. * Decrements the reference to the given object, and unlinks it from the servers
  1865. * container if it's the last reference.
  1866. *
  1867. * After a server object has been added to the container this method should always
  1868. * be called to decrement the object's reference instead of the regular ao2 methods.
  1869. *
  1870. * \note NULL tolerant
  1871. *
  1872. * \param server The server object
  1873. */
  1874. static void http_server_discard(struct ast_http_server *server)
  1875. {
  1876. if (!server) {
  1877. return;
  1878. }
  1879. /*
  1880. * If only two references were on the object then the last one is from
  1881. * the servers container, so remove from container now.
  1882. */
  1883. if (ao2_ref(server, -1) == 2) {
  1884. ao2_unlink(http_servers, server);
  1885. }
  1886. }
  1887. /*!
  1888. * \brief Retrieve, or create a HTTP server object by sock address
  1889. *
  1890. * Look for, and return a matching server object by addr. If an object is not found
  1891. * then create a new one.
  1892. *
  1893. * \note This method should be called with the http_servers container already locked.
  1894. *
  1895. * \param name The name of the server
  1896. * \param addr The address to match on, or create a new object with
  1897. *
  1898. * \return a HTTP server object, or NULL on error
  1899. */
  1900. static struct ast_http_server *http_server_get_by_addr(
  1901. const char *name, const struct ast_sockaddr *addr)
  1902. {
  1903. struct ast_http_server *server;
  1904. const char *address;
  1905. address = ast_sockaddr_stringify(addr);
  1906. if (ast_strlen_zero(address)) {
  1907. return NULL;
  1908. }
  1909. server = ao2_find(http_servers, address, OBJ_KEY | OBJ_NOLOCK);
  1910. return server ?: http_server_create(name, address, addr);
  1911. }
  1912. /*!
  1913. * \brief Retrieve, or create a HTTP server object by host
  1914. *
  1915. * Resolve the given host, and then look for, and return a matching server object.
  1916. * If an object is not found then create a new one.
  1917. *
  1918. * \note This method should be called with the http_servers container already locked.
  1919. *
  1920. * \param name The name of the server
  1921. * \param host The host to resolve, and match on or create a new object with
  1922. * \param port Optional port used if one is not specified with the host (default 8088)
  1923. *
  1924. * \return a HTTP server object, or NULL on error
  1925. */
  1926. static struct ast_http_server *http_server_get_by_host(const char *name, const char *host,
  1927. uint32_t port)
  1928. {
  1929. struct ast_sockaddr *addrs = NULL;
  1930. int num_addrs;
  1931. int i;
  1932. if (!(num_addrs = ast_sockaddr_resolve(&addrs, host, 0, AST_AF_UNSPEC))) {
  1933. ast_log(LOG_WARNING, "Unable to resolve host '%s'\n", host);
  1934. return NULL;
  1935. }
  1936. if (port == 0) {
  1937. port = DEFAULT_PORT;
  1938. }
  1939. for (i = 0; i < num_addrs; ++i) {
  1940. struct ast_http_server *server;
  1941. /* Use the given port if one was not specified already */
  1942. if (!ast_sockaddr_port(&addrs[i])) {
  1943. ast_sockaddr_set_port(&addrs[i], port);
  1944. }
  1945. server = http_server_get_by_addr(name, &addrs[i]);
  1946. if (server) {
  1947. ast_free(addrs);
  1948. return server;
  1949. }
  1950. }
  1951. ast_free(addrs);
  1952. return NULL;
  1953. }
  1954. /*!
  1955. * \brief Retrieve, or create and start a HTTP server
  1956. *
  1957. * Resolve the given host, and retrieve a listening server object. If the server is
  1958. * not already listening then start it. If a replace_me parameter is given, and it
  1959. * points to a non-NULL value then that server is discarded and replaced.
  1960. *
  1961. * \param name The name of the server
  1962. * \param host The host to resolve, and match on or create a new object with
  1963. * \param port Optional port used if one is not specified with the host (default 8088)
  1964. * \param[out] replace_me Optional server to be replaced
  1965. *
  1966. * \note If replace_me is specified the returned value is always the same as what's
  1967. * passed back out in the variable.
  1968. *
  1969. * \return a HTTP server object, or NULL on error
  1970. */
  1971. static struct ast_http_server *http_server_get(const char *name, const char *host,
  1972. uint32_t port, struct ast_http_server **replace_me)
  1973. {
  1974. struct ast_http_server *server;
  1975. ao2_lock(http_servers);
  1976. server = http_server_get_by_host(name, host, port);
  1977. if (replace_me) {
  1978. /* Only replace if different */
  1979. if (*replace_me == server) {
  1980. ao2_cleanup(server);
  1981. ao2_unlock(http_servers);
  1982. return *replace_me;
  1983. }
  1984. if (*replace_me) {
  1985. http_server_discard(*replace_me);
  1986. }
  1987. *replace_me = server;
  1988. }
  1989. if (server && http_server_start(server)) {
  1990. if (replace_me) {
  1991. *replace_me = NULL;
  1992. }
  1993. ao2_ref(server, -1);
  1994. server = NULL;
  1995. }
  1996. ao2_unlock(http_servers);
  1997. return server;
  1998. }
  1999. #ifdef TEST_FRAMEWORK
  2000. struct ast_http_server *ast_http_test_server_get(const char *name, const char *host)
  2001. {
  2002. struct ast_http_server *server;
  2003. /*
  2004. * Currently multiple HTTP servers are only allowed when the TEST_FRAMEWORK
  2005. * is enabled, leaving the follow 'todos' if they become a problem or if this
  2006. * ability moves outside the TEST_FRAMEWORK.
  2007. *
  2008. * TODO: Add locking around global_http_server use. If this module is reloading
  2009. * it's possible for the global_http_server to exist here, and then become
  2010. * NULL between the check and return.
  2011. *
  2012. * TODO: Make it so 'localhost' and 'any' addresses equate.
  2013. */
  2014. if (ast_strlen_zero(host)) {
  2015. /* Use configured server if one available */
  2016. if (global_http_server) {
  2017. ast_module_ref(ast_module_info->self);
  2018. return ao2_bump(global_http_server);
  2019. }
  2020. host = "localhost:8088";
  2021. }
  2022. if (!name) {
  2023. name = "http test server";
  2024. }
  2025. server = http_server_get(name, host, 0, NULL);
  2026. if (server) {
  2027. ast_module_ref(ast_module_info->self);
  2028. }
  2029. return server;
  2030. }
  2031. void ast_http_test_server_discard(struct ast_http_server *server)
  2032. {
  2033. if (server) {
  2034. http_server_discard(server);
  2035. ast_module_unref(ast_module_info->self);
  2036. }
  2037. }
  2038. #endif
  2039. static int __ast_http_load(int reload)
  2040. {
  2041. struct ast_config *cfg;
  2042. struct ast_variable *v;
  2043. int enabled = 0;
  2044. int new_static_uri_enabled = 0;
  2045. int new_status_uri_enabled = 1; /* Default to enabled for BC */
  2046. char newprefix[MAX_PREFIX] = "";
  2047. char server_name[MAX_SERVER_NAME_LENGTH];
  2048. struct http_uri_redirect *redirect;
  2049. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  2050. uint32_t bindport = DEFAULT_PORT;
  2051. int http_tls_was_enabled = 0;
  2052. char *bindaddr = NULL;
  2053. cfg = ast_config_load2("http.conf", "http", config_flags);
  2054. if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
  2055. return 0;
  2056. }
  2057. /* Even if the http.conf hasn't been updated, the TLS certs/keys may have been */
  2058. if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  2059. if (http_tls_cfg.enabled && ast_ssl_setup(https_desc.tls_cfg)) {
  2060. ast_tcptls_server_start(&https_desc);
  2061. }
  2062. return 0;
  2063. }
  2064. http_tls_was_enabled = (reload && http_tls_cfg.enabled);
  2065. http_tls_cfg.enabled = 0;
  2066. ast_free(http_tls_cfg.certfile);
  2067. http_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
  2068. ast_free(http_tls_cfg.capath);
  2069. http_tls_cfg.capath = ast_strdup("");
  2070. ast_free(http_tls_cfg.pvtfile);
  2071. http_tls_cfg.pvtfile = ast_strdup("");
  2072. /* Apply modern intermediate settings according to the Mozilla OpSec team as of July 30th, 2015 but disable TLSv1 */
  2073. ast_set_flag(&http_tls_cfg.flags, AST_SSL_DISABLE_TLSV1 | AST_SSL_SERVER_CIPHER_ORDER);
  2074. ast_free(http_tls_cfg.cipher);
  2075. http_tls_cfg.cipher = ast_strdup("ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA");
  2076. AST_RWLIST_WRLOCK(&uri_redirects);
  2077. while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
  2078. ast_free(redirect);
  2079. }
  2080. AST_RWLIST_UNLOCK(&uri_redirects);
  2081. ast_sockaddr_setnull(&https_desc.local_address);
  2082. session_limit = DEFAULT_SESSION_LIMIT;
  2083. session_inactivity = DEFAULT_SESSION_INACTIVITY;
  2084. session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
  2085. snprintf(server_name, sizeof(server_name), "Asterisk/%s", ast_get_version());
  2086. v = ast_variable_browse(cfg, "general");
  2087. for (; v; v = v->next) {
  2088. /* read tls config options while preventing unsupported options from being set */
  2089. if (strcasecmp(v->name, "tlscafile")
  2090. && strcasecmp(v->name, "tlscapath")
  2091. && strcasecmp(v->name, "tlscadir")
  2092. && strcasecmp(v->name, "tlsverifyclient")
  2093. && strcasecmp(v->name, "tlsdontverifyserver")
  2094. && strcasecmp(v->name, "tlsclientmethod")
  2095. && strcasecmp(v->name, "sslclientmethod")
  2096. && !ast_tls_read_conf(&http_tls_cfg, &https_desc, v->name, v->value)) {
  2097. continue;
  2098. }
  2099. if (!strcasecmp(v->name, "servername")) {
  2100. if (!ast_strlen_zero(v->value)) {
  2101. ast_copy_string(server_name, v->value, sizeof(server_name));
  2102. } else {
  2103. server_name[0] = '\0';
  2104. }
  2105. } else if (!strcasecmp(v->name, "enabled")) {
  2106. enabled = ast_true(v->value);
  2107. } else if (!strcasecmp(v->name, "enablestatic") || !strcasecmp(v->name, "enable_static")) {
  2108. new_static_uri_enabled = ast_true(v->value);
  2109. } else if (!strcasecmp(v->name, "enable_status")) {
  2110. new_status_uri_enabled = ast_true(v->value);
  2111. } else if (!strcasecmp(v->name, "bindport")) {
  2112. if (ast_parse_arg(v->value, PARSE_UINT32 | PARSE_IN_RANGE | PARSE_DEFAULT,
  2113. &bindport, DEFAULT_PORT, 0, 65535)) {
  2114. ast_log(LOG_WARNING, "Invalid port %s specified. Using default port %" PRId32 "\n",
  2115. v->value, DEFAULT_PORT);
  2116. }
  2117. } else if (!strcasecmp(v->name, "bindaddr")) {
  2118. bindaddr = ast_strdupa(v->value);
  2119. } else if (!strcasecmp(v->name, "prefix")) {
  2120. if (!ast_strlen_zero(v->value)) {
  2121. newprefix[0] = '/';
  2122. ast_copy_string(newprefix + 1, v->value, sizeof(newprefix) - 1);
  2123. } else {
  2124. newprefix[0] = '\0';
  2125. }
  2126. } else if (!strcasecmp(v->name, "redirect")) {
  2127. add_redirect(v->value);
  2128. } else if (!strcasecmp(v->name, "sessionlimit")) {
  2129. if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
  2130. &session_limit, DEFAULT_SESSION_LIMIT, 1, INT_MAX)) {
  2131. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
  2132. v->name, v->value, v->lineno);
  2133. }
  2134. } else if (!strcasecmp(v->name, "session_inactivity")) {
  2135. if (ast_parse_arg(v->value, PARSE_INT32 | PARSE_DEFAULT | PARSE_IN_RANGE,
  2136. &session_inactivity, DEFAULT_SESSION_INACTIVITY, 1, INT_MAX)) {
  2137. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
  2138. v->name, v->value, v->lineno);
  2139. }
  2140. } else if (!strcasecmp(v->name, "session_keep_alive")) {
  2141. if (sscanf(v->value, "%30d", &session_keep_alive) != 1
  2142. || session_keep_alive < 0) {
  2143. session_keep_alive = DEFAULT_SESSION_KEEP_ALIVE;
  2144. ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of http.conf\n",
  2145. v->name, v->value, v->lineno);
  2146. }
  2147. } else {
  2148. ast_log(LOG_WARNING, "Ignoring unknown option '%s' in http.conf\n", v->name);
  2149. }
  2150. }
  2151. ast_config_destroy(cfg);
  2152. if (strcmp(prefix, newprefix)) {
  2153. ast_copy_string(prefix, newprefix, sizeof(prefix));
  2154. }
  2155. ast_copy_string(http_server_name, server_name, sizeof(http_server_name));
  2156. if (enabled) {
  2157. http_server_get("http server", bindaddr, bindport, &global_http_server);
  2158. } else if (global_http_server) {
  2159. http_server_discard(global_http_server);
  2160. global_http_server = NULL;
  2161. }
  2162. /* When no specific TLS bindaddr is specified, we just use
  2163. * the non-TLS bindaddress here.
  2164. */
  2165. if (global_http_server && ast_sockaddr_isnull(&https_desc.local_address) &&
  2166. global_http_server->args.accept_fd != -1) {
  2167. ast_sockaddr_copy(&https_desc.local_address, &global_http_server->args.local_address);
  2168. /* Of course, we can't use the same port though.
  2169. * Since no bind address was specified, we just use the
  2170. * default TLS port
  2171. */
  2172. ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
  2173. }
  2174. if (http_tls_was_enabled && !http_tls_cfg.enabled) {
  2175. ast_tcptls_server_stop(&https_desc);
  2176. } else if (http_tls_cfg.enabled && !ast_sockaddr_isnull(&https_desc.local_address)) {
  2177. /* We can get here either because a TLS-specific address was specified
  2178. * or because we copied the non-TLS address here. In the case where
  2179. * we read an explicit address from the config, there may have been
  2180. * no port specified, so we'll just use the default TLS port.
  2181. */
  2182. if (!ast_sockaddr_port(&https_desc.local_address)) {
  2183. ast_sockaddr_set_port(&https_desc.local_address, DEFAULT_TLS_PORT);
  2184. }
  2185. if (ast_ssl_setup(https_desc.tls_cfg)) {
  2186. ast_tcptls_server_start(&https_desc);
  2187. }
  2188. }
  2189. if (static_uri_enabled && !new_static_uri_enabled) {
  2190. ast_http_uri_unlink(&static_uri);
  2191. } else if (!static_uri_enabled && new_static_uri_enabled) {
  2192. ast_http_uri_link(&static_uri);
  2193. }
  2194. static_uri_enabled = new_static_uri_enabled;
  2195. if (status_uri_enabled && !new_status_uri_enabled) {
  2196. ast_http_uri_unlink(&status_uri);
  2197. } else if (!status_uri_enabled && new_status_uri_enabled) {
  2198. ast_http_uri_link(&status_uri);
  2199. }
  2200. status_uri_enabled = new_status_uri_enabled;
  2201. return 0;
  2202. }
  2203. static char *handle_show_http(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2204. {
  2205. struct ast_http_uri *urih;
  2206. struct http_uri_redirect *redirect;
  2207. switch (cmd) {
  2208. case CLI_INIT:
  2209. e->command = "http show status";
  2210. e->usage =
  2211. "Usage: http show status\n"
  2212. " Lists status of internal HTTP engine\n";
  2213. return NULL;
  2214. case CLI_GENERATE:
  2215. return NULL;
  2216. }
  2217. if (a->argc != 3) {
  2218. return CLI_SHOWUSAGE;
  2219. }
  2220. ast_cli(a->fd, "HTTP Server Status:\n");
  2221. ast_cli(a->fd, "Prefix: %s\n", prefix);
  2222. ast_cli(a->fd, "Server: %s\n", http_server_name);
  2223. if (!global_http_server) {
  2224. ast_cli(a->fd, "Server Disabled\n\n");
  2225. } else {
  2226. ast_cli(a->fd, "Server Enabled and Bound to %s\n\n",
  2227. ast_sockaddr_stringify(&global_http_server->args.old_address));
  2228. if (http_tls_cfg.enabled) {
  2229. ast_cli(a->fd, "HTTPS Server Enabled and Bound to %s\n\n",
  2230. ast_sockaddr_stringify(&https_desc.old_address));
  2231. }
  2232. }
  2233. ast_cli(a->fd, "Enabled URI's:\n");
  2234. AST_RWLIST_RDLOCK(&uris);
  2235. if (AST_RWLIST_EMPTY(&uris)) {
  2236. ast_cli(a->fd, "None.\n");
  2237. } else {
  2238. AST_RWLIST_TRAVERSE(&uris, urih, entry)
  2239. ast_cli(a->fd, "%s/%s%s => %s\n", prefix, urih->uri, (urih->has_subtree ? "/..." : "" ), urih->description);
  2240. }
  2241. AST_RWLIST_UNLOCK(&uris);
  2242. ast_cli(a->fd, "\nEnabled Redirects:\n");
  2243. AST_RWLIST_RDLOCK(&uri_redirects);
  2244. AST_RWLIST_TRAVERSE(&uri_redirects, redirect, entry)
  2245. ast_cli(a->fd, " %s => %s\n", redirect->target, redirect->dest);
  2246. if (AST_RWLIST_EMPTY(&uri_redirects)) {
  2247. ast_cli(a->fd, " None.\n");
  2248. }
  2249. AST_RWLIST_UNLOCK(&uri_redirects);
  2250. return CLI_SUCCESS;
  2251. }
  2252. static int reload_module(void)
  2253. {
  2254. return __ast_http_load(1);
  2255. }
  2256. static struct ast_cli_entry cli_http[] = {
  2257. AST_CLI_DEFINE(handle_show_http, "Display HTTP server status"),
  2258. };
  2259. static int unload_module(void)
  2260. {
  2261. struct http_uri_redirect *redirect;
  2262. ast_cli_unregister_multiple(cli_http, ARRAY_LEN(cli_http));
  2263. ao2_cleanup(global_http_server);
  2264. ao2_cleanup(http_servers);
  2265. if (http_tls_cfg.enabled) {
  2266. ast_tcptls_server_stop(&https_desc);
  2267. }
  2268. ast_free(http_tls_cfg.certfile);
  2269. ast_free(http_tls_cfg.capath);
  2270. ast_free(http_tls_cfg.pvtfile);
  2271. ast_free(http_tls_cfg.cipher);
  2272. if (status_uri_enabled) {
  2273. ast_http_uri_unlink(&status_uri);
  2274. }
  2275. if (static_uri_enabled) {
  2276. ast_http_uri_unlink(&static_uri);
  2277. }
  2278. AST_RWLIST_WRLOCK(&uri_redirects);
  2279. while ((redirect = AST_RWLIST_REMOVE_HEAD(&uri_redirects, entry))) {
  2280. ast_free(redirect);
  2281. }
  2282. AST_RWLIST_UNLOCK(&uri_redirects);
  2283. return 0;
  2284. }
  2285. static int load_module(void)
  2286. {
  2287. ast_cli_register_multiple(cli_http, ARRAY_LEN(cli_http));
  2288. http_servers = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
  2289. HTTP_SERVER_BUCKETS, ast_http_server_hash_fn, NULL, ast_http_server_cmp_fn);
  2290. if (!http_servers) {
  2291. return AST_MODULE_LOAD_FAILURE;
  2292. }
  2293. if (__ast_http_load(0)) {
  2294. ao2_cleanup(http_servers);
  2295. http_servers = NULL;
  2296. return AST_MODULE_LOAD_FAILURE;
  2297. }
  2298. return AST_MODULE_LOAD_SUCCESS;
  2299. }
  2300. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Built-in HTTP Server",
  2301. .support_level = AST_MODULE_SUPPORT_CORE,
  2302. .load = load_module,
  2303. .unload = unload_module,
  2304. .reload = reload_module,
  2305. .load_pri = AST_MODPRI_CORE,
  2306. .requires = "extconfig",
  2307. );