res_ari.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2012 - 2013, Digium, Inc.
  5. *
  6. * David M. Lee, II <dlee@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. /*! \file
  19. *
  20. * \brief HTTP binding for the Stasis API
  21. * \author David M. Lee, II <dlee@digium.com>
  22. *
  23. * The API itself is documented using <a
  24. * href="https://developers.helloreverb.com/swagger/">Swagger</a>, a lightweight
  25. * mechanism for documenting RESTful API's using JSON. This allows us to use <a
  26. * href="https://github.com/wordnik/swagger-ui">swagger-ui</a> to provide
  27. * executable documentation for the API, generate client bindings in different
  28. * <a href="https://github.com/asterisk/asterisk_rest_libraries">languages</a>,
  29. * and generate a lot of the boilerplate code for implementing the RESTful
  30. * bindings. The API docs live in the \c rest-api/ directory.
  31. *
  32. * The RESTful bindings are generated from the Swagger API docs using a set of
  33. * <a href="http://mustache.github.io/mustache.5.html">Mustache</a> templates.
  34. * The code generator is written in Python, and uses the Python implementation
  35. * <a href="https://github.com/defunkt/pystache">pystache</a>. Pystache has no
  36. * dependencies, and be installed easily using \c pip. Code generation code
  37. * lives in \c rest-api-templates/.
  38. *
  39. * The generated code reduces a lot of boilerplate when it comes to handling
  40. * HTTP requests. It also helps us have greater consistency in the REST API.
  41. *
  42. * The structure of the generated code is:
  43. *
  44. * - res/ari/resource_{resource}.h
  45. * - For each operation in the resouce, a generated argument structure
  46. * (holding the parsed arguments from the request) and function
  47. * declarations (to implement in res/ari/resource_{resource}.c)
  48. * - res_ari_{resource}.c
  49. * - A set of \ref stasis_rest_callback functions, which glue the two
  50. * together. They parse out path variables and request parameters to
  51. * populate a specific \c *_args which is passed to the specific request
  52. * handler (in res/ari/resource_{resource}.c)
  53. * - A tree of \ref stasis_rest_handlers for routing requests to its
  54. * \ref stasis_rest_callback
  55. *
  56. * The basic flow of an HTTP request is:
  57. *
  58. * - ast_ari_callback()
  59. * 1. Initial request validation
  60. * 2. Routes as either a doc request (ast_ari_get_docs) or API
  61. * request (ast_ari_invoke)
  62. * - ast_ari_invoke()
  63. * 1. Further request validation
  64. * 2. Routes the request through the tree of generated
  65. * \ref stasis_rest_handlers.
  66. * 3. Dispatch to the generated callback
  67. * - \c ast_ari_*_cb
  68. * 1. Populate \c *_args struct with path and get params
  69. * 2. Invoke the request handler
  70. * 3. Validates and sends response
  71. */
  72. /*** MODULEINFO
  73. <depend type="module">res_http_websocket</depend>
  74. <support_level>core</support_level>
  75. ***/
  76. /*** DOCUMENTATION
  77. <configInfo name="res_ari" language="en_US">
  78. <synopsis>HTTP binding for the Stasis API</synopsis>
  79. <configFile name="ari.conf">
  80. <configObject name="general">
  81. <synopsis>General configuration settings</synopsis>
  82. <configOption name="enabled">
  83. <synopsis>Enable/disable the ARI module</synopsis>
  84. <description>
  85. <para>This option enables or disables the ARI module.</para>
  86. <note>
  87. <para>ARI uses Asterisk's HTTP server, which must also be enabled in <filename>http.conf</filename>.</para>
  88. </note>
  89. </description>
  90. <see-also>
  91. <ref type="filename">http.conf</ref>
  92. <ref type="link">https://wiki.asterisk.org/wiki/display/AST/Asterisk+Builtin+mini-HTTP+Server</ref>
  93. </see-also>
  94. </configOption>
  95. <configOption name="websocket_write_timeout">
  96. <synopsis>The timeout (in milliseconds) to set on WebSocket connections.</synopsis>
  97. <description>
  98. <para>If a websocket connection accepts input slowly, the timeout
  99. for writes to it can be increased to keep it from being disconnected.
  100. Value is in milliseconds; default is 100 ms.</para>
  101. </description>
  102. </configOption>
  103. <configOption name="pretty">
  104. <synopsis>Responses from ARI are formatted to be human readable</synopsis>
  105. </configOption>
  106. <configOption name="auth_realm">
  107. <synopsis>Realm to use for authentication. Defaults to Asterisk REST Interface.</synopsis>
  108. </configOption>
  109. <configOption name="allowed_origins">
  110. <synopsis>Comma separated list of allowed origins, for Cross-Origin Resource Sharing. May be set to * to allow all origins.</synopsis>
  111. </configOption>
  112. </configObject>
  113. <configObject name="user">
  114. <synopsis>Per-user configuration settings</synopsis>
  115. <configOption name="type">
  116. <synopsis>Define this configuration section as a user.</synopsis>
  117. <description>
  118. <enumlist>
  119. <enum name="user"><para>Configure this section as a <replaceable>user</replaceable></para></enum>
  120. </enumlist>
  121. </description>
  122. </configOption>
  123. <configOption name="read_only">
  124. <synopsis>When set to yes, user is only authorized for read-only requests</synopsis>
  125. </configOption>
  126. <configOption name="password">
  127. <synopsis>Crypted or plaintext password (see password_format)</synopsis>
  128. </configOption>
  129. <configOption name="password_format">
  130. <synopsis>password_format may be set to plain (the default) or crypt. When set to crypt, crypt(3) is used to validate the password. A crypted password can be generated using mkpasswd -m sha-512. When set to plain, the password is in plaintext</synopsis>
  131. </configOption>
  132. </configObject>
  133. </configFile>
  134. </configInfo>
  135. ***/
  136. #include "asterisk.h"
  137. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  138. #include "ari/internal.h"
  139. #include "asterisk/ari.h"
  140. #include "asterisk/astobj2.h"
  141. #include "asterisk/module.h"
  142. #include "asterisk/paths.h"
  143. #include <string.h>
  144. #include <sys/stat.h>
  145. #include <unistd.h>
  146. /*! \brief Helper function to check if module is enabled. */
  147. static int is_enabled(void)
  148. {
  149. RAII_VAR(struct ast_ari_conf *, cfg, ast_ari_config_get(), ao2_cleanup);
  150. return cfg && cfg->general && cfg->general->enabled;
  151. }
  152. /*! Lock for \ref root_handler */
  153. static ast_mutex_t root_handler_lock;
  154. /*! Handler for root RESTful resource. */
  155. static struct stasis_rest_handlers *root_handler;
  156. /*! Pre-defined message for allocation failures. */
  157. static struct ast_json *oom_json;
  158. struct ast_json *ast_ari_oom_json(void)
  159. {
  160. return oom_json;
  161. }
  162. int ast_ari_add_handler(struct stasis_rest_handlers *handler)
  163. {
  164. RAII_VAR(struct stasis_rest_handlers *, new_handler, NULL, ao2_cleanup);
  165. size_t old_size, new_size;
  166. SCOPED_MUTEX(lock, &root_handler_lock);
  167. old_size = sizeof(*new_handler) +
  168. root_handler->num_children * sizeof(handler);
  169. new_size = old_size + sizeof(handler);
  170. new_handler = ao2_alloc(new_size, NULL);
  171. if (!new_handler) {
  172. return -1;
  173. }
  174. memcpy(new_handler, root_handler, old_size);
  175. new_handler->children[new_handler->num_children++] = handler;
  176. ao2_cleanup(root_handler);
  177. ao2_ref(new_handler, +1);
  178. root_handler = new_handler;
  179. ast_module_ref(ast_module_info->self);
  180. return 0;
  181. }
  182. int ast_ari_remove_handler(struct stasis_rest_handlers *handler)
  183. {
  184. RAII_VAR(struct stasis_rest_handlers *, new_handler, NULL, ao2_cleanup);
  185. size_t size, i, j;
  186. ast_assert(root_handler != NULL);
  187. ast_mutex_lock(&root_handler_lock);
  188. size = sizeof(*new_handler) +
  189. root_handler->num_children * sizeof(handler);
  190. new_handler = ao2_alloc(size, NULL);
  191. if (!new_handler) {
  192. return -1;
  193. }
  194. memcpy(new_handler, root_handler, sizeof(*new_handler));
  195. for (i = 0, j = 0; i < root_handler->num_children; ++i) {
  196. if (root_handler->children[i] == handler) {
  197. ast_module_unref(ast_module_info->self);
  198. continue;
  199. }
  200. new_handler->children[j++] = root_handler->children[i];
  201. }
  202. new_handler->num_children = j;
  203. ao2_cleanup(root_handler);
  204. ao2_ref(new_handler, +1);
  205. root_handler = new_handler;
  206. ast_mutex_unlock(&root_handler_lock);
  207. return 0;
  208. }
  209. static struct stasis_rest_handlers *get_root_handler(void)
  210. {
  211. SCOPED_MUTEX(lock, &root_handler_lock);
  212. ao2_ref(root_handler, +1);
  213. return root_handler;
  214. }
  215. static struct stasis_rest_handlers *root_handler_create(void)
  216. {
  217. RAII_VAR(struct stasis_rest_handlers *, handler, NULL, ao2_cleanup);
  218. handler = ao2_alloc(sizeof(*handler), NULL);
  219. if (!handler) {
  220. return NULL;
  221. }
  222. handler->path_segment = "ari";
  223. ao2_ref(handler, +1);
  224. return handler;
  225. }
  226. void ast_ari_response_error(struct ast_ari_response *response,
  227. int response_code,
  228. const char *response_text,
  229. const char *message_fmt, ...)
  230. {
  231. RAII_VAR(struct ast_json *, message, NULL, ast_json_unref);
  232. va_list ap;
  233. va_start(ap, message_fmt);
  234. message = ast_json_vstringf(message_fmt, ap);
  235. va_end(ap);
  236. response->message = ast_json_pack("{s: o}",
  237. "message", ast_json_ref(message));
  238. response->response_code = response_code;
  239. response->response_text = response_text;
  240. }
  241. void ast_ari_response_ok(struct ast_ari_response *response,
  242. struct ast_json *message)
  243. {
  244. response->message = message;
  245. response->response_code = 200;
  246. response->response_text = "OK";
  247. }
  248. void ast_ari_response_no_content(struct ast_ari_response *response)
  249. {
  250. response->message = ast_json_null();
  251. response->response_code = 204;
  252. response->response_text = "No Content";
  253. }
  254. void ast_ari_response_alloc_failed(struct ast_ari_response *response)
  255. {
  256. response->message = ast_json_ref(oom_json);
  257. response->response_code = 500;
  258. response->response_text = "Internal Server Error";
  259. }
  260. void ast_ari_response_created(struct ast_ari_response *response,
  261. const char *url, struct ast_json *message)
  262. {
  263. response->message = message;
  264. response->response_code = 201;
  265. response->response_text = "Created";
  266. ast_str_append(&response->headers, 0, "Location: %s\r\n", url);
  267. }
  268. static void add_allow_header(struct stasis_rest_handlers *handler,
  269. struct ast_ari_response *response)
  270. {
  271. enum ast_http_method m;
  272. ast_str_append(&response->headers, 0,
  273. "Allow: OPTIONS");
  274. for (m = 0; m < AST_HTTP_MAX_METHOD; ++m) {
  275. if (handler->callbacks[m] != NULL) {
  276. ast_str_append(&response->headers, 0,
  277. ",%s", ast_get_http_method(m));
  278. }
  279. }
  280. ast_str_append(&response->headers, 0, "\r\n");
  281. }
  282. static int origin_allowed(const char *origin)
  283. {
  284. RAII_VAR(struct ast_ari_conf *, cfg, ast_ari_config_get(), ao2_cleanup);
  285. char *allowed = ast_strdupa(cfg->general->allowed_origins);
  286. char *current;
  287. while ((current = strsep(&allowed, ","))) {
  288. if (!strcmp(current, "*")) {
  289. return 1;
  290. }
  291. if (!strcmp(current, origin)) {
  292. return 1;
  293. }
  294. }
  295. return 0;
  296. }
  297. #define ACR_METHOD "Access-Control-Request-Method"
  298. #define ACR_HEADERS "Access-Control-Request-Headers"
  299. #define ACA_METHODS "Access-Control-Allow-Methods"
  300. #define ACA_HEADERS "Access-Control-Allow-Headers"
  301. /*!
  302. * \brief Handle OPTIONS request, mainly for CORS preflight requests.
  303. *
  304. * Some browsers will send this prior to non-simple methods (i.e. DELETE).
  305. * See http://www.w3.org/TR/cors/ for the spec. Especially section 6.2.
  306. */
  307. static void handle_options(struct stasis_rest_handlers *handler,
  308. struct ast_variable *headers,
  309. struct ast_ari_response *response)
  310. {
  311. struct ast_variable *header;
  312. char const *acr_method = NULL;
  313. char const *acr_headers = NULL;
  314. char const *origin = NULL;
  315. RAII_VAR(struct ast_str *, allow, NULL, ast_free);
  316. enum ast_http_method m;
  317. int allowed = 0;
  318. /* Regular OPTIONS response */
  319. add_allow_header(handler, response);
  320. ast_ari_response_no_content(response);
  321. /* Parse CORS headers */
  322. for (header = headers; header != NULL; header = header->next) {
  323. if (strcmp(ACR_METHOD, header->name) == 0) {
  324. acr_method = header->value;
  325. } else if (strcmp(ACR_HEADERS, header->name) == 0) {
  326. acr_headers = header->value;
  327. } else if (strcmp("Origin", header->name) == 0) {
  328. origin = header->value;
  329. }
  330. }
  331. /* CORS 6.2, #1 - "If the Origin header is not present terminate this
  332. * set of steps."
  333. */
  334. if (origin == NULL) {
  335. return;
  336. }
  337. /* CORS 6.2, #2 - "If the value of the Origin header is not a
  338. * case-sensitive match for any of the values in list of origins do not
  339. * set any additional headers and terminate this set of steps.
  340. *
  341. * Always matching is acceptable since the list of origins can be
  342. * unbounded.
  343. *
  344. * The Origin header can only contain a single origin as the user agent
  345. * will not follow redirects."
  346. */
  347. if (!origin_allowed(origin)) {
  348. ast_log(LOG_NOTICE, "Origin header '%s' does not match an allowed origin.\n", origin);
  349. return;
  350. }
  351. /* CORS 6.2, #3 - "If there is no Access-Control-Request-Method header
  352. * or if parsing failed, do not set any additional headers and terminate
  353. * this set of steps."
  354. */
  355. if (acr_method == NULL) {
  356. return;
  357. }
  358. /* CORS 6.2, #4 - "If there are no Access-Control-Request-Headers
  359. * headers let header field-names be the empty list."
  360. */
  361. if (acr_headers == NULL) {
  362. acr_headers = "";
  363. }
  364. /* CORS 6.2, #5 - "If method is not a case-sensitive match for any of
  365. * the values in list of methods do not set any additional headers and
  366. * terminate this set of steps."
  367. */
  368. allow = ast_str_create(20);
  369. if (!allow) {
  370. ast_ari_response_alloc_failed(response);
  371. return;
  372. }
  373. /* Go ahead and build the ACA_METHODS header at the same time */
  374. for (m = 0; m < AST_HTTP_MAX_METHOD; ++m) {
  375. if (handler->callbacks[m] != NULL) {
  376. char const *m_str = ast_get_http_method(m);
  377. if (strcmp(m_str, acr_method) == 0) {
  378. allowed = 1;
  379. }
  380. ast_str_append(&allow, 0, ",%s", m_str);
  381. }
  382. }
  383. if (!allowed) {
  384. return;
  385. }
  386. /* CORS 6.2 #6 - "If any of the header field-names is not a ASCII
  387. * case-insensitive match for any of the values in list of headers do
  388. * not set any additional headers and terminate this set of steps.
  389. *
  390. * Note: Always matching is acceptable since the list of headers can be
  391. * unbounded."
  392. */
  393. /* CORS 6.2 #7 - "If the resource supports credentials add a single
  394. * Access-Control-Allow-Origin header, with the value of the Origin
  395. * header as value, and add a single Access-Control-Allow-Credentials
  396. * header with the case-sensitive string "true" as value."
  397. *
  398. * Added by process_cors_request() earlier in the request.
  399. */
  400. /* CORS 6.2 #8 - "Optionally add a single Access-Control-Max-Age
  401. * header..."
  402. */
  403. /* CORS 6.2 #9 - "Add one or more Access-Control-Allow-Methods headers
  404. * consisting of (a subset of) the list of methods."
  405. */
  406. ast_str_append(&response->headers, 0, "%s: OPTIONS%s\r\n",
  407. ACA_METHODS, ast_str_buffer(allow));
  408. /* CORS 6.2, #10 - "Add one or more Access-Control-Allow-Headers headers
  409. * consisting of (a subset of) the list of headers.
  410. *
  411. * Since the list of headers can be unbounded simply returning headers
  412. * can be enough."
  413. */
  414. if (!ast_strlen_zero(acr_headers)) {
  415. ast_str_append(&response->headers, 0, "%s: %s\r\n",
  416. ACA_HEADERS, acr_headers);
  417. }
  418. }
  419. void ast_ari_invoke(struct ast_tcptls_session_instance *ser,
  420. const char *uri, enum ast_http_method method,
  421. struct ast_variable *get_params, struct ast_variable *headers,
  422. struct ast_ari_response *response)
  423. {
  424. RAII_VAR(struct stasis_rest_handlers *, root, NULL, ao2_cleanup);
  425. struct stasis_rest_handlers *handler;
  426. RAII_VAR(struct ast_variable *, path_vars, NULL, ast_variables_destroy);
  427. char *path = ast_strdupa(uri);
  428. char *path_segment;
  429. stasis_rest_callback callback;
  430. root = handler = get_root_handler();
  431. ast_assert(root != NULL);
  432. while ((path_segment = strsep(&path, "/")) && (strlen(path_segment) > 0)) {
  433. struct stasis_rest_handlers *found_handler = NULL;
  434. int i;
  435. ast_uri_decode(path_segment, ast_uri_http_legacy);
  436. ast_debug(3, "Finding handler for %s\n", path_segment);
  437. for (i = 0; found_handler == NULL && i < handler->num_children; ++i) {
  438. struct stasis_rest_handlers *child = handler->children[i];
  439. ast_debug(3, " Checking %s\n", child->path_segment);
  440. if (child->is_wildcard) {
  441. /* Record the path variable */
  442. struct ast_variable *path_var = ast_variable_new(child->path_segment, path_segment, __FILE__);
  443. path_var->next = path_vars;
  444. path_vars = path_var;
  445. found_handler = child;
  446. } else if (strcmp(child->path_segment, path_segment) == 0) {
  447. found_handler = child;
  448. }
  449. }
  450. if (found_handler == NULL) {
  451. /* resource not found */
  452. ast_debug(3, " Handler not found\n");
  453. ast_ari_response_error(
  454. response, 404, "Not Found",
  455. "Resource not found");
  456. return;
  457. } else {
  458. ast_debug(3, " Got it!\n");
  459. handler = found_handler;
  460. }
  461. }
  462. ast_assert(handler != NULL);
  463. if (method == AST_HTTP_OPTIONS) {
  464. handle_options(handler, headers, response);
  465. return;
  466. }
  467. if (method < 0 || method >= AST_HTTP_MAX_METHOD) {
  468. add_allow_header(handler, response);
  469. ast_ari_response_error(
  470. response, 405, "Method Not Allowed",
  471. "Invalid method");
  472. return;
  473. }
  474. if (handler->ws_server && method == AST_HTTP_GET) {
  475. /* WebSocket! */
  476. ari_handle_websocket(handler->ws_server, ser, uri, method,
  477. get_params, headers);
  478. /* Since the WebSocket code handles the connection, we shouldn't
  479. * do anything else; setting no_response */
  480. response->no_response = 1;
  481. return;
  482. }
  483. callback = handler->callbacks[method];
  484. if (callback == NULL) {
  485. add_allow_header(handler, response);
  486. ast_ari_response_error(
  487. response, 405, "Method Not Allowed",
  488. "Invalid method");
  489. return;
  490. }
  491. callback(ser, get_params, path_vars, headers, response);
  492. if (response->message == NULL && response->response_code == 0) {
  493. /* Really should not happen */
  494. ast_log(LOG_ERROR, "ARI %s %s not implemented\n",
  495. ast_get_http_method(method), uri);
  496. ast_ari_response_error(
  497. response, 501, "Not Implemented",
  498. "Method not implemented");
  499. }
  500. }
  501. void ast_ari_get_docs(const char *uri, struct ast_variable *headers,
  502. struct ast_ari_response *response)
  503. {
  504. RAII_VAR(struct ast_str *, absolute_path_builder, NULL, ast_free);
  505. RAII_VAR(char *, absolute_api_dirname, NULL, ast_std_free);
  506. RAII_VAR(char *, absolute_filename, NULL, ast_std_free);
  507. struct ast_json *obj = NULL;
  508. struct ast_variable *host = NULL;
  509. struct ast_json_error error = {};
  510. struct stat file_stat;
  511. ast_debug(3, "%s(%s)\n", __func__, uri);
  512. absolute_path_builder = ast_str_create(80);
  513. if (absolute_path_builder == NULL) {
  514. ast_ari_response_alloc_failed(response);
  515. return;
  516. }
  517. /* absolute path to the rest-api directory */
  518. ast_str_append(&absolute_path_builder, 0, "%s", ast_config_AST_DATA_DIR);
  519. ast_str_append(&absolute_path_builder, 0, "/rest-api/");
  520. absolute_api_dirname = realpath(ast_str_buffer(absolute_path_builder), NULL);
  521. if (absolute_api_dirname == NULL) {
  522. ast_log(LOG_ERROR, "Error determining real directory for rest-api\n");
  523. ast_ari_response_error(
  524. response, 500, "Internal Server Error",
  525. "Cannot find rest-api directory");
  526. return;
  527. }
  528. /* absolute path to the requested file */
  529. ast_str_append(&absolute_path_builder, 0, "%s", uri);
  530. absolute_filename = realpath(ast_str_buffer(absolute_path_builder), NULL);
  531. if (absolute_filename == NULL) {
  532. switch (errno) {
  533. case ENAMETOOLONG:
  534. case ENOENT:
  535. case ENOTDIR:
  536. ast_ari_response_error(
  537. response, 404, "Not Found",
  538. "Resource not found");
  539. break;
  540. case EACCES:
  541. ast_ari_response_error(
  542. response, 403, "Forbidden",
  543. "Permission denied");
  544. break;
  545. default:
  546. ast_log(LOG_ERROR,
  547. "Error determining real path for uri '%s': %s\n",
  548. uri, strerror(errno));
  549. ast_ari_response_error(
  550. response, 500, "Internal Server Error",
  551. "Cannot find file");
  552. break;
  553. }
  554. return;
  555. }
  556. if (!ast_begins_with(absolute_filename, absolute_api_dirname)) {
  557. /* HACKERZ! */
  558. ast_log(LOG_ERROR,
  559. "Invalid attempt to access '%s' (not in %s)\n",
  560. absolute_filename, absolute_api_dirname);
  561. ast_ari_response_error(
  562. response, 404, "Not Found",
  563. "Resource not found");
  564. return;
  565. }
  566. if (stat(absolute_filename, &file_stat) == 0) {
  567. if (!(file_stat.st_mode & S_IFREG)) {
  568. /* Not a file */
  569. ast_ari_response_error(
  570. response, 403, "Forbidden",
  571. "Invalid access");
  572. return;
  573. }
  574. } else {
  575. /* Does not exist */
  576. ast_ari_response_error(
  577. response, 404, "Not Found",
  578. "Resource not found");
  579. return;
  580. }
  581. /* Load resource object from file */
  582. obj = ast_json_load_new_file(absolute_filename, &error);
  583. if (obj == NULL) {
  584. ast_log(LOG_ERROR, "Error parsing resource file: %s:%d(%d) %s\n",
  585. error.source, error.line, error.column, error.text);
  586. ast_ari_response_error(
  587. response, 500, "Internal Server Error",
  588. "Yikes! Cannot parse resource");
  589. return;
  590. }
  591. /* Update the basePath properly */
  592. if (ast_json_object_get(obj, "basePath") != NULL) {
  593. for (host = headers; host; host = host->next) {
  594. if (strcasecmp(host->name, "Host") == 0) {
  595. break;
  596. }
  597. }
  598. if (host != NULL) {
  599. ast_json_object_set(
  600. obj, "basePath",
  601. ast_json_stringf("http://%s/ari", host->value));
  602. } else {
  603. /* Without the host, we don't have the basePath */
  604. ast_json_object_del(obj, "basePath");
  605. }
  606. }
  607. ast_ari_response_ok(response, obj);
  608. }
  609. static void remove_trailing_slash(const char *uri,
  610. struct ast_ari_response *response)
  611. {
  612. char *slashless = ast_strdupa(uri);
  613. slashless[strlen(slashless) - 1] = '\0';
  614. /* While it's tempting to redirect the client to the slashless URL,
  615. * that is problematic. A 302 Found is the most appropriate response,
  616. * but most clients issue a GET on the location you give them,
  617. * regardless of the method of the original request.
  618. *
  619. * While there are some ways around this, it gets into a lot of client
  620. * specific behavior and corner cases in the HTTP standard. There's also
  621. * very little practical benefit of redirecting; only GET and HEAD can
  622. * be redirected automagically; all other requests "MUST NOT
  623. * automatically redirect the request unless it can be confirmed by the
  624. * user, since this might change the conditions under which the request
  625. * was issued."
  626. *
  627. * Given all of that, a 404 with a nice message telling them what to do
  628. * is probably our best bet.
  629. */
  630. ast_ari_response_error(response, 404, "Not Found",
  631. "ARI URLs do not end with a slash. Try /ari/%s", slashless);
  632. }
  633. /*!
  634. * \brief Handle CORS headers for simple requests.
  635. *
  636. * See http://www.w3.org/TR/cors/ for the spec. Especially section 6.1.
  637. */
  638. static void process_cors_request(struct ast_variable *headers,
  639. struct ast_ari_response *response)
  640. {
  641. char const *origin = NULL;
  642. struct ast_variable *header;
  643. /* Parse CORS headers */
  644. for (header = headers; header != NULL; header = header->next) {
  645. if (strcmp("Origin", header->name) == 0) {
  646. origin = header->value;
  647. }
  648. }
  649. /* CORS 6.1, #1 - "If the Origin header is not present terminate this
  650. * set of steps."
  651. */
  652. if (origin == NULL) {
  653. return;
  654. }
  655. /* CORS 6.1, #2 - "If the value of the Origin header is not a
  656. * case-sensitive match for any of the values in list of origins, do not
  657. * set any additional headers and terminate this set of steps.
  658. *
  659. * Note: Always matching is acceptable since the list of origins can be
  660. * unbounded."
  661. */
  662. if (!origin_allowed(origin)) {
  663. ast_log(LOG_NOTICE, "Origin header '%s' does not match an allowed origin.\n", origin);
  664. return;
  665. }
  666. /* CORS 6.1, #3 - "If the resource supports credentials add a single
  667. * Access-Control-Allow-Origin header, with the value of the Origin
  668. * header as value, and add a single Access-Control-Allow-Credentials
  669. * header with the case-sensitive string "true" as value.
  670. *
  671. * Otherwise, add a single Access-Control-Allow-Origin header, with
  672. * either the value of the Origin header or the string "*" as value."
  673. */
  674. ast_str_append(&response->headers, 0,
  675. "Access-Control-Allow-Origin: %s\r\n", origin);
  676. ast_str_append(&response->headers, 0,
  677. "Access-Control-Allow-Credentials: true\r\n");
  678. /* CORS 6.1, #4 - "If the list of exposed headers is not empty add one
  679. * or more Access-Control-Expose-Headers headers, with as values the
  680. * header field names given in the list of exposed headers."
  681. *
  682. * No exposed headers; skipping
  683. */
  684. }
  685. enum ast_json_encoding_format ast_ari_json_format(void)
  686. {
  687. RAII_VAR(struct ast_ari_conf *, cfg, NULL, ao2_cleanup);
  688. cfg = ast_ari_config_get();
  689. return cfg->general->format;
  690. }
  691. /*!
  692. * \brief Authenticate a <code>?api_key=userid:password</code>
  693. *
  694. * \param api_key API key query parameter
  695. * \return User object for the authenticated user.
  696. * \return \c NULL if authentication failed.
  697. */
  698. static struct ast_ari_conf_user *authenticate_api_key(const char *api_key)
  699. {
  700. RAII_VAR(char *, copy, NULL, ast_free);
  701. char *username;
  702. char *password;
  703. password = copy = ast_strdup(api_key);
  704. if (!copy) {
  705. return NULL;
  706. }
  707. username = strsep(&password, ":");
  708. if (!password) {
  709. ast_log(LOG_WARNING, "Invalid api_key\n");
  710. return NULL;
  711. }
  712. return ast_ari_config_validate_user(username, password);
  713. }
  714. /*!
  715. * \brief Authenticate an HTTP request.
  716. *
  717. * \param get_params GET parameters of the request.
  718. * \param header HTTP headers.
  719. * \return User object for the authenticated user.
  720. * \return \c NULL if authentication failed.
  721. */
  722. static struct ast_ari_conf_user *authenticate_user(struct ast_variable *get_params,
  723. struct ast_variable *headers)
  724. {
  725. RAII_VAR(struct ast_http_auth *, http_auth, NULL, ao2_cleanup);
  726. struct ast_variable *v;
  727. /* HTTP Basic authentication */
  728. http_auth = ast_http_get_auth(headers);
  729. if (http_auth) {
  730. return ast_ari_config_validate_user(http_auth->userid,
  731. http_auth->password);
  732. }
  733. /* ?api_key authentication */
  734. for (v = get_params; v; v = v->next) {
  735. if (strcasecmp("api_key", v->name) == 0) {
  736. return authenticate_api_key(v->value);
  737. }
  738. }
  739. return NULL;
  740. }
  741. /*!
  742. * \internal
  743. * \brief ARI HTTP handler.
  744. *
  745. * This handler takes the HTTP request and turns it into the appropriate
  746. * RESTful request (conversion to JSON, routing, etc.)
  747. *
  748. * \param ser TCP session.
  749. * \param urih URI handler.
  750. * \param uri URI requested.
  751. * \param method HTTP method.
  752. * \param get_params HTTP \c GET params.
  753. * \param headers HTTP headers.
  754. */
  755. static int ast_ari_callback(struct ast_tcptls_session_instance *ser,
  756. const struct ast_http_uri *urih,
  757. const char *uri,
  758. enum ast_http_method method,
  759. struct ast_variable *get_params,
  760. struct ast_variable *headers)
  761. {
  762. RAII_VAR(struct ast_ari_conf *, conf, NULL, ao2_cleanup);
  763. RAII_VAR(struct ast_str *, response_body, ast_str_create(256), ast_free);
  764. RAII_VAR(struct ast_ari_conf_user *, user, NULL, ao2_cleanup);
  765. struct ast_ari_response response = {};
  766. RAII_VAR(struct ast_variable *, post_vars, NULL, ast_variables_destroy);
  767. if (!response_body) {
  768. ast_http_request_close_on_completion(ser);
  769. ast_http_error(ser, 500, "Server Error", "Out of memory");
  770. return 0;
  771. }
  772. response.headers = ast_str_create(40);
  773. if (!response.headers) {
  774. ast_http_request_close_on_completion(ser);
  775. ast_http_error(ser, 500, "Server Error", "Out of memory");
  776. return 0;
  777. }
  778. conf = ast_ari_config_get();
  779. if (!conf || !conf->general) {
  780. ast_free(response.headers);
  781. ast_http_request_close_on_completion(ser);
  782. ast_http_error(ser, 500, "Server Error", "URI handler config missing");
  783. return 0;
  784. }
  785. process_cors_request(headers, &response);
  786. /* Process form data from a POST. It could be mixed with query
  787. * parameters, which seems a bit odd. But it's allowed, so that's okay
  788. * with us.
  789. */
  790. post_vars = ast_http_get_post_vars(ser, headers);
  791. if (!post_vars) {
  792. switch (errno) {
  793. case EFBIG:
  794. ast_ari_response_error(&response, 413,
  795. "Request Entity Too Large",
  796. "Request body too large");
  797. goto request_failed;
  798. case ENOMEM:
  799. ast_http_request_close_on_completion(ser);
  800. ast_ari_response_error(&response, 500,
  801. "Internal Server Error",
  802. "Out of memory");
  803. goto request_failed;
  804. case EIO:
  805. ast_ari_response_error(&response, 400,
  806. "Bad Request", "Error parsing request body");
  807. goto request_failed;
  808. }
  809. }
  810. if (get_params == NULL) {
  811. get_params = post_vars;
  812. } else if (get_params && post_vars) {
  813. /* Has both post_vars and get_params */
  814. struct ast_variable *last_var = post_vars;
  815. while (last_var->next) {
  816. last_var = last_var->next;
  817. }
  818. /* The duped get_params will get freed when post_vars gets
  819. * ast_variables_destroyed.
  820. */
  821. last_var->next = ast_variables_dup(get_params);
  822. get_params = post_vars;
  823. }
  824. user = authenticate_user(get_params, headers);
  825. if (response.response_code > 0) {
  826. /* POST parameter processing error. Do nothing. */
  827. } else if (!user) {
  828. /* Per RFC 2617, section 1.2: The 401 (Unauthorized) response
  829. * message is used by an origin server to challenge the
  830. * authorization of a user agent. This response MUST include a
  831. * WWW-Authenticate header field containing at least one
  832. * challenge applicable to the requested resource.
  833. */
  834. ast_ari_response_error(&response, 401, "Unauthorized", "Authentication required");
  835. /* Section 1.2:
  836. * realm = "realm" "=" realm-value
  837. * realm-value = quoted-string
  838. * Section 2:
  839. * challenge = "Basic" realm
  840. */
  841. ast_str_append(&response.headers, 0,
  842. "WWW-Authenticate: Basic realm=\"%s\"\r\n",
  843. conf->general->auth_realm);
  844. } else if (!ast_fully_booted) {
  845. ast_http_request_close_on_completion(ser);
  846. ast_ari_response_error(&response, 503, "Service Unavailable", "Asterisk not booted");
  847. } else if (user->read_only && method != AST_HTTP_GET && method != AST_HTTP_OPTIONS) {
  848. ast_ari_response_error(&response, 403, "Forbidden", "Write access denied");
  849. } else if (ast_ends_with(uri, "/")) {
  850. remove_trailing_slash(uri, &response);
  851. } else if (ast_begins_with(uri, "api-docs/")) {
  852. /* Serving up API docs */
  853. if (method != AST_HTTP_GET) {
  854. ast_ari_response_error(&response, 405, "Method Not Allowed", "Unsupported method");
  855. } else {
  856. /* Skip the api-docs prefix */
  857. ast_ari_get_docs(strchr(uri, '/') + 1, headers, &response);
  858. }
  859. } else {
  860. /* Other RESTful resources */
  861. ast_ari_invoke(ser, uri, method, get_params, headers,
  862. &response);
  863. }
  864. if (response.no_response) {
  865. /* The handler indicates no further response is necessary.
  866. * Probably because it already handled it */
  867. ast_free(response.headers);
  868. return 0;
  869. }
  870. request_failed:
  871. /* If you explicitly want to have no content, set message to
  872. * ast_json_null().
  873. */
  874. ast_assert(response.message != NULL);
  875. ast_assert(response.response_code > 0);
  876. /* response.message could be NULL, in which case the empty response_body
  877. * is correct
  878. */
  879. if (response.message && !ast_json_is_null(response.message)) {
  880. ast_str_append(&response.headers, 0,
  881. "Content-type: application/json\r\n");
  882. if (ast_json_dump_str_format(response.message, &response_body,
  883. conf->general->format) != 0) {
  884. /* Error encoding response */
  885. response.response_code = 500;
  886. response.response_text = "Internal Server Error";
  887. ast_str_set(&response_body, 0, "%s", "");
  888. ast_str_set(&response.headers, 0, "%s", "");
  889. }
  890. }
  891. ast_debug(3, "Examining ARI response:\n%d %s\n%s\n%s\n", response.response_code,
  892. response.response_text, ast_str_buffer(response.headers), ast_str_buffer(response_body));
  893. ast_http_send(ser, method, response.response_code,
  894. response.response_text, response.headers, response_body,
  895. 0, 0);
  896. /* ast_http_send takes ownership, so we don't have to free them */
  897. response_body = NULL;
  898. ast_json_unref(response.message);
  899. return 0;
  900. }
  901. static struct ast_http_uri http_uri = {
  902. .callback = ast_ari_callback,
  903. .description = "Asterisk RESTful API",
  904. .uri = "ari",
  905. .has_subtree = 1,
  906. .data = NULL,
  907. .key = __FILE__,
  908. .no_decode_uri = 1,
  909. };
  910. static int load_module(void)
  911. {
  912. ast_mutex_init(&root_handler_lock);
  913. /* root_handler may have been built during a declined load */
  914. if (!root_handler) {
  915. root_handler = root_handler_create();
  916. }
  917. if (!root_handler) {
  918. return AST_MODULE_LOAD_FAILURE;
  919. }
  920. /* oom_json may have been built during a declined load */
  921. if (!oom_json) {
  922. oom_json = ast_json_pack(
  923. "{s: s}", "error", "Allocation failed");
  924. }
  925. if (!oom_json) {
  926. /* Ironic */
  927. return AST_MODULE_LOAD_FAILURE;
  928. }
  929. if (ast_ari_config_init() != 0) {
  930. return AST_MODULE_LOAD_DECLINE;
  931. }
  932. if (is_enabled()) {
  933. ast_debug(3, "ARI enabled\n");
  934. ast_http_uri_link(&http_uri);
  935. } else {
  936. ast_debug(3, "ARI disabled\n");
  937. }
  938. if (ast_ari_cli_register() != 0) {
  939. return AST_MODULE_LOAD_FAILURE;
  940. }
  941. return AST_MODULE_LOAD_SUCCESS;
  942. }
  943. static int unload_module(void)
  944. {
  945. ast_ari_cli_unregister();
  946. if (is_enabled()) {
  947. ast_debug(3, "Disabling ARI\n");
  948. ast_http_uri_unlink(&http_uri);
  949. }
  950. ast_ari_config_destroy();
  951. ao2_cleanup(root_handler);
  952. root_handler = NULL;
  953. ast_mutex_destroy(&root_handler_lock);
  954. ast_json_unref(oom_json);
  955. oom_json = NULL;
  956. return 0;
  957. }
  958. static int reload_module(void)
  959. {
  960. char was_enabled = is_enabled();
  961. if (ast_ari_config_reload() != 0) {
  962. return AST_MODULE_LOAD_DECLINE;
  963. }
  964. if (was_enabled && !is_enabled()) {
  965. ast_debug(3, "Disabling ARI\n");
  966. ast_http_uri_unlink(&http_uri);
  967. } else if (!was_enabled && is_enabled()) {
  968. ast_debug(3, "Enabling ARI\n");
  969. ast_http_uri_link(&http_uri);
  970. }
  971. return AST_MODULE_LOAD_SUCCESS;
  972. }
  973. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk RESTful Interface",
  974. .support_level = AST_MODULE_SUPPORT_CORE,
  975. .load = load_module,
  976. .unload = unload_module,
  977. .reload = reload_module,
  978. .nonoptreq = "res_http_websocket",
  979. .load_pri = AST_MODPRI_APP_DEPEND,
  980. );