From dcf03554a0b38806bf1fe258acc423b070533d6e Mon Sep 17 00:00:00 2001 From: "David M. Lee" Date: Wed, 3 Jul 2013 16:32:00 +0000 Subject: Shuffle RESTful URL's around. This patch moves the RESTful URL's around to more appropriate locations for release. The /stasis URL's are moved to /ari, since Asterisk REST Interface was a more appropriate name than Stasis-HTTP. (Most of the code still has stasis_http references, but they will be cleaned up after there are no more outstanding branches that would have merge conflicts with such a change). A larger change was moving the ARI events WebSocket off of the shared /ws URL to its permanent home on /ari/events. The Swagger code generator was extended to handle "upgrade: websocket" and "websocketProtocol:" attributes on an operation. The WebSocket module was modified to better handle WebSocket servers that have a single registered protocol handler. If a client connections does not specify the Sec-WebSocket-Protocol header, and the server has a single protocol handler registered, the WebSocket server will go ahead and accept the client for that subprotocol. (closes issue ASTERISK-21857) Review: https://reviewboard.asterisk.org/r/2621/ git-svn-id: https://origsvn.digium.com/svn/asterisk/trunk@393528 65c4cc65-6c06-0410-ace0-fbb531ad65f3 --- res/Makefile | 3 + res/res_http_websocket.c | 40 ++++-- res/res_http_websocket.exports.in | 4 + res/res_stasis_http.c | 67 ++++++--- res/res_stasis_http.exports.in | 1 + res/res_stasis_http_asterisk.c | 4 +- res/res_stasis_http_bridges.c | 4 +- res/res_stasis_http_channels.c | 4 +- res/res_stasis_http_endpoints.c | 4 +- res/res_stasis_http_events.c | 34 +++-- res/res_stasis_http_playback.c | 4 +- res/res_stasis_http_recordings.c | 4 +- res/res_stasis_http_sounds.c | 4 +- res/res_stasis_websocket.c | 293 -------------------------------------- res/stasis_http/ari_websockets.c | 124 ++++++++++++++++ res/stasis_http/resource_events.c | 183 ++++++++++++++++++++++-- res/stasis_http/resource_events.h | 10 +- 17 files changed, 431 insertions(+), 356 deletions(-) delete mode 100644 res/res_stasis_websocket.c create mode 100644 res/stasis_http/ari_websockets.c (limited to 'res') diff --git a/res/Makefile b/res/Makefile index 667e097e8..c69862802 100644 --- a/res/Makefile +++ b/res/Makefile @@ -80,5 +80,8 @@ clean:: $(if $(filter res_parking,$(EMBEDDED_MODS)),modules.link,res_parking.so): $(subst .c,.o,$(wildcard parking/*.c)) $(subst .c,.o,$(wildcard parking/*.c)): _ASTCFLAGS+=$(call MOD_ASTCFLAGS,res_parking) +res_stasis_http.so: stasis_http/ari_websockets.o +stasis_http/ari_websockets.o: _ASTCFLAGS+=$(call MOD_ASTCFLAGS,res_stasis_http_asterisk) + # Dependencies for res_stasis_http_*.so are generated, so they're in this file include stasis_http.make diff --git a/res/res_http_websocket.c b/res/res_http_websocket.c index 077c2126a..0726950bb 100644 --- a/res/res_http_websocket.c +++ b/res/res_http_websocket.c @@ -282,7 +282,7 @@ void AST_OPTIONAL_API_NAME(ast_websocket_ref)(struct ast_websocket *session) void AST_OPTIONAL_API_NAME(ast_websocket_unref)(struct ast_websocket *session) { - ao2_ref(session, -1); + ao2_cleanup(session); } int AST_OPTIONAL_API_NAME(ast_websocket_fd)(struct ast_websocket *session) @@ -497,6 +497,21 @@ int AST_OPTIONAL_API_NAME(ast_websocket_read)(struct ast_websocket *session, cha return 0; } +/*! + * \brief If the server has exactly one configured protocol, return it. + */ +static struct websocket_protocol *one_protocol( + struct ast_websocket_server *server) +{ + SCOPED_AO2LOCK(lock, server->protocols); + + if (ao2_container_count(server->protocols) != 1) { + return NULL; + } + + return ao2_callback(server->protocols, OBJ_NOLOCK, NULL, NULL); +} + int ast_websocket_uri_cb(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers) { struct ast_variable *v; @@ -541,11 +556,18 @@ int ast_websocket_uri_cb(struct ast_tcptls_session_instance *ser, const struct a ast_http_error(ser, 426, "Upgrade Required", NULL); return -1; } else if (ast_strlen_zero(requested_protocols)) { - ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols requested\n", - ast_sockaddr_stringify(&ser->remote_address)); - fputs("HTTP/1.1 400 Bad Request\r\n" - "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f); - return -1; + /* If there's only a single protocol registered, and the + * client doesn't specify what protocol it's using, go ahead + * and accept the connection */ + protocol_handler = one_protocol(server); + if (!protocol_handler) { + /* Multiple registered subprotocols; client must specify */ + ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols requested\n", + ast_sockaddr_stringify(&ser->remote_address)); + fputs("HTTP/1.1 400 Bad Request\r\n" + "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f); + return -1; + } } else if (key1 && key2) { /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 and * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 -- not currently supported*/ @@ -557,10 +579,8 @@ int ast_websocket_uri_cb(struct ast_tcptls_session_instance *ser, const struct a } /* Iterate through the requested protocols trying to find one that we have a handler for */ - while ((protocol = strsep(&requested_protocols, ","))) { - if ((protocol_handler = ao2_find(server->protocols, ast_strip(protocol), OBJ_KEY))) { - break; - } + while (!protocol_handler && (protocol = strsep(&requested_protocols, ","))) { + protocol_handler = ao2_find(server->protocols, ast_strip(protocol), OBJ_KEY); } /* If no protocol handler exists bump this back to the requester */ diff --git a/res/res_http_websocket.exports.in b/res/res_http_websocket.exports.in index e0ddd9570..de3d02625 100644 --- a/res/res_http_websocket.exports.in +++ b/res/res_http_websocket.exports.in @@ -13,6 +13,10 @@ LINKER_SYMBOL_PREFIX*ast_websocket_remote_address; LINKER_SYMBOL_PREFIX*ast_websocket_is_secure; LINKER_SYMBOL_PREFIX*ast_websocket_set_nonblock; + LINKER_SYMBOL_PREFIX*ast_websocket_uri_cb; + LINKER_SYMBOL_PREFIX*ast_websocket_server_create; + LINKER_SYMBOL_PREFIX*ast_websocket_server_add_protocol; + LINKER_SYMBOL_PREFIX*ast_websocket_server_remove_protocol; local: *; }; diff --git a/res/res_stasis_http.c b/res/res_stasis_http.c index 9e634aacb..fce108146 100644 --- a/res/res_stasis_http.c +++ b/res/res_stasis_http.c @@ -72,6 +72,7 @@ */ /*** MODULEINFO + res_http_websocket core ***/ @@ -211,7 +212,12 @@ static ast_mutex_t root_handler_lock; static struct stasis_rest_handlers *root_handler; /*! Pre-defined message for allocation failures. */ -static struct ast_json *alloc_failed_message; +static struct ast_json *oom_json; + +struct ast_json *ari_oom_json(void) +{ + return oom_json; +} int stasis_http_add_handler(struct stasis_rest_handlers *handler) { @@ -286,7 +292,7 @@ static struct stasis_rest_handlers *root_handler_create(void) if (!handler) { return NULL; } - handler->path_segment = "stasis"; + handler->path_segment = "ari"; ao2_ref(handler, +1); return handler; @@ -325,7 +331,7 @@ void stasis_http_response_no_content(struct stasis_http_response *response) void stasis_http_response_alloc_failed(struct stasis_http_response *response) { - response->message = ast_json_ref(alloc_failed_message); + response->message = ast_json_ref(oom_json); response->response_code = 500; response->response_text = "Internal Server Error"; } @@ -495,11 +501,10 @@ static void handle_options(struct stasis_rest_handlers *handler, } } -void stasis_http_invoke(const char *uri, - enum ast_http_method method, - struct ast_variable *get_params, - struct ast_variable *headers, - struct stasis_http_response *response) +void stasis_http_invoke(struct ast_tcptls_session_instance *ser, + const char *uri, enum ast_http_method method, + struct ast_variable *get_params, struct ast_variable *headers, + struct stasis_http_response *response) { RAII_VAR(char *, response_text, NULL, ast_free); RAII_VAR(struct stasis_rest_handlers *, root, NULL, ao2_cleanup); @@ -559,6 +564,19 @@ void stasis_http_invoke(const char *uri, return; } + if (handler->ws_server && method == AST_HTTP_GET) { + /* WebSocket! */ + struct ast_http_uri fake_urih = { + .data = handler->ws_server, + }; + ast_websocket_uri_cb(ser, &fake_urih, uri, method, get_params, + headers); + /* Since the WebSocket code handles the connection, we shouldn't + * do anything else; setting no_response */ + response->no_response = 1; + return; + } + callback = handler->callbacks[method]; if (callback == NULL) { add_allow_header(handler, response); @@ -686,7 +704,7 @@ void stasis_http_get_docs(const char *uri, struct ast_variable *headers, if (host != NULL) { ast_json_object_set( obj, "basePath", - ast_json_stringf("http://%s/stasis", host->value)); + ast_json_stringf("http://%s/ari", host->value)); } else { /* Without the host, we don't have the basePath */ ast_json_object_del(obj, "basePath"); @@ -719,7 +737,7 @@ static void remove_trailing_slash(const char *uri, * is probably our best bet. */ stasis_http_response_error(response, 404, "Not Found", - "ARI URLs do not end with a slash. Try /%s", slashless); + "ARI URLs do not end with a slash. Try /ari/%s", slashless); } /*! @@ -831,7 +849,14 @@ static int stasis_http_callback(struct ast_tcptls_session_instance *ser, } } else { /* Other RESTful resources */ - stasis_http_invoke(uri, method, get_params, headers, &response); + stasis_http_invoke(ser, uri, method, get_params, headers, + &response); + } + + if (response.no_response) { + /* The handler indicates no further response is necessary. + * Probably because it already handled it */ + return 0; } /* Leaving message unset is only allowed for 204 (No Content). @@ -873,7 +898,7 @@ static int stasis_http_callback(struct ast_tcptls_session_instance *ser, static struct ast_http_uri http_uri = { .callback = stasis_http_callback, .description = "Asterisk RESTful API", - .uri = "stasis", + .uri = "ari", .has_subtree = 1, .data = NULL, @@ -883,6 +908,14 @@ static struct ast_http_uri http_uri = { static int load_module(void) { + oom_json = ast_json_pack( + "{s: s}", "error", "AllocationFailed"); + + if (!oom_json) { + /* Ironic */ + return AST_MODULE_LOAD_FAILURE; + } + ast_mutex_init(&root_handler_lock); root_handler = root_handler_create(); @@ -905,9 +938,6 @@ static int load_module(void) return AST_MODULE_LOAD_DECLINE; } - alloc_failed_message = ast_json_pack( - "{s: s}", "message", "Allocation failed"); - if (is_enabled()) { ast_http_uri_link(&http_uri); } @@ -917,8 +947,8 @@ static int load_module(void) static int unload_module(void) { - ast_json_unref(alloc_failed_message); - alloc_failed_message = NULL; + ast_json_unref(oom_json); + oom_json = NULL; if (is_enabled()) { ast_http_uri_unlink(&http_uri); @@ -951,9 +981,10 @@ static int reload_module(void) return AST_MODULE_LOAD_SUCCESS; } -AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Stasis HTTP bindings", +AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk RESTful Interface", .load = load_module, .unload = unload_module, .reload = reload_module, + .nonoptreq = "res_stasis,res_http_websocket", .load_pri = AST_MODPRI_APP_DEPEND, ); diff --git a/res/res_stasis_http.exports.in b/res/res_stasis_http.exports.in index 726a86424..08f5065e2 100644 --- a/res/res_stasis_http.exports.in +++ b/res/res_stasis_http.exports.in @@ -1,6 +1,7 @@ { global: LINKER_SYMBOL_PREFIXstasis_http_*; + LINKER_SYMBOL_PREFIXari_*; local: *; }; diff --git a/res/res_stasis_http_asterisk.c b/res/res_stasis_http_asterisk.c index d5e8e3fde..9f4fd63e1 100644 --- a/res/res_stasis_http_asterisk.c +++ b/res/res_stasis_http_asterisk.c @@ -88,8 +88,10 @@ static struct stasis_rest_handlers asterisk = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&asterisk); + res |= stasis_http_add_handler(&asterisk); + return res; } static int unload_module(void) diff --git a/res/res_stasis_http_bridges.c b/res/res_stasis_http_bridges.c index 757af1f23..717b2f83f 100644 --- a/res/res_stasis_http_bridges.c +++ b/res/res_stasis_http_bridges.c @@ -276,8 +276,10 @@ static struct stasis_rest_handlers bridges = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&bridges); + res |= stasis_http_add_handler(&bridges); + return res; } static int unload_module(void) diff --git a/res/res_stasis_http_channels.c b/res/res_stasis_http_channels.c index 9bc4b3bcc..c865b3931 100644 --- a/res/res_stasis_http_channels.c +++ b/res/res_stasis_http_channels.c @@ -528,8 +528,10 @@ static struct stasis_rest_handlers channels = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&channels); + res |= stasis_http_add_handler(&channels); + return res; } static int unload_module(void) diff --git a/res/res_stasis_http_endpoints.c b/res/res_stasis_http_endpoints.c index 2170784eb..81cdfeb0f 100644 --- a/res/res_stasis_http_endpoints.c +++ b/res/res_stasis_http_endpoints.c @@ -139,8 +139,10 @@ static struct stasis_rest_handlers endpoints = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&endpoints); + res |= stasis_http_add_handler(&endpoints); + return res; } static int unload_module(void) diff --git a/res/res_stasis_http_events.c b/res/res_stasis_http_events.c index 800efb9b9..909c2d659 100644 --- a/res/res_stasis_http_events.c +++ b/res/res_stasis_http_events.c @@ -45,17 +45,11 @@ ASTERISK_FILE_VERSION(__FILE__, "$Revision$") #include "asterisk/stasis_app.h" #include "stasis_http/resource_events.h" -/*! - * \brief Parameter parsing callback for /events. - * \param get_params GET parameters in the HTTP request. - * \param path_vars Path variables extracted from the request. - * \param headers HTTP headers. - * \param[out] response Response to the HTTP request. - */ -static void stasis_http_event_websocket_cb( - struct ast_variable *get_params, struct ast_variable *path_vars, - struct ast_variable *headers, struct stasis_http_response *response) +static void stasis_http_event_websocket_ws_cb(struct ast_websocket *ws_session, + struct ast_variable *get_params, struct ast_variable *headers) { + RAII_VAR(struct ast_websocket *, s, ws_session, ast_websocket_unref); + RAII_VAR(struct ari_websocket_session *, session, NULL, ao2_cleanup); struct ast_event_websocket_args args = {}; struct ast_variable *i; @@ -65,14 +59,18 @@ static void stasis_http_event_websocket_cb( } else {} } - stasis_http_event_websocket(headers, &args, response); + session = ari_websocket_session_create(ws_session); + if (!session) { + ast_log(LOG_ERROR, "Failed to create ARI session\n"); + return; + } + ari_websocket_event_websocket(session, headers, &args); } /*! \brief REST handler for /api-docs/events.{format} */ static struct stasis_rest_handlers events = { .path_segment = "events", .callbacks = { - [AST_HTTP_GET] = stasis_http_event_websocket_cb, }, .num_children = 0, .children = { } @@ -80,13 +78,23 @@ static struct stasis_rest_handlers events = { static int load_module(void) { + int res = 0; + events.ws_server = ast_websocket_server_create(); + if (!events.ws_server) { + return AST_MODULE_LOAD_FAILURE; + } + res |= ast_websocket_server_add_protocol(events.ws_server, + "ari", stasis_http_event_websocket_ws_cb); stasis_app_ref(); - return stasis_http_add_handler(&events); + res |= stasis_http_add_handler(&events); + return res; } static int unload_module(void) { stasis_http_remove_handler(&events); + ao2_cleanup(events.ws_server); + events.ws_server = NULL; stasis_app_unref(); return 0; } diff --git a/res/res_stasis_http_playback.c b/res/res_stasis_http_playback.c index 31c04bac6..4608686bc 100644 --- a/res/res_stasis_http_playback.c +++ b/res/res_stasis_http_playback.c @@ -149,8 +149,10 @@ static struct stasis_rest_handlers playback = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&playback); + res |= stasis_http_add_handler(&playback); + return res; } static int unload_module(void) diff --git a/res/res_stasis_http_recordings.c b/res/res_stasis_http_recordings.c index cd421138f..7d89393bc 100644 --- a/res/res_stasis_http_recordings.c +++ b/res/res_stasis_http_recordings.c @@ -383,8 +383,10 @@ static struct stasis_rest_handlers recordings = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&recordings); + res |= stasis_http_add_handler(&recordings); + return res; } static int unload_module(void) diff --git a/res/res_stasis_http_sounds.c b/res/res_stasis_http_sounds.c index 7dce38ed1..975ca0388 100644 --- a/res/res_stasis_http_sounds.c +++ b/res/res_stasis_http_sounds.c @@ -115,8 +115,10 @@ static struct stasis_rest_handlers sounds = { static int load_module(void) { + int res = 0; stasis_app_ref(); - return stasis_http_add_handler(&sounds); + res |= stasis_http_add_handler(&sounds); + return res; } static int unload_module(void) diff --git a/res/res_stasis_websocket.c b/res/res_stasis_websocket.c deleted file mode 100644 index 5d6dcb6a9..000000000 --- a/res/res_stasis_websocket.c +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Asterisk -- An open source telephony toolkit. - * - * Copyright (C) 2012 - 2013, Digium, Inc. - * - * David M. Lee, II - * - * See http://www.asterisk.org for more information about - * the Asterisk project. Please do not directly contact - * any of the maintainers of this project for assistance; - * the project provides a web site, mailing lists and IRC - * channels for your use. - * - * This program is free software, distributed under the terms of - * the GNU General Public License Version 2. See the LICENSE file - * at the top of the source tree. - */ - -/*! \file - * - * \brief HTTP binding for the Stasis API - * - * \author David M. Lee, II - */ - -/*** MODULEINFO - res_stasis - res_http_websocket - core - ***/ - -#include "asterisk.h" - -ASTERISK_FILE_VERSION(__FILE__, "$Revision$") - -#include "asterisk/astobj2.h" -#include "asterisk/http_websocket.h" -#include "asterisk/json.h" -#include "asterisk/module.h" -#include "asterisk/stasis_app.h" -#include "asterisk/strings.h" -#include "asterisk/utils.h" - -/*! WebSocket protocol for Stasis */ -static const char * const ws_protocol = "stasis"; - -/*! Message to send when out of memory */ -static struct ast_json *oom_json; - -/*! Number of buckets for the Stasis application hash table. Remember to keep it - * a prime number! - */ -#define APPS_NUM_BUCKETS 7 - -/*! - * \internal - * \brief Helper to write a JSON object to a WebSocket. - * \param session WebSocket session. - * \param message JSON message. - * \return 0 on success. - * \return -1 on error. - */ -static int websocket_write_json(struct ast_websocket *session, - struct ast_json *message) -{ - RAII_VAR(char *, str, ast_json_dump_string(message), ast_free); - - if (str == NULL) { - ast_log(LOG_ERROR, "Failed to encode JSON object\n"); - return -1; - } - - return ast_websocket_write(session, AST_WEBSOCKET_OPCODE_TEXT, str, - strlen(str)); -} - -struct stasis_ws_session_info { - struct ast_websocket *ws_session; - struct ao2_container *websocket_apps; -}; - -static void session_dtor(void *obj) -{ -#ifdef AST_DEVMODE /* Avoid unused variable warning */ - struct stasis_ws_session_info *session = obj; -#endif - - /* session_shutdown should have been called before */ - ast_assert(session->ws_session == NULL); - ast_assert(session->websocket_apps == NULL); -} - -static struct stasis_ws_session_info *session_create( - struct ast_websocket *ws_session) -{ - RAII_VAR(struct stasis_ws_session_info *, session, NULL, ao2_cleanup); - - session = ao2_alloc(sizeof(*session), session_dtor); - - session->ws_session = ws_session; - session->websocket_apps = - ast_str_container_alloc(APPS_NUM_BUCKETS); - - if (!session->websocket_apps) { - return NULL; - } - - ao2_ref(session, +1); - return session; -} - -/*! - * \brief Explicitly shutdown a session. - * - * An explicit shutdown is necessary, since stasis-app has a reference to this - * session. We also need to be sure to null out the \c ws_session field, since - * the websocket is about to go away. - * - * \param session Session info struct. - */ -static void session_shutdown(struct stasis_ws_session_info *session) -{ - struct ao2_iterator i; - char *app; - SCOPED_AO2LOCK(lock, session); - - i = ao2_iterator_init(session->websocket_apps, 0); - while ((app = ao2_iterator_next(&i))) { - stasis_app_unregister(app); - ao2_cleanup(app); - } - ao2_iterator_destroy(&i); - ao2_cleanup(session->websocket_apps); - - session->websocket_apps = NULL; - session->ws_session = NULL; -} - -/*! - * \brief Callback handler for Stasis application messages. - */ -static void app_handler(void *data, const char *app_name, - struct ast_json *message) -{ - struct stasis_ws_session_info *session = data; - int res; - - res = ast_json_object_set(message, "application", - ast_json_string_create(app_name)); - if(res != 0) { - return; - } - - ao2_lock(session); - if (session->ws_session) { - websocket_write_json(session->ws_session, message); - } - ao2_unlock(session); -} - -/*! - * \brief Register for all of the apps given. - * \param session Session info struct. - * \param app_list Comma seperated list of app names to register. - */ -static int session_register_apps(struct stasis_ws_session_info *session, - const char *app_list) -{ - RAII_VAR(char *, to_free, NULL, ast_free); - char *apps, *app_name; - SCOPED_AO2LOCK(lock, session); - - ast_assert(session->ws_session != NULL); - ast_assert(session->websocket_apps != NULL); - - to_free = apps = ast_strdup(app_list); - if (!apps) { - websocket_write_json(session->ws_session, oom_json); - return -1; - } - while ((app_name = strsep(&apps, ","))) { - if (ast_str_container_add(session->websocket_apps, app_name)) { - websocket_write_json(session->ws_session, oom_json); - return -1; - } - - stasis_app_register(app_name, app_handler, session); - } - return 0; -} - -static void websocket_callback(struct ast_websocket *ws_session, - struct ast_variable *parameters, - struct ast_variable *headers) -{ - RAII_VAR(struct stasis_ws_session_info *, stasis_session, NULL, ao2_cleanup); - struct ast_variable *param = NULL; - int res; - - ast_debug(3, "Stasis web socket connection\n"); - - if (ast_websocket_set_nonblock(ws_session) != 0) { - ast_log(LOG_ERROR, - "Stasis web socket failed to set nonblock; closing\n"); - goto end; - } - - stasis_session = session_create(ws_session); - - if (!stasis_session) { - websocket_write_json(ws_session, oom_json); - goto end; - } - - for (param = parameters; param; param = param->next) { - if (strcmp(param->name, "app") == 0) { - int ret = session_register_apps( - stasis_session, param->value); - if (ret != 0) { - goto end; - } - } - } - - if (ao2_container_count(stasis_session->websocket_apps) == 0) { - RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref); - - msg = ast_json_pack("{s: s, s: [s]}", - "error", "MissingParams", - "params", "app"); - if (msg) { - websocket_write_json(ws_session, msg); - } - - goto end; - } - - while ((res = ast_wait_for_input(ast_websocket_fd(ws_session), -1)) > 0) { - char *payload; - uint64_t payload_len; - enum ast_websocket_opcode opcode; - int fragmented; - int read = ast_websocket_read(ws_session, &payload, &payload_len, - &opcode, &fragmented); - - if (read) { - ast_log(LOG_ERROR, - "Stasis WebSocket read error; closing\n"); - break; - } - - if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) { - break; - } - } - -end: - session_shutdown(stasis_session); - ast_websocket_unref(ws_session); -} - -static int load_module(void) -{ - int r = 0; - - stasis_app_ref(); - oom_json = ast_json_pack("{s: s}", - "error", "OutOfMemory"); - if (!oom_json) { - /* ironic */ - return AST_MODULE_LOAD_FAILURE; - } - r |= ast_websocket_add_protocol(ws_protocol, websocket_callback); - return r; -} - -static int unload_module(void) -{ - int r = 0; - - stasis_app_unref(); - ast_json_unref(oom_json); - oom_json = NULL; - r |= ast_websocket_remove_protocol(ws_protocol, websocket_callback); - return r; -} - -AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Stasis HTTP bindings", - .load = load_module, - .unload = unload_module, - .nonoptreq = "res_stasis,res_http_websocket", - .load_pri = AST_MODPRI_APP_DEPEND, - ); diff --git a/res/stasis_http/ari_websockets.c b/res/stasis_http/ari_websockets.c new file mode 100644 index 000000000..e6b316b57 --- /dev/null +++ b/res/stasis_http/ari_websockets.c @@ -0,0 +1,124 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 2013, Digium, Inc. + * + * David M. Lee, II + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +#include "asterisk.h" + +ASTERISK_FILE_VERSION(__FILE__, "$Revision$") + +#include "asterisk/astobj2.h" +#include "asterisk/stasis_http.h" + +/*! \file + * + * \brief WebSocket support for RESTful API's. + * \author David M. Lee, II + */ + +struct ari_websocket_session { + struct ast_websocket *ws_session; +}; + +static void websocket_session_dtor(void *obj) +{ + struct ari_websocket_session *session = obj; + + ast_websocket_unref(session->ws_session); + session->ws_session = NULL; +} + +struct ari_websocket_session *ari_websocket_session_create( + struct ast_websocket *ws_session) +{ + RAII_VAR(struct ari_websocket_session *, session, NULL, ao2_cleanup); + + if (ws_session == NULL) { + return NULL; + } + + if (ast_websocket_set_nonblock(ws_session) != 0) { + ast_log(LOG_ERROR, + "Stasis web socket failed to set nonblock; closing\n"); + return NULL; + } + + session = ao2_alloc(sizeof(*session), websocket_session_dtor); + if (!session) { + return NULL; + } + + ao2_ref(ws_session, +1); + session->ws_session = ws_session; + + ao2_ref(session, +1); + return session; +} + +struct ast_json *ari_websocket_session_read( + struct ari_websocket_session *session) +{ + RAII_VAR(struct ast_json *, message, NULL, ast_json_unref); + + while (!message) { + int res; + char *payload; + uint64_t payload_len; + enum ast_websocket_opcode opcode; + int fragmented; + + res = ast_wait_for_input( + ast_websocket_fd(session->ws_session), -1); + + if (res <= 0) { + return NULL; + } + + res = ast_websocket_read(session->ws_session, &payload, + &payload_len, &opcode, &fragmented); + + if (res != 0) { + return NULL; + } + + switch (opcode) { + case AST_WEBSOCKET_OPCODE_CLOSE: + return NULL; + case AST_WEBSOCKET_OPCODE_TEXT: + message = ast_json_load_buf(payload, payload_len, NULL); + break; + default: + /* Ignore all other message types */ + break; + } + } + + return ast_json_ref(message); +} + +int ari_websocket_session_write(struct ari_websocket_session *session, + struct ast_json *message) +{ + RAII_VAR(char *, str, ast_json_dump_string(message), ast_free); + + if (str == NULL) { + ast_log(LOG_ERROR, "Failed to encode JSON object\n"); + return -1; + } + + return ast_websocket_write(session->ws_session, + AST_WEBSOCKET_OPCODE_TEXT, str, strlen(str)); +} diff --git a/res/stasis_http/resource_events.c b/res/stasis_http/resource_events.c index 34563fe6e..0412fd79c 100644 --- a/res/stasis_http/resource_events.c +++ b/res/stasis_http/resource_events.c @@ -1,4 +1,4 @@ -/* -*- C -*- +/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 2012 - 2013, Digium, Inc. @@ -18,23 +18,188 @@ /*! \file * - * \brief Implementation for stasis-http stubs. + * \brief /api-docs/events.{format} implementation- WebSocket resource * * \author David M. Lee, II */ -/*** MODULEINFO - core - ***/ - #include "asterisk.h" ASTERISK_FILE_VERSION(__FILE__, "$Revision$") +#include "asterisk/astobj2.h" +#include "asterisk/stasis_app.h" #include "resource_events.h" -void stasis_http_event_websocket(struct ast_variable *headers, struct ast_event_websocket_args *args, struct stasis_http_response *response) +/*! Number of buckets for the Stasis application hash table. Remember to keep it + * a prime number! + */ +#define APPS_NUM_BUCKETS 7 + +/*! \brief A connection to the event WebSocket */ +struct event_session { + struct ari_websocket_session *ws_session; + struct ao2_container *websocket_apps; +}; + +/*! + * \brief Explicitly shutdown a session. + * + * An explicit shutdown is necessary, since stasis-app has a reference to this + * session. We also need to be sure to null out the \c ws_session field, since + * the websocket is about to go away. + * + * \param session Session info struct. + */ +static void session_shutdown(struct event_session *session) +{ + struct ao2_iterator i; + char *app; + SCOPED_AO2LOCK(lock, session); + + i = ao2_iterator_init(session->websocket_apps, 0); + while ((app = ao2_iterator_next(&i))) { + stasis_app_unregister(app); + ao2_cleanup(app); + } + ao2_iterator_destroy(&i); + ao2_cleanup(session->websocket_apps); + + session->websocket_apps = NULL; + session->ws_session = NULL; +} + +static void session_dtor(void *obj) { - /* TODO: This should promote this socket to a websocket connection */ - ast_log(LOG_ERROR, "TODO: stasis_http_event_websocket\n"); +#ifdef AST_DEVMODE /* Avoid unused variable warning */ + struct event_session *session = obj; +#endif + + /* session_shutdown should have been called before */ + ast_assert(session->ws_session == NULL); + ast_assert(session->websocket_apps == NULL); +} + +static void session_cleanup(struct event_session *session) +{ + session_shutdown(session); + ao2_cleanup(session); +} + +static struct event_session *session_create( + struct ari_websocket_session *ws_session) +{ + RAII_VAR(struct event_session *, session, NULL, ao2_cleanup); + + session = ao2_alloc(sizeof(*session), session_dtor); + + session->ws_session = ws_session; + session->websocket_apps = + ast_str_container_alloc(APPS_NUM_BUCKETS); + + if (!session->websocket_apps) { + return NULL; + } + + ao2_ref(session, +1); + return session; +} + +/*! + * \brief Callback handler for Stasis application messages. + */ +static void app_handler(void *data, const char *app_name, + struct ast_json *message) +{ + struct event_session *session = data; + int res; + + res = ast_json_object_set(message, "application", + ast_json_string_create(app_name)); + if(res != 0) { + return; + } + + ao2_lock(session); + if (session->ws_session) { + ari_websocket_session_write(session->ws_session, message); + } + ao2_unlock(session); +} + +/*! + * \brief Register for all of the apps given. + * \param session Session info struct. + * \param app_list Comma seperated list of app names to register. + */ +static int session_register_apps(struct event_session *session, + const char *app_list) +{ + RAII_VAR(char *, to_free, NULL, ast_free); + char *apps, *app_name; + SCOPED_AO2LOCK(lock, session); + + ast_assert(session->ws_session != NULL); + ast_assert(session->websocket_apps != NULL); + + if (!app_list) { + return -1; + } + + to_free = apps = ast_strdup(app_list); + if (!apps) { + ari_websocket_session_write(session->ws_session, ari_oom_json()); + return -1; + } + while ((app_name = strsep(&apps, ","))) { + if (ast_str_container_add(session->websocket_apps, app_name)) { + ari_websocket_session_write(session->ws_session, ari_oom_json()); + return -1; + } + + stasis_app_register(app_name, app_handler, session); + } + return 0; +} + +void ari_websocket_event_websocket(struct ari_websocket_session *ws_session, + struct ast_variable *headers, + struct ast_event_websocket_args *args) +{ + RAII_VAR(struct event_session *, session, NULL, session_cleanup); + struct ast_json *msg; + int res; + + ast_debug(3, "/events WebSocket connection\n"); + + session = session_create(ws_session); + if (!session) { + ari_websocket_session_write(ws_session, ari_oom_json()); + return; + } + + if (!args->app) { + RAII_VAR(struct ast_json *, msg, NULL, ast_json_unref); + + msg = ast_json_pack("{s: s, s: [s]}", + "error", "MissingParams", + "params", "app"); + if (!msg) { + msg = ast_json_ref(ari_oom_json()); + } + + ari_websocket_session_write(session->ws_session, msg); + return; + } + + res = session_register_apps(session, args->app); + if (res != 0) { + ari_websocket_session_write(ws_session, ari_oom_json()); + return; + } + + /* We don't process any input, but we'll consume it waiting for EOF */ + while ((msg = ari_websocket_session_read(ws_session))) { + ast_json_unref(msg); + } } diff --git a/res/stasis_http/resource_events.h b/res/stasis_http/resource_events.h index 0f58476df..298228cff 100644 --- a/res/stasis_http/resource_events.h +++ b/res/stasis_http/resource_events.h @@ -43,16 +43,14 @@ struct ast_event_websocket_args { /*! \brief Comma seperated list of applications to subscribe to. */ const char *app; - /*! \brief RFC6455 header for upgrading a connection to a websocket. */ - const char *upgrade; }; /*! * \brief WebSocket connection for events. * - * \param headers HTTP headers - * \param args Swagger parameters - * \param[out] response HTTP response + * \param session ARI WebSocket. + * \param headers HTTP headers. + * \param args Swagger parameters. */ -void stasis_http_event_websocket(struct ast_variable *headers, struct ast_event_websocket_args *args, struct stasis_http_response *response); +void ari_websocket_event_websocket(struct ari_websocket_session *session, struct ast_variable *headers, struct ast_event_websocket_args *args); #endif /* _ASTERISK_RESOURCE_EVENTS_H */ -- cgit v1.2.3