Debian Codegraph @

res/ari/ari_websockets.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2013, Digium, Inc.
5 *
6 * David M. Lee, II <[email protected]>
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 #include "asterisk.h"
20
21 #include "resource_events.h"
22 #include "ari_websockets.h"
23 #include "internal.h"
24 #include "ari_model_validators.h"
25 #include "asterisk/app.h"
26 #include "asterisk/ari.h"
27 #include "asterisk/astobj2.h"
28 #include "asterisk/http_websocket.h"
29 #include "asterisk/module.h"
30 #include "asterisk/pbx.h"
31 #include "asterisk/stasis_app.h"
32 #include "asterisk/time.h"
33 #include "asterisk/uuid.h"
34 #include "asterisk/vector.h"
35 #include "asterisk/websocket_client.h"
36
37
38 /*! \file
39 *
40 * \brief WebSocket support for RESTful API's.
41 * \author David M. Lee, II <[email protected]>
42 */
43
44 /*! Number of buckets for the ari_ws_session registry. Remember to keep it a prime number! */
45 #define SESSION_REGISTRY_NUM_BUCKETS 23
46
47 /*! Initial size of websocket session apps vector */
48 #define APPS_INIT_SIZE 7
49
50 /*! Initial size of the websocket session message queue. */
51 #define MESSAGES_INIT_SIZE 23
52
53 #define ARI_CONTEXT_REGISTRAR "res_ari"
54
55 /*! \brief Local registry for created \ref ari_ws_session objects. */
56 static struct ao2_container *session_registry;
57
58 struct ast_websocket_server *ast_ws_server;
59
60 #if defined(AST_DEVMODE)
61 ari_validator ari_validate_message_fn = ast_ari_validate_message;
62 #else
63 /*!
64 * \brief Validator that always succeeds.
65 */
66 static int null_validator(struct ast_json *json)
67 {
68 return 1;
69 }
70
71 ari_validator ari_validate_message_fn = null_validator;
72 #endif
73
74
75 #define VALIDATION_FAILED \
76 "{" \
77 " \"error\": \"InvalidMessage\"," \
78 " \"message\": \"Message validation failed\"" \
79 "}"
80
81 static int session_write(struct ari_ws_session *session, struct ast_json *message)
82 {
83 RAII_VAR(char *, str, NULL, ast_json_free);
84
85 if (!session || !session->ast_ws_session || !message) {
86 return -1;
87 }
88
89 #ifdef AST_DEVMODE
90 if (!session->validator(message)) {
91 ast_log(LOG_ERROR, "Outgoing message failed validation\n");
92 return ast_websocket_write_string(session->ast_ws_session, VALIDATION_FAILED);
93 }
94 #endif
95
96 str = ast_json_dump_string_format(message, ast_ari_json_format());
97
98 if (str == NULL) {
99 ast_log(LOG_ERROR, "Failed to encode JSON object\n");
100 return -1;
101 }
102
103 if (ast_websocket_write_string(session->ast_ws_session, str)) {
104 ast_log(LOG_NOTICE, "Problem occurred during websocket write to %s, websocket closed\n",
105 ast_sockaddr_stringify(ast_websocket_remote_address(session->ast_ws_session)));
106 return -1;
107 }
108 return 0;
109 }
110
111 static void session_send_or_queue(struct ari_ws_session *session,
112 struct ast_json *message, const char *msg_type, const char *app_name,
113 int debug_app)
114 {
115 const char *msg_timestamp, *msg_ast_id;
116
117 msg_timestamp = S_OR(
118 ast_json_string_get(ast_json_object_get(message, "timestamp")), "");
119 if (ast_strlen_zero(msg_timestamp)) {
120 if (ast_json_object_set(message, "timestamp", ast_json_timeval(ast_tvnow(), NULL))) {
121 ast_log(LOG_ERROR,
122 "%s: Failed to dispatch '%s' message from Stasis app '%s'; could not update message\n",
123 session->remote_addr, msg_type, app_name);
124 return;
125 }
126 }
127
128 msg_ast_id = S_OR(
129 ast_json_string_get(ast_json_object_get(message, "asterisk_id")), "");
130 if (ast_strlen_zero(msg_ast_id)) {
131 char eid[20];
132
133 if (ast_json_object_set(message, "asterisk_id",
134 ast_json_string_create(ast_eid_to_str(eid, sizeof(eid), &ast_eid_default)))) {
135 ao2_unlock(session);
136 ast_log(LOG_ERROR,
137 "%s: Failed to dispatch '%s' message from Stasis app '%s'; could not update message\n",
138 session->remote_addr, msg_type, app_name);
139 }
140 }
141
142 if (!session->ast_ws_session) {
143 /* If the websocket is NULL, the message goes to the queue */
144 if (AST_VECTOR_APPEND(&session->message_queue, message) == 0) {
145 ast_json_ref(message);
146 }
147 /*
148 * If the msg_type one of the Application* types, the websocket
149 * might not be there yet so don't log.
150 */
151 if (!ast_begins_with(msg_type, "Application")) {
152 ast_log(LOG_WARNING,
153 "%s: Queued '%s' message for Stasis app '%s'; websocket is not ready\n",
154 session->remote_addr,
155 msg_type,
156 app_name);
157 }
158 } else {
159
160 if (DEBUG_ATLEAST(4) || debug_app) {
161 char *str = ast_json_dump_string_format(message, AST_JSON_PRETTY);
162
163 ast_verbose("<--- Sending ARI event to %s --->\n%s\n",
164 session->remote_addr,
165 str);
166 ast_json_free(str);
167 }
168 session_write(session, message);
169 }
170 }
171
172 static void session_send_app_event(struct ari_ws_session *session,
173 const char *event_type, const char *app_name)
174 {
175 char eid[20];
176 int debug_app = stasis_app_get_debug_by_name(app_name);
177 struct ast_json *msg = ast_json_pack("{s:s, s:o?, s:s, s:s }",
178 "type", event_type,
179 "timestamp", ast_json_timeval(ast_tvnow(), NULL),
180 "application", app_name,
181 "asterisk_id", ast_eid_to_str(eid, sizeof(eid), &ast_eid_default));
182
183 if (!msg) {
184 return;
185 }
186 ast_debug(3, "%s: Sending '%s' event to app '%s'\n", session->session_id,
187 event_type, app_name);
188 /*
189 * We don't want to use ari_websocket_send_event() here because
190 * the app may be unregistered which will cause stasis_app_event_allowed
191 * to return false.
192 */
193 session_send_or_queue(session, msg, event_type, app_name, debug_app);
194 ast_json_unref(msg);
195 }
196
197 static struct ast_json *session_read(struct ari_ws_session *session)
198 {
199 RAII_VAR(struct ast_json *, message, NULL, ast_json_unref);
200
201 if (!session || !session->ast_ws_session) {
202 return NULL;
203 }
204 if (ast_websocket_fd(session->ast_ws_session) < 0) {
205 return NULL;
206 }
207
208 while (!message) {
209 int res;
210 char *payload;
211 uint64_t payload_len;
212 enum ast_websocket_opcode opcode;
213 int fragmented;
214
215 res = ast_wait_for_input(
216 ast_websocket_fd(session->ast_ws_session), -1);
217
218 if (res <= 0) {
219 ast_log(LOG_WARNING, "WebSocket poll error: %s\n",
220 strerror(errno));
221 return NULL;
222 }
223
224 res = ast_websocket_read(session->ast_ws_session, &payload,
225 &payload_len, &opcode, &fragmented);
226
227 if (res != 0) {
228 ast_log(LOG_WARNING, "WebSocket read error: %s\n",
229 strerror(errno));
230 return NULL;
231 }
232
233 switch (opcode) {
234 case AST_WEBSOCKET_OPCODE_CLOSE:
235 ast_debug(1, "WebSocket closed\n");
236 return NULL;
237 case AST_WEBSOCKET_OPCODE_TEXT:
238 message = ast_json_load_buf(payload, payload_len, NULL);
239 if (message == NULL) {
240 struct ast_json *error = ast_json_pack(
241 "{s:s, s:s, s:s, s:i, s:s, s:s }",
242 "type", "RESTResponse",
243 "transaction_id", "",
244 "request_id", "",
245 "status_code", 400,
246 "reason_phrase", "Failed to parse request message JSON",
247 "uri", ""
248 );
249 ari_websocket_send_event(session, session->app_name,
250 error, 0);
251 ast_json_unref(error);
252 ast_log(LOG_WARNING,
253 "WebSocket input failed to parse\n");
254
255 }
256
257 break;
258 default:
259 /* Ignore all other message types */
260 break;
261 }
262 }
263
264 return ast_json_ref(message);
265 }
266
267 void ari_handle_websocket(
268 struct ast_tcptls_session_instance *ser, const char *uri,
269 enum ast_http_method method, struct ast_variable *get_params,
270 struct ast_variable *headers)
271 {
272 struct ast_http_uri fake_urih = {
273 .data = ast_ws_server,
274 };
275
276 ast_websocket_uri_cb(ser, &fake_urih, uri, method, get_params,
277 headers);
278 }
279
280 /*!
281 * \brief Callback handler for Stasis application messages.
282 *
283 * \internal
284 *
285 * \param data Void pointer to the event session (\ref event_session).
286 * \param app_name Name of the Stasis application that dispatched the message.
287 * \param message The dispatched message.
288 * \param debug_app Debug flag for the application.
289 */
290 void ari_websocket_send_event(struct ari_ws_session *session,
291 const char *app_name, struct ast_json *message, int debug_app)
292 {
293 char *remote_addr = session->ast_ws_session ? ast_sockaddr_stringify(
294 ast_websocket_remote_address(session->ast_ws_session)) : "";
295 const char *msg_type, *msg_application;
296 SCOPE_ENTER(4, "%s: Dispatching message from Stasis app '%s'\n", remote_addr, app_name);
297
298 ast_assert(session != NULL);
299
300 ao2_lock(session);
301
302 msg_type = S_OR(ast_json_string_get(ast_json_object_get(message, "type")), "");
303 msg_application = S_OR(
304 ast_json_string_get(ast_json_object_get(message, "application")), app_name);
305
306 /* If we've been replaced, remove the application from our local
307 websocket_apps container */
308 if (session->type == AST_WS_TYPE_INBOUND
309 && strcmp(msg_type, "ApplicationReplaced") == 0 &&
310 strcmp(msg_application, app_name) == 0) {
311 AST_VECTOR_REMOVE_CMP_ORDERED(&session->websocket_apps,
312 app_name, ast_strings_equal, ast_free_ptr);
313 }
314
315 /* Now, we need to determine our state to see how we will handle the message */
316 if (ast_json_object_set(message, "application", ast_json_string_create(app_name))) {
317 ao2_unlock(session);
318 SCOPE_EXIT_LOG_RTN(LOG_WARNING,
319 "%s: Failed to dispatch '%s' message from Stasis app '%s'; could not update message\n",
320 remote_addr, msg_type, msg_application);
321 }
322
323 if (stasis_app_event_allowed(app_name, message)) {
324 session_send_or_queue(session, message, msg_type,
325 app_name, debug_app);
326 }
327
328 if (session->type == AST_WS_TYPE_CLIENT_PER_CALL
329 && !ast_strlen_zero(session->channel_id)
330 && ast_strings_equal(msg_type, "StasisEnd")) {
331 struct ast_json *chan = ast_json_object_get(message, "channel");
332 struct ast_json *id_obj = ast_json_object_get(chan, "id");
333 const char *id = ast_json_string_get(id_obj);
334 if (!ast_strlen_zero(id)
335 && ast_strings_equal(id, session->channel_id)) {
336 ast_debug(3, "%s: StasisEnd message sent for channel '%s'\n",
337 remote_addr, id);
338 session->stasis_end_sent = 1;
339 }
340 }
341 ao2_unlock(session);
342 SCOPE_EXIT("%s: Dispatched '%s' message from Stasis app '%s'\n",
343 remote_addr, msg_type, app_name);
344 }
345
346 static void stasis_app_message_handler(void *data, const char *app_name,
347 struct ast_json *message)
348 {
349 int debug_app = stasis_app_get_debug_by_name(app_name);
350 struct ari_ws_session *session = data;
351
352 if (!session) {
353 ast_debug(3, "Stasis app '%s' message handler called with NULL session. OK for per_call_config websocket.\n",
354 app_name);
355 return;
356 }
357
358 ari_websocket_send_event(session, app_name, message, debug_app);
359 }
360
361 static void session_unref(struct ari_ws_session *session)
362 {
363 if (!session) {
364 return;
365 }
366 ast_debug(4, "%s: Unreffing ARI websocket session\n", session->session_id);
367 ao2_ref(session, -1);
368 }
369
370 static void session_unregister_app_cb(char *app_name, struct ari_ws_session *session)
371 {
372 ast_debug(3, "%s: Trying to unregister app '%s'\n",
373 session->session_id, app_name);
374 if (session->type == AST_WS_TYPE_CLIENT_PER_CALL_CONFIG) {
375 char context_name[AST_MAX_CONTEXT + 1];
376 sprintf(context_name, "%s%s", STASIS_CONTEXT_PREFIX, app_name);
377 ast_debug(3, "%s: Unregistering context '%s' for app '%s'\n",
378 session->session_id, context_name, app_name);
379 ast_context_destroy_by_name(context_name, ARI_CONTEXT_REGISTRAR);
380 } else {
381 ast_debug(3, "%s: Unregistering stasis app '%s' and unsubscribing from all events.\n",
382 session->session_id, app_name);
383 stasis_app_unregister(app_name);
384 }
385
386 /*
387 * We don't send ApplicationUnregistered events for outbound per-call
388 * configs because there's no websocket to send them via or to
389 * inbound websockets because the websocket is probably closed already.
390 */
391 if (!(session->type
392 & (AST_WS_TYPE_CLIENT_PER_CALL_CONFIG | AST_WS_TYPE_INBOUND))) {
393 session_send_app_event(session, "ApplicationUnregistered", app_name);
394 }
395 }
396
397 static void session_unregister_apps(struct ari_ws_session *session)
398 {
399 int app_count = (int)AST_VECTOR_SIZE(&session->websocket_apps);
400
401 if (app_count == 0) {
402 return;
403 }
404 ast_debug(3, "%s: Unregistering stasis apps.\n", session->session_id);
405
406 AST_VECTOR_CALLBACK_VOID(&session->websocket_apps, session_unregister_app_cb,
407 session);
408 AST_VECTOR_RESET(&session->websocket_apps, ast_free_ptr);
409
410 return;
411 }
412
413 static int session_register_apps(struct ari_ws_session *session,
414 const char *_apps, int subscribe_all)
415 {
416 char *apps = ast_strdupa(_apps);
417 char *app_name;
418 int app_counter = 0;
419
420 ast_debug(3, "%s: Registering apps '%s'. Subscribe all: %s\n",
421 session->session_id, apps, subscribe_all ? "yes" : "no");
422
423 while ((app_name = ast_strsep(&apps, ',', AST_STRSEP_STRIP))) {
424
425 if (ast_strlen_zero(app_name)) {
426 ast_log(LOG_WARNING, "%s: Invalid application name\n", session->session_id);
427 return -1;
428 }
429
430 if (strlen(app_name) > ARI_MAX_APP_NAME_LEN) {
431 ast_log(LOG_WARNING, "%s: Websocket app '%s' > %d characters\n",
432 session->session_id, app_name, (int)ARI_MAX_APP_NAME_LEN);
433 return -1;
434 }
435
436 if (session->type == AST_WS_TYPE_CLIENT_PER_CALL_CONFIG) {
437 /*
438 * Outbound per-call configs only create a dialplan context.
439 * If they registered stasis apps there'd be no way for the
440 * Stasis dialplan app to know that it needs to start a
441 * per-call websocket connection.
442 */
443 char context_name[AST_MAX_CONTEXT + 1];
444
445 sprintf(context_name, "%s%s", STASIS_CONTEXT_PREFIX, app_name);
446 if (!ast_context_find(context_name)) {
447 if (!ast_context_find_or_create(NULL, NULL, context_name,
448 ARI_CONTEXT_REGISTRAR)) {
449 ast_log(LOG_WARNING, "%s: Could not create context '%s'\n",
450 session->session_id, context_name);
451 return -1;
452 } else {
453 ast_add_extension(context_name, 0, "_.", 1, NULL, NULL,
454 "Stasis", ast_strdup(app_name), ast_free_ptr,
455 ARI_CONTEXT_REGISTRAR);
456 ast_add_extension(context_name, 0, "h", 1, NULL, NULL,
457 "NoOp", NULL, NULL, ARI_CONTEXT_REGISTRAR);
458 }
459 } else {
460 ast_debug(3, "%s: Context '%s' already exists\n", session->session_id,
461 context_name);
462 }
463 } else {
464 int already_registered = stasis_app_is_registered(app_name);
465 int res = 0;
466
467 if (subscribe_all) {
468 res = stasis_app_register_all(app_name, stasis_app_message_handler,
469 session);
470 } else {
471 res = stasis_app_register(app_name, stasis_app_message_handler,
472 session);
473 }
474
475 if (res != 0) {
476 return -1;
477 }
478
479 /*
480 * If there was an existing app by the same name, the register handler
481 * will have sent an ApplicationReplaced event. If it's a new app, we
482 * send an ApplicationRegistered event.
483 *
484 * Except... There's no websocket to send it on for outbound per-call
485 * configs and inbound websockets don't need them because they aready
486 * know what apps they've registered for.
487 */
488 if (!already_registered
489 && !(session->type & (AST_WS_TYPE_INBOUND | AST_WS_TYPE_CLIENT_PER_CALL_CONFIG))) {
490 session_send_app_event(session, "ApplicationRegistered",
491 app_name);
492 }
493 }
494
495 if (AST_VECTOR_ADD_SORTED(&session->websocket_apps, ast_strdup(app_name), strcmp)) {
496 ast_log(LOG_WARNING, "%s: Unable to add app '%s' to apps container\n",
497 session->session_id, app_name);
498 return -1;
499 }
500
501 app_counter++;
502 if (app_counter == 1) {
503 ast_free(session->app_name);
504 session->app_name = ast_strdup(app_name);
505 if (!session->app_name) {
506 ast_log(LOG_WARNING, "%s: Unable to duplicate app name\n",
507 session->session_id);
508 return -1;
509 }
510 }
511 }
512
513 return 0;
514 }
515
516 /*
517 * Websocket session cleanup is a bit complicated because it can be
518 * in different states, it may or may not be in the registry container,
519 * and stasis may be sending asynchronous events to it and some
520 * stages of cleanup need to lock it.
521 *
522 * That's why there are 3 different cleanup functions.
523 */
524
525 /*!
526 * \internal
527 * \brief Reset the ari_ws_session without destroying it.
528 * It can't be reused and will be cleaned up by the caller.
529 * This should only be called by session_create()
530 * and session_cleanup().
531 */
532 static void session_reset(struct ari_ws_session *session)
533 {
534 SCOPED_AO2LOCK(lock, session);
535
536 ast_debug(3, "%s: Resetting ARI websocket session\n",
537 session->session_id);
538
539 /* Clean up the websocket_apps container */
540 if (AST_VECTOR_SIZE(&session->websocket_apps) > 0) {
541 session_unregister_apps(session);
542 }
543 AST_VECTOR_RESET(&session->websocket_apps, ast_free_ptr);
544 AST_VECTOR_FREE(&session->websocket_apps);
545
546 AST_VECTOR_RESET(&session->message_queue, ast_json_unref);
547 AST_VECTOR_FREE(&session->message_queue);
548 }
549
550 /*!
551 * \internal
552 * \brief RAII_VAR and container ari_ws_session cleanup function.
553 * This unlinks the ari_ws_session from the registry and cleans up the
554 * decrements the reference count.
555 */
556 static void session_cleanup(void *obj)
557 {
558 struct ari_ws_session *session = obj;
559 enum ast_websocket_type wstype;
560
561 if (!session) {
562 return;
563 }
564
565 /*
566 * We need to save the websocket type because client-per-call websockets
567 * will get destroyed when they're unlinked from the session_registry
568 * so we won't be able to test it afterwards.
569 */
570 wstype = session->type;
571
572 ast_debug(3, "%s: Cleaning up ARI %s websocket session. Refcount: %d\n",
573 session->session_id, ast_websocket_type_to_str(wstype), (int)ao2_ref(session, 0));
574
575 session_reset(session);
576
577 if (session_registry) {
578 ast_debug(3, "%s: Unlinking %s websocket session from registry Refcount: %d\n",
579 session->session_id, ast_websocket_type_to_str(wstype), (int)ao2_ref(session, 0));
580 ao2_unlink(session_registry, session);
581 }
582
583 /*
584 * If this is a per-call config then its only reference
585 * was held by the registry container so we don't need
586 * to unref it here.
587 */
588 if (wstype != AST_WS_TYPE_CLIENT_PER_CALL_CONFIG) {
589 session_unref(session);
590 }
591 }
592
593 /*!
594 * \internal
595 * \brief The ao2 destructor.
596 * This cleans up the reference to the parent ast_websocket and the
597 * outbound connection websocket if any.
598 */
599 static void session_dtor(void *obj)
600 {
601 struct ari_ws_session *session = obj;
602
603 ast_debug(3, "%s: Destroying ARI websocket session\n",
604 session->session_id);
605
606 ast_free(session->app_name);
607 ast_free(session->remote_addr);
608 ast_free(session->channel_id);
609 ast_free(session->channel_name);
610 ao2_cleanup(session->owc);
611 session->owc = NULL;
612 if (!session->ast_ws_session) {
613 return;
614 }
615 ast_websocket_unref(session->ast_ws_session);
616 session->ast_ws_session = NULL;
617 }
618
619 #define handle_create_error(ser, code, msg, reason) \
620 ({ \
621 if (ser) { \
622 ast_http_error(ser, code, msg, reason); \
623 } \
624 ast_log(LOG_WARNING, "Failed to create ARI websocket session: %d %s %s\n", \
625 code, msg, reason); \
626 })
627
628 static struct ari_ws_session *session_create(
629 struct ast_tcptls_session_instance *ser,
630 const char *apps,
631 int subscribe_all,
632 const char *session_id,
633 struct ari_conf_outbound_websocket *ows,
634 enum ast_websocket_type ws_type)
635 {
636 RAII_VAR(struct ari_ws_session *, session, NULL, ao2_cleanup);
637 size_t size;
638
639 ast_debug(3, "%s: Creating ARI websocket session for apps '%s'\n",
640 session_id, apps);
641
642 size = sizeof(*session) + strlen(session_id) + 1;
643
644 session = ao2_alloc(size, session_dtor);
645 if (!session) {
646 return NULL;
647 }
648
649 session->type = ws_type;
650 session->subscribe_all = subscribe_all;
651
652 strcpy(session->session_id, session_id); /* Safe */
653
654 /* Instantiate the hash table for Stasis apps */
655 if (AST_VECTOR_INIT(&session->websocket_apps, APPS_INIT_SIZE)) {
656 handle_create_error(ser, 500, "Internal Server Error",
657 "Allocation failed");
658 return NULL;
659 }
660
661 /* Instantiate the message queue */
662 if (AST_VECTOR_INIT(&session->message_queue, MESSAGES_INIT_SIZE)) {
663 handle_create_error(ser, 500, "Internal Server Error",
664 "Allocation failed");
665 AST_VECTOR_FREE(&session->websocket_apps);
666 return NULL;
667 }
668
669 session->validator = ari_validate_message_fn;
670
671 if (ows) {
672 session->owc = ao2_bump(ows);
673 }
674
675 if (session_register_apps(session, apps, subscribe_all) < 0) {
676 handle_create_error(ser, 500, "Internal Server Error",
677 "Stasis app registration failed");
678 session_reset(session);
679 return NULL;
680 }
681
682 if (!ao2_link(session_registry, session)) {
683 handle_create_error(ser, 500, "Internal Server Error",
684 "Allocation failed");
685 session_reset(session);
686 return NULL;
687 }
688
689 return ao2_bump(session);
690 }
691
692 /*!
693 * \internal
694 * \brief Updates the websocket session.
695 *
696 * \details If the value of the \c ws_session is not \c NULL and there are messages in the
697 * event session's \c message_queue, the messages are dispatched and removed from
698 * the queue.
699 *
700 * \param ari_ws_session The ARI websocket session
701 * \param ast_ws_session The Asterisk websocket session
702 */
703 static int session_update(struct ari_ws_session *ari_ws_session,
704 struct ast_websocket *ast_ws_session, int send_registered_events)
705 {
706 RAII_VAR(struct ari_conf_general *, general, ari_conf_get_general(), ao2_cleanup);
707 int i;
708
709 if (ast_ws_session == NULL) {
710 return -1;
711 }
712
713 if (!general) {
714 return -1;
715 }
716
717 ari_ws_session->remote_addr = ast_strdup(ast_sockaddr_stringify(
718 ast_websocket_remote_address(ast_ws_session)));
719 if (!ari_ws_session->remote_addr) {
720 ast_log(LOG_ERROR, "Failed to copy remote address\n");
721 return -1;
722 }
723
724 if (ast_websocket_set_nonblock(ast_ws_session) != 0) {
725 ast_log(LOG_ERROR,
726 "ARI web socket failed to set nonblock; closing: %s\n",
727 strerror(errno));
728 return -1;
729 }
730
731 if (ast_websocket_set_timeout(ast_ws_session, general->write_timeout)) {
732 ast_log(LOG_WARNING, "Failed to set write timeout %d on ARI web socket\n",
733 general->write_timeout);
734 }
735
736 ao2_ref(ast_ws_session, +1);
737 ari_ws_session->ast_ws_session = ast_ws_session;
738 ao2_lock(ari_ws_session);
739 for (i = 0; i < AST_VECTOR_SIZE(&ari_ws_session->message_queue); i++) {
740 struct ast_json *msg = AST_VECTOR_GET(&ari_ws_session->message_queue, i);
741 session_write(ari_ws_session, msg);
742 ast_json_unref(msg);
743 }
744
745 AST_VECTOR_RESET(&ari_ws_session->message_queue, AST_VECTOR_ELEM_CLEANUP_NOOP);
746 ao2_unlock(ari_ws_session);
747
748 if (send_registered_events) {
749 int i;
750 char *app;
751
752 for (i = 0; i < AST_VECTOR_SIZE(&ari_ws_session->websocket_apps); i++) {
753 app = AST_VECTOR_GET(&ari_ws_session->websocket_apps, i);
754 session_send_app_event(ari_ws_session,
755 "ApplicationRegistered", app);
756 }
757 }
758
759 return 0;
760 }
761
762 /*!
763 * \internal
764 * \brief This function gets called for incoming websocket connections
765 * before the upgrade process is completed.
766 *
767 * The point is to be able to report early errors via HTTP rather
768 * than letting res_http_websocket create an ast_websocket session
769 * then immediately close it if there's an error.
770 */
771 static int websocket_attempted_cb(struct ast_tcptls_session_instance *ser,
772 struct ast_variable *get_params, struct ast_variable *headers,
773 const char *session_id)
774 {
775 const char *subscribe_all = NULL;
776 const char *apps = NULL;
777 struct ari_ws_session *session = NULL;
778
779 apps = ast_variable_find_in_list(get_params, "app");
780 if (ast_strlen_zero(apps)) {
781 handle_create_error(ser, 400, "Bad Request",
782 "HTTP request is missing param: [app]");
783 return -1;
784 }
785
786 subscribe_all = ast_variable_find_in_list(get_params, "subscribeAll");
787
788 session = session_create(ser, apps, ast_true(subscribe_all),
789 session_id, NULL, AST_WS_TYPE_INBOUND);
790 if (!session) {
791 handle_create_error(ser, 500, "Server Error",
792 "Failed to create ARI websocket session");
793 return -1;
794 }
795 /* It's in the session registry now so we can release our reference */
796 session_unref(session);
797
798 return 0;
799 }
800
801 /*!
802 * \internal
803 * \brief This function gets called for incoming websocket connections
804 * after the upgrade process is completed.
805 */
806 static void websocket_established_cb(struct ast_websocket *ast_ws_session,
807 struct ast_variable *get_params, struct ast_variable *upgrade_headers)
808 {
809 /*
810 * ast_ws_session is passed in with it's refcount bumped so
811 * we need to unref it when we're done. The refcount will
812 * be bumped again when we add it to the ari_ws_session.
813 */
814 RAII_VAR(struct ast_websocket *, s, ast_ws_session, ast_websocket_unref);
815 RAII_VAR(struct ari_ws_session *, ari_ws_session, NULL, session_cleanup);
816 struct ast_json *msg;
817 struct ast_variable *v;
818 char *remote_addr = ast_sockaddr_stringify(
819 ast_websocket_remote_address(ast_ws_session));
820 const char *session_id = ast_websocket_session_id(ast_ws_session);
821
822 SCOPE_ENTER(2, "%s: WebSocket established\n", remote_addr);
823
824 if (TRACE_ATLEAST(2)) {
825 ast_trace(2, "%s: Websocket Upgrade Headers:\n", remote_addr);
826 for (v = upgrade_headers; v; v = v->next) {
827 ast_trace(3, "--> %s: %s\n", v->name, v->value);
828 }
829
830 ast_trace(2, "%s: Websocket query params:\n", remote_addr);
831 for (v = get_params; v; v = v->next) {
832 ast_trace(3, "--> %s: %s\n", v->name, v->value);
833 }
834 }
835
836 /*
837 * Find the ari_ws_session that was created by websocket_attempted_cb
838 * and update its ast_websocket.
839 */
840 ari_ws_session = ao2_find(session_registry, session_id, OBJ_SEARCH_KEY);
841 if (!ari_ws_session) {
842 SCOPE_EXIT_LOG_RTN(LOG_ERROR,
843 "%s: Failed to locate an event session for the websocket session %s\n",
844 remote_addr, session_id);
845 }
846
847 /*
848 * Since this is a new inbound websocket session,
849 * session_register_apps() will have already sent "ApplicationRegistered"
850 * events for the apps. We don't want to do it again.
851 */
852 session_update(ari_ws_session, ast_ws_session, 0);
853
854 ari_ws_session->connected = 1;
855 ast_trace(-1, "%s: Waiting for messages\n", remote_addr);
856 while ((msg = session_read(ari_ws_session))) {
857 ari_websocket_process_request(ari_ws_session, remote_addr, get_params,
858 upgrade_headers, ari_ws_session->app_name, msg);
859 ast_json_unref(msg);
860 }
861 ari_ws_session->connected = 0;
862
863 SCOPE_EXIT("%s: Websocket closed\n", remote_addr);
864 }
865
866 static int session_shutdown_cb(void *obj, void *arg, int flags)
867 {
868 struct ari_ws_session *session = obj;
869
870 /* Per-call configs have no actual websocket */
871 if (session->type == AST_WS_TYPE_CLIENT_PER_CALL_CONFIG) {
872 ast_log(LOG_NOTICE, "%s: Shutting down %s ARI websocket session\n",
873 session->session_id,
874 ari_websocket_type_to_str(session->type));
875 session_cleanup(session);
876 return 0;
877 }
878 if (session->type == AST_WS_TYPE_INBOUND) {
879 ast_log(LOG_NOTICE, "%s: Shutting down inbound ARI websocket session from %s\n",
880 session->session_id, session->remote_addr);
881 } else {
882 ast_log(LOG_NOTICE, "%s: Shutting down %s ARI websocket session to %s\n",
883 session->session_id,
884 ari_websocket_type_to_str(session->type),
885 session->remote_addr);
886 }
887
888 /*
889 * We need to ensure the session is kept around after the cleanup
890 * so we can close the websocket.
891 */
892 ao2_bump(session);
893 session->closing = 1;
894 session_cleanup(session);
895 if (session->ast_ws_session) {
896 ast_debug(3, "%s: Closing websocket\n", session->session_id);
897 ast_websocket_close(session->ast_ws_session, 1000);
898 } else if (session->thread) {
899 ast_debug(3, "%s: Cancelling handler thread\n", session->session_id);
900 pthread_cancel(session->thread);
901 }
902
903 return 0;
904 }
905
906
907 struct ari_ws_session * ari_websocket_get_session(const char *session_id)
908 {
909 return ao2_find(session_registry, session_id, OBJ_SEARCH_KEY);
910 }
911
912 static struct ari_ws_session *session_find_by_app(const char *app_name,
913 unsigned int ws_type)
914 {
915 struct ari_ws_session *session = NULL;
916 struct ao2_iterator i;
917
918 if (ast_strlen_zero(app_name)) {
919 return NULL;
920 }
921
922 i = ao2_iterator_init(session_registry, 0);
923 while ((session = ao2_iterator_next(&i))) {
924 char *app = NULL;
925 if (!(session->type & ws_type)) {
926 session_unref(session);
927 continue;
928 }
929
930 app = AST_VECTOR_GET_CMP(&session->websocket_apps,
931 app_name, ast_strings_equal);
932 if (app) {
933 break;
934 }
935 session_unref(session);
936 }
937 ao2_iterator_destroy(&i);
938 return session;
939 }
940
941 /*!
942 * \internal
943 * \brief Connection and request handler thread for outbound websockets.
944 *
945 * This thread handles the connection and reconnection logic for outbound
946 * websockets. Once connected, it waits for incoming REST over Websocket
947 * requests and dispatches them to ari_websocket_process_request()).
948 */
949 static void *outbound_session_handler_thread(void *obj)
950 {
951 struct ari_ws_session *session = obj;
952 int already_sent_registers = 1;
953
954 /*
955 * We use pthread_cleanup_push because RAII destructors don't run
956 * if we cancel the thread.
957 */
958 pthread_cleanup_push(session_cleanup, obj);
959
960 ast_debug(3, "%s: Starting outbound websocket thread RC: %d\n",
961 session->session_id, (int)ao2_ref(session, 0));
962 session->thread = pthread_self();
963 session->connected = 0;
964
965 while(1) {
966 RAII_VAR(struct ast_websocket *, astws, NULL, ast_websocket_unref);
967 RAII_VAR(struct ast_variable *, upgrade_headers, NULL, ast_variables_destroy);
968 enum ast_websocket_result result;
969 struct ast_json *msg;
970
971 ast_debug(3, "%s: Attempting to connect to %s\n", session->session_id,
972 session->owc->websocket_client->uri);
973
974 astws = ast_websocket_client_connect(session->owc->websocket_client,
975 NULL, session->session_id, &result);
976 if (!astws || result != WS_OK) {
977 if (session->type == AST_WS_TYPE_CLIENT_PER_CALL) {
978 struct stasis_app_control *control =
979 stasis_app_control_find_by_channel_id(session->channel_id);
980 if (control) {
981 ast_debug(3, "%s: Connection failed. Returning to dialplan.\n",
982 session->session_id);
983 stasis_app_control_mark_failed(control);
984 stasis_app_control_continue(control, NULL, NULL, -1);
985 ao2_cleanup(control);
986 } else {
987 ast_debug(3, "%s: Connection failed. No control object found.\n",
988 session->session_id);
989 }
990
991 break;
992 }
993
994 if (session->closing) {
995 ast_debug(3, "%s: Websocket closing RC: %d\n",
996 session->session_id, (int)ao2_ref(session, 0));
997 break;
998 }
999
1000 usleep(session->owc->websocket_client->reconnect_interval * 1000);
1001 continue;
1002 }
1003 ast_log(LOG_NOTICE, "%s: Outbound websocket connected to %s\n",
1004 session->type == AST_WS_TYPE_CLIENT_PERSISTENT ? session->session_id : session->channel_name,
1005 session->owc->websocket_client->uri);
1006
1007 /*
1008 * We only want to send "ApplicationRegistered" events in the
1009 * case of a reconnect. The initial connection will have already sent
1010 * the events when outbound_register_apps() was called.
1011 */
1012 session_update(session, astws, !already_sent_registers);
1013 already_sent_registers = 0;
1014
1015 /*
1016 * This is the Authorization header that would normally be taken
1017 * from the incoming HTTP request that is being upgraded to a websocket.
1018 * Since this is an outbound websocket, we have to create it ourselves.
1019 *
1020 * This is NOT the same as the Authorization header that is used for
1021 * authentication with the remote websocket server.
1022 */
1023 upgrade_headers = ast_http_create_basic_auth_header(
1024 session->owc->local_ari_user, session->owc->local_ari_password);
1025 if (!upgrade_headers) {
1026 ast_log(LOG_WARNING, "%s: Failed to create upgrade header\n", session->session_id);
1027 session->thread = 0;
1028 session->connected = 0;
1029 ast_websocket_close(astws, 1000);
1030 session->ast_ws_session = NULL;
1031 break;
1032 }
1033
1034 session->connected = 1;
1035 ast_debug(3, "%s: Websocket connected\n", session->session_id);
1036 ast_debug(3, "%s: Waiting for messages RC: %d\n",
1037 session->session_id, (int)ao2_ref(session, 0));
1038
1039 /*
1040 * The websocket is connected. Now we need to wait for messages
1041 * from the server.
1042 */
1043 while ((msg = session_read(session))) {
1044 ari_websocket_process_request(session, session->remote_addr,
1045 NULL, upgrade_headers, session->app_name, msg);
1046 ast_json_unref(msg);
1047 }
1048
1049 session->connected = 0;
1050 ast_websocket_unref(session->ast_ws_session);
1051 session->ast_ws_session = NULL;
1052 if (session->closing) {
1053 ast_debug(3, "%s: Websocket closing RC: %d\n",
1054 session->session_id, (int)ao2_ref(session, 0));
1055 break;
1056 }
1057
1058 ast_log(LOG_WARNING, "%s: Websocket disconnected. Reconnecting\n",
1059 session->session_id);
1060 }
1061
1062 ast_debug(3, "%s: Stopping outbound websocket thread RC: %d\n",
1063 session->session_id, (int)ao2_ref(session, 0));
1064 session->thread = 0;
1065
1066 pthread_cleanup_pop(1);
1067
1068 return NULL;
1069 }
1070
1071 enum session_apply_result {
1072 SESSION_APPLY_NO_CHANGE,
1073 SESSION_APPLY_OK,
1074 SESSION_APPLY_RECONNECT_REQUIRED,
1075 SESSION_APPLY_FAILED,
1076 };
1077
1078 static enum session_apply_result outbound_session_apply_config(
1079 struct ari_ws_session *session,
1080 struct ari_conf_outbound_websocket *new_owc)
1081 {
1082 enum session_apply_result apply_result;
1083 enum ari_conf_owc_fields what_changed;
1084 const char *new_owc_id = ast_sorcery_object_get_id(new_owc);
1085
1086 what_changed = ari_conf_owc_detect_changes(session->owc, new_owc);
1087
1088 if (what_changed == ARI_OWC_FIELD_NONE) {
1089 ast_debug(2, "%s: No changes detected\n", new_owc_id);
1090 return SESSION_APPLY_NO_CHANGE;
1091 }
1092 ast_debug(2, "%s: Config change detected. Checking details\n", new_owc_id);
1093
1094 if (what_changed & ARI_OWC_NEEDS_REREGISTER) {
1095 ast_debug(2, "%s: Re-registering apps\n", new_owc_id);
1096
1097 if (!(what_changed & ARI_OWC_FIELD_SUBSCRIBE_ALL)) {
1098 /*
1099 * If subscribe_all didn't change, we don't have to
1100 * unregister apps that are already registered and
1101 * also in the new config. We'll remove them from
1102 * the session->websocket_apps container so that
1103 * session_unregister_apps will only clean up
1104 * the ones that are going away. session_register_apps
1105 * will add them back in again and cause ApplicationReplaced
1106 * messages to be sent.
1107 *
1108 * If subscribe_all did change, we have no choice but to
1109 * unregister all apps and register all the ones in
1110 * the new config even if they already existed.
1111 */
1112 int i = 0;
1113 char *app;
1114
1115 while(i < (int) AST_VECTOR_SIZE(&session->websocket_apps)) {
1116 app = AST_VECTOR_GET(&session->websocket_apps, i);
1117 if (ast_in_delimited_string(app, new_owc->apps, ',')) {
1118 AST_VECTOR_REMOVE_ORDERED(&session->websocket_apps, i);
1119 ast_debug(3, "%s: Unlinked app '%s' to keep it from being unregistered\n",
1120 new_owc_id, app);
1121 ast_free(app);
1122 } else {
1123 i++;
1124 }
1125 }
1126 }
1127
1128 session_unregister_apps(session);
1129
1130 /*
1131 * Register the new apps. This will also replace any
1132 * existing apps that are in the new config sending
1133 * ApplicationRegistered or ApplicationReplaced events
1134 * as necessary.
1135 */
1136 if (session_register_apps(session, new_owc->apps,
1137 new_owc->subscribe_all) < 0) {
1138 ast_log(LOG_WARNING, "%s: Failed to register apps '%s'\n",
1139 new_owc_id, new_owc->apps);
1140 /* Roll back. */
1141 session_unregister_apps(session);
1142 /* Re-register the original apps. */
1143 if (session_register_apps(session, session->owc->apps,
1144 session->owc->subscribe_all) < 0) {
1145 ast_log(LOG_WARNING, "%s: Failed to re-register apps '%s'\n",
1146 new_owc_id, session->owc->apps);
1147 }
1148 return SESSION_APPLY_FAILED;
1149 }
1150 }
1151 /*
1152 * We need to update the session with the new config
1153 * but it has to be done after re-registering apps and
1154 * before we reconnect.
1155 */
1156 ao2_replace(session->owc, new_owc);
1157 session->type = new_owc->websocket_client->connection_type;
1158 session->subscribe_all = new_owc->subscribe_all;
1159
1160 apply_result = SESSION_APPLY_OK;
1161
1162 if (what_changed & ARI_OWC_NEEDS_RECONNECT) {
1163 ast_debug(2, "%s: Reconnect required\n", new_owc_id);
1164 apply_result = SESSION_APPLY_RECONNECT_REQUIRED;
1165 if (session->ast_ws_session) {
1166 ast_debug(2, "%s: Closing websocket\n", new_owc_id);
1167 ast_websocket_close(session->ast_ws_session, 1000);
1168 }
1169 }
1170
1171 return apply_result;
1172 }
1173
1174 /*
1175 * This is the fail-safe timeout for the per-call websocket
1176 * connection. To prevent a cleanup race condition, we wait
1177 * 3 times the timeout the thread will use to connect to the
1178 * websocket server. This way we're sure the thread will be
1179 * done before we do final cleanup. This timeout is only used
1180 * if the thread is cancelled somehow and can't indicate
1181 * whether it actually connected or not.
1182 */
1183 #define PER_CALL_FAIL_SAFE_TIMEOUT(owc) \
1184 (int64_t)((owc->websocket_client->connect_timeout + owc->websocket_client->reconnect_interval) \
1185 * (owc->websocket_client->reconnect_attempts + 3))
1186
1187 /*!
1188 * \brief This function gets called by app_stasis when a call arrives
1189 * but a Stasis application isn't already registered. We check to see
1190 * if a per-call config exists for the application and if so, we create a
1191 * per-call websocket connection and return a unique app id which app_stasis
1192 * can use to call stasis_app_exec() with.
1193 */
1194 char *ast_ari_create_per_call_websocket(const char *app_name,
1195 struct ast_channel *chan)
1196 {
1197 RAII_VAR(struct ari_ws_session *, session, NULL, session_unref);
1198 RAII_VAR(struct ari_conf_outbound_websocket *, owc, NULL, ao2_cleanup);
1199 RAII_VAR(char *, session_id, NULL, ast_free);
1200 RAII_VAR(char *, app_id, NULL, ast_free);
1201 enum ari_conf_owc_fields invalid_fields;
1202 const char *owc_id = NULL;
1203 char *app_id_rtn = NULL;
1204 struct timeval tv_start;
1205 int res = 0;
1206
1207 owc = ari_conf_get_owc_for_app(app_name, AST_WS_TYPE_CLIENT_PER_CALL_CONFIG);
1208 if (!owc) {
1209 ast_log(LOG_WARNING, "%s: Failed to find outbound websocket per-call config for app '%s'\n",
1210 ast_channel_name(chan), app_name);
1211 return NULL;
1212 }
1213 owc_id = ast_sorcery_object_get_id(owc);
1214 invalid_fields = ari_conf_owc_get_invalid_fields(owc_id);
1215
1216 if (invalid_fields) {
1217 ast_log(LOG_WARNING, "%s: Unable to create per-call websocket. Outbound websocket config is invalid\n",
1218 owc_id);
1219 return NULL;
1220 }
1221
1222 res = ast_asprintf(&session_id, "%s:%s", owc_id, ast_channel_name(chan));
1223 if (res < 0) {
1224 return NULL;
1225 }
1226 res = ast_asprintf(&app_id, "%s:%s", app_name, ast_channel_name(chan));
1227 if (res < 0) {
1228 ast_free(app_id);
1229 return NULL;
1230 }
1231
1232 session = session_create(NULL, app_id, owc->subscribe_all,
1233 session_id, owc, AST_WS_TYPE_CLIENT_PER_CALL);
1234 if (!session) {
1235 ast_log(LOG_WARNING, "%s: Failed to create websocket session\n", session_id);
1236 return NULL;
1237 }
1238
1239 session->channel_id = ast_strdup(ast_channel_uniqueid(chan));
1240 session->channel_name = ast_strdup(ast_channel_name(chan));
1241
1242 /*
1243 * We have to bump the session reference count here because
1244 * we need to check that the session is connected before we return.
1245 * If it didn't connect, then the thread will have cleaned up the
1246 * session while we're in the loop checking for the connection
1247 * which will result in a SEGV or FRACK.
1248 * RAII will clean up this bump.
1249 */
1250 ao2_bump(session);
1251 ast_debug(2, "%s: Starting thread RC: %d\n", session->session_id,
1252 (int)ao2_ref(session, 0));
1253
1254 if (ast_pthread_create_detached_background(&session->thread, NULL,
1255 outbound_session_handler_thread, session)) {
1256 session_cleanup(session);
1257 ast_log(LOG_WARNING, "%s: Failed to create thread.\n", session->session_id);
1258 return NULL;
1259 }
1260
1261 /*
1262 * We need to make sure the session connected and is processing
1263 * requests before we return but we don't want to block forever
1264 * in case the thread never starts or gets cancelled so we have
1265 * a fail-safe timeout.
1266 */
1267 tv_start = ast_tvnow();
1268 while (session->thread > 0 && !session->connected) {
1269 struct timeval tv_now = ast_tvnow();
1270 if (ast_tvdiff_ms(tv_now, tv_start) > PER_CALL_FAIL_SAFE_TIMEOUT(owc)) {
1271 break;
1272 }
1273 /* Sleep for 500ms before checking again. */
1274 usleep(500 * 1000);
1275 }
1276
1277 if (session->thread <= 0 || !session->connected) {
1278 ast_log(LOG_WARNING, "%s: Failed to create per call websocket thread\n",
1279 session_id);
1280 return NULL;
1281 }
1282
1283 ast_debug(3, "%s: Created per call websocket for app '%s'\n",
1284 session_id, app_id);
1285
1286 /*
1287 * We now need to prevent RAII from freeing the app_id.
1288 */
1289 app_id_rtn = app_id;
1290 app_id = NULL;
1291 return app_id_rtn;
1292 }
1293
1294 #define STASIS_END_MAX_WAIT_MS 5000
1295 #define STASIS_END_POST_WAIT_US (3000 * 1000)
1296
1297 /*
1298 * This thread is used to close the websocket after the StasisEnd
1299 * event has been sent and control has been returned to the dialplan.
1300 * We wait a few seconds to allow additional events to be sent
1301 * like ChannelVarset and ChannelDestroyed.
1302 */
1303 static void *outbound_session_pc_close_thread(void *data)
1304 {
1305 /*
1306 * We're using RAII because we want to show a debug message
1307 * after we run ast_websocket_close().
1308 */
1309 RAII_VAR(struct ari_ws_session *, session, data, session_unref);
1310
1311 /*
1312 * We're going to wait 3 seconds to allow stasis to send additional
1313 * events like ChannelVarset and ChannelDestroyed after the StasisEnd.
1314 */
1315 ast_debug(3, "%s: Waiting for %dms before closing websocket RC: %d\n",
1316 session->session_id, (int)(STASIS_END_POST_WAIT_US / 1000),
1317 (int)ao2_ref(session, 0));
1318 usleep(STASIS_END_POST_WAIT_US);
1319 session->closing = 1;
1320 if (session->ast_ws_session) {
1321 ast_websocket_close(session->ast_ws_session, 1000);
1322 }
1323 ast_debug(3, "%s: Websocket closed RC: %d\n", session->session_id,
1324 (int)ao2_ref(session, 0));
1325 return NULL;
1326 }
1327
1328 /*!
1329 * \brief This function is called by the app_stasis dialplan app
1330 * to close a per-call websocket after stasis_app_exec() returns.
1331 */
1332 void ast_ari_close_per_call_websocket(char *app_name)
1333 {
1334 struct ari_ws_session *session = NULL;
1335 pthread_t thread;
1336 struct timeval tv_start;
1337
1338 session = session_find_by_app(app_name, AST_WS_TYPE_CLIENT_PER_CALL);
1339 if (!session) {
1340 ast_debug(3, "%s: Per call websocket not found\n", app_name);
1341 ast_free(app_name);
1342 return;
1343 }
1344 ast_free(app_name);
1345
1346 /*
1347 * When stasis_app_exec() returns, the StasisEnd event for the
1348 * channel has been queued but since actually sending it is done
1349 * in a separate thread, it probably won't have been sent yet.
1350 * We need to wait for it to go out on the wire before we close the
1351 * websocket. ari_websocket_send_event will set a flag on the session
1352 * when a StasisEnd event is sent for the channel that originally
1353 * triggered the connection. We'll wait for that but we don't want
1354 * to wait forever so there's a fail-safe timeout in case a thread
1355 * got cancelled or we missed the StasisEnd event somehow.
1356 */
1357 ast_debug(3, "%s: Waiting for StasisEnd event to be sent RC: %d\n",
1358 session->session_id, (int)ao2_ref(session, 0));
1359
1360 tv_start = ast_tvnow();
1361 while (session->thread > 0 && !session->stasis_end_sent) {
1362 struct timeval tv_now = ast_tvnow();
1363 int64_t diff = ast_tvdiff_ms(tv_now, tv_start);
1364 ast_debug(3, "%s: Waiting for StasisEnd event %lu %d %ld\n",
1365 session->session_id, (unsigned long)session->thread,
1366 session->stasis_end_sent, diff);
1367 if (diff > STASIS_END_MAX_WAIT_MS) {
1368 break;
1369 }
1370 /* Sleep for 500ms before checking again. */
1371 usleep(500 * 1000);
1372 }
1373 ast_debug(3, "%s: StasisEnd event sent. Scheduling websocket close. RC: %d\n",
1374 session->session_id, (int)ao2_ref(session, 0));
1375
1376 /*
1377 * We can continue to send events like ChannelVarset and ChannelDestroyed
1378 * to the websocket after the StasisEnd event but those events won't be
1379 * generated until after the Stasis() dialplan app returns. We don't want
1380 * to hold up the dialplan while we wait so we'll create a thread that waits
1381 * a few seconds more before closing the websocket.
1382 *
1383 * We transferring ownership of the session to the thread.
1384 */
1385 if (ast_pthread_create_detached_background(&thread, NULL,
1386 outbound_session_pc_close_thread, session)) {
1387 ast_log(LOG_WARNING, "%s: Failed to create websocket close thread\n",
1388 session->session_id);
1389 session_unref(session);
1390 }
1391 ast_debug(3, "%s: Scheduled websocket close RC: %d\n",
1392 session->session_id, (int)ao2_ref(session, 0));
1393
1394 return;
1395 }
1396
1397 struct ao2_container* ari_websocket_get_sessions(void)
1398 {
1399 return ao2_bump(session_registry);
1400 }
1401
1402 static int outbound_session_create(void *obj, void *args, int flags)
1403 {
1404 struct ari_conf_outbound_websocket *owc = obj;
1405 const char *owc_id = ast_sorcery_object_get_id(owc);
1406 struct ari_ws_session *session = NULL;
1407 enum session_apply_result apply_result;
1408 enum ari_conf_owc_fields invalid_fields = ari_conf_owc_get_invalid_fields(owc_id);
1409
1410 session = ari_websocket_get_session(owc_id);
1411 if (session) {
1412 ast_debug(2, "%s: Found existing connection\n", owc_id);
1413 if (invalid_fields) {
1414 session_unref(session);
1415 ast_log(LOG_WARNING,
1416 "%s: Unable to update websocket session. Outbound websocket config is invalid\n",
1417 owc_id);
1418 return 0;
1419 }
1420
1421 ao2_lock(session);
1422 apply_result = outbound_session_apply_config(session, owc);
1423 ao2_unlock(session);
1424 session_unref(session);
1425 if (apply_result == SESSION_APPLY_FAILED) {
1426 ast_log(LOG_WARNING,
1427 "%s: Failed to apply new configuration. Existing connection preserved.\n",
1428 owc_id);
1429 }
1430 return 0;
1431 }
1432
1433 if (invalid_fields) {
1434 ast_log(LOG_WARNING,
1435 "%s: Unable to create websocket session. Outbound websocket config is invalid\n",
1436 owc_id);
1437 return 0;
1438 }
1439
1440 session = session_create(NULL, owc->apps, owc->subscribe_all, owc_id,
1441 owc, owc->websocket_client->connection_type);
1442 if (!session) {
1443 ast_log(LOG_WARNING, "%s: Failed to create websocket session\n", owc_id);
1444 return 0;
1445 }
1446
1447 if (owc->websocket_client->connection_type == AST_WS_TYPE_CLIENT_PER_CALL_CONFIG) {
1448 /* There's no thread to transfer the reference to */
1449 session_unref(session);
1450 return 0;
1451 }
1452
1453 ast_debug(2, "%s: Starting thread RC: %d\n", session->session_id,
1454 (int)ao2_ref(session, 0));
1455 /* We're transferring the session reference to the thread. */
1456 if (ast_pthread_create_detached_background(&session->thread, NULL,
1457 outbound_session_handler_thread, session)) {
1458 session_cleanup(session);
1459 ast_log(LOG_WARNING, "%s: Failed to create thread.\n", session->session_id);
1460 return 0;
1461 }
1462 ast_debug(2, "%s: launched thread\n", session->session_id);
1463
1464 return 0;
1465 }
1466
1467 static void outbound_sessions_load(const char *name)
1468 {
1469 RAII_VAR(struct ao2_container *, owcs, ari_conf_get_owcs(), ao2_cleanup);
1470 struct ao2_iterator i;
1471 struct ari_ws_session *session;
1472
1473 ast_debug(2, "Reloading ARI websockets\n");
1474
1475 ao2_callback(owcs, OBJ_NODATA, outbound_session_create, NULL);
1476
1477 i = ao2_iterator_init(session_registry, 0);
1478 while ((session = ao2_iterator_next(&i))) {
1479 int cleanup = 1;
1480 if (session->owc
1481 && (session->type &
1482 (AST_WS_TYPE_CLIENT_PERSISTENT | AST_WS_TYPE_CLIENT_PER_CALL_CONFIG))) {
1483 struct ari_conf_outbound_websocket *ows =
1484 ari_conf_get_owc(session->session_id);
1485 if (!ows) {
1486 ast_debug(3, "Cleaning up outbound websocket %s\n",
1487 session->session_id);
1488 session->closing = 1;
1489 session_cleanup(session);
1490 if (session->ast_ws_session) {
1491 ast_debug(3, "%s: Closing websocket\n", session->session_id);
1492 ast_websocket_close(session->ast_ws_session, 1000);
1493 } else if (session->thread) {
1494 ast_debug(3, "%s: Cancelling handler thread\n", session->session_id);
1495 pthread_cancel(session->thread);
1496 }
1497
1498 if (session->type == AST_WS_TYPE_CLIENT_PERSISTENT) {
1499 /*
1500 * If persistent, session_cleanup will cleanup
1501 * this reference so we don't want to double clean it up.
1502 * session_cleanup doesn't cleanup the reference
1503 * for per-call configs so we need to do that ourselves.
1504 */
1505 cleanup = 0;
1506 }
1507 }
1508 ao2_cleanup(ows);
1509 }
1510 /* We don't want to double cleanup if its been closed. */
1511 if (cleanup) {
1512 ao2_cleanup(session);
1513 }
1514 }
1515 ao2_iterator_destroy(&i);
1516
1517 return;
1518 }
1519
1520 int ari_outbound_websocket_start(struct ari_conf_outbound_websocket *owc)
1521 {
1522 if (owc) {
1523 return outbound_session_create(owc, NULL, 0);
1524 }
1525 return -1;
1526 }
1527
1528 void ari_websocket_shutdown(struct ari_ws_session *session)
1529 {
1530 if (session) {
1531 session_shutdown_cb(session, NULL, 0);
1532 }
1533 }
1534
1535 void ari_websocket_shutdown_all(void)
1536 {
1537 if (session_registry) {
1538 ao2_callback(session_registry, OBJ_MULTIPLE | OBJ_NODATA,
1539 session_shutdown_cb, NULL);
1540 }
1541 }
1542
1543 static void session_registry_dtor(void)
1544 {
1545 if (session_registry) {
1546 ao2_callback(session_registry, OBJ_MULTIPLE | OBJ_NODATA,
1547 session_shutdown_cb, NULL);
1548 ao2_cleanup(session_registry);
1549 session_registry = NULL;
1550 }
1551 }
1552
1553 static struct ast_sorcery_observer observer_callbacks = {
1554 .loaded = outbound_sessions_load,
1555 };
1556
1557 int ari_websocket_unload_module(void)
1558 {
1559 ari_sorcery_observer_remove("outbound_websocket", &observer_callbacks);
1560 session_registry_dtor();
1561 ao2_cleanup(ast_ws_server);
1562 ast_ws_server = NULL;
1563 return 0;
1564 }
1565
1566 AO2_STRING_FIELD_CMP_FN(ari_ws_session, session_id)
1567 AO2_STRING_FIELD_SORT_FN(ari_ws_session, session_id)
1568
1569 int ari_websocket_load_module(int is_enabled)
1570 {
1571 int res = 0;
1572 struct ast_websocket_protocol *protocol;
1573
1574 ast_debug(2, "Initializing ARI websockets. Enabled: %s\n", is_enabled ? "yes" : "no");
1575
1576 session_registry = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_MUTEX,
1577 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE,
1578 ari_ws_session_sort_fn, ari_ws_session_cmp_fn);
1579 if (!session_registry) {
1580 ast_log(LOG_WARNING,
1581 "Failed to allocate the local registry for websocket applications\n");
1582 return AST_MODULE_LOAD_DECLINE;
1583 }
1584
1585 res = ari_sorcery_observer_add("outbound_websocket", &observer_callbacks);
1586 if (res < 0) {
1587 ast_log(LOG_WARNING, "Failed to register ARI websocket observer\n");
1588 ari_websocket_unload_module();
1589 return AST_MODULE_LOAD_DECLINE;
1590 }
1591
1592 /*
1593 * The global "enabled" flag only controls whether the REST and
1594 * inbound websockets are enabled. The outbound websocket
1595 * configs are always enabled.
1596 if (!is_enabled) {
1597 return AST_MODULE_LOAD_SUCCESS;
1598 }
1599 */
1600
1601 ast_ws_server = ast_websocket_server_create();
1602 if (!ast_ws_server) {
1603 ari_websocket_unload_module();
1604 return AST_MODULE_LOAD_DECLINE;
1605 }
1606
1607 protocol = ast_websocket_sub_protocol_alloc("ari");
1608 if (!protocol) {
1609 ari_websocket_unload_module();
1610 return AST_MODULE_LOAD_DECLINE;
1611 }
1612 protocol->session_attempted = websocket_attempted_cb;
1613 protocol->session_established = websocket_established_cb;
1614 res = ast_websocket_server_add_protocol2(ast_ws_server, protocol);
1615
1616 return res == 0 ? AST_MODULE_LOAD_SUCCESS : AST_MODULE_LOAD_DECLINE;
1617 }
1618