http.c 61 KB

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