Asterisk - The Open Source Telephony Project GIT-master-35be64c
Loading...
Searching...
No Matches
Data Structures | Macros | Enumerations | Functions | Variables
chan_websocket.c File Reference

Websocket Media Channel. More...

#include "asterisk.h"
#include "asterisk/app.h"
#include "asterisk/causes.h"
#include "asterisk/channel.h"
#include "asterisk/codec.h"
#include "asterisk/http_websocket.h"
#include "asterisk/format_cache.h"
#include "asterisk/frame.h"
#include "asterisk/json.h"
#include "asterisk/lock.h"
#include "asterisk/mod_format.h"
#include "asterisk/module.h"
#include "asterisk/pbx.h"
#include "asterisk/uuid.h"
#include "asterisk/timing.h"
#include "asterisk/translate.h"
#include "asterisk/websocket_client.h"
#include "asterisk/sorcery.h"
Include dependency graph for chan_websocket.c:

Go to the source code of this file.

Data Structures

struct  instance_proxy
 
struct  webchan_conf_global
 
struct  websocket_pvt
 

Macros

#define _create_event_MEDIA_XOFF(_instance)   _create_event_nodata(_instance, "MEDIA_XOFF");
 
#define _create_event_MEDIA_XON(_instance)   _create_event_nodata(_instance, "MEDIA_XON");
 
#define _create_event_QUEUE_DRAINED(_instance)   _create_event_nodata(_instance, "QUEUE_DRAINED");
 
#define ANSWER_CHANNEL   "ANSWER"
 
#define CONTINUE_MEDIA   "CONTINUE_MEDIA"
 
#define create_event(_instance, _event, ...)    _create_event_ ## _event(_instance, ##__VA_ARGS__)
 Use this macro to create events passing in any event-specific parameters.
 
#define ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, direction)
 
#define ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command)
 
#define ERROR_ON_UNBUFFERED_MODE_RTN(instance, command)
 
#define FLUSH_MEDIA   "FLUSH_MEDIA"
 
#define GET_DRIVER_STATUS   "GET_STATUS"
 
#define HANGUP_CHANNEL   "HANGUP"
 
#define INCOMING_CONNECTION_ID   "INCOMING"
 
#define MARK_MEDIA   "MARK_MEDIA"
 
#define MAX_TEXT_MESSAGE_LEN   MIN(128, (AST_WEBSOCKET_MAX_RX_PAYLOAD_SIZE - 1))
 
#define MEDIA_WEBSOCKET_CONNECTION_ID   "MEDIA_WEBSOCKET_CONNECTION_ID"
 
#define MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE   "MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE"
 
#define PAUSE_MEDIA   "PAUSE_MEDIA"
 
#define QUEUE_FRAME_DROPPED_FULL   1
 Result of queue_frame_from_buffer() when the frame was dropped because the queue is already at QUEUE_LENGTH_MAX.
 
#define QUEUE_LENGTH_MAX   1000
 
#define QUEUE_LENGTH_XOFF_LEVEL   900
 
#define QUEUE_LENGTH_XON_LEVEL   800
 
#define REPORT_QUEUE_DRAINED   "REPORT_QUEUE_DRAINED"
 
#define send_event(_instance, _event, ...)
 Use this macro to create and send events passing in any event-specific parameters.
 
#define SET_MEDIA_DIRECTION   "SET_MEDIA_DIRECTION"
 
#define START_MEDIA_BUFFERING   "START_MEDIA_BUFFERING"
 
#define STOP_MEDIA_BUFFERING   "STOP_MEDIA_BUFFERING"
 
#define websocket_request_hangup(_instance, _cause, _tech)    _websocket_request_hangup(_instance, _cause, _tech, __LINE__, __FUNCTION__)
 
#define WS_TIMER_FDNO   (AST_EXTENDED_FDS + 1)
 
#define WS_WEBSOCKET_FDNO   (AST_EXTENDED_FDS + 2)
 

Enumerations

enum  {
  OPT_WS_CODEC = (1 << 0) , OPT_WS_NO_AUTO_ANSWER = (1 << 1) , OPT_WS_URI_PARAM = (1 << 2) , OPT_WS_PASSTHROUGH = (1 << 3) ,
  OPT_WS_MSG_FORMAT = (1 << 4) , OPT_WS_MEDIA_DIRECTION = (1 << 5) , OPT_WS_UNBUFFERED = (1 << 6)
}
 
enum  {
  OPT_ARG_WS_CODEC , OPT_ARG_WS_NO_AUTO_ANSWER , OPT_ARG_WS_URI_PARAM , OPT_ARG_WS_PASSTHROUGH ,
  OPT_ARG_WS_MSG_FORMAT , OPT_ARG_WS_MEDIA_DIRECTION , OPT_ARG_WS_UNBUFFERED , OPT_ARG_ARRAY_SIZE
}
 
enum  webchan_control_msg_format { WEBCHAN_CONTROL_MSG_FORMAT_PLAIN = 0 , WEBCHAN_CONTROL_MSG_FORMAT_JSON , WEBCHAN_CONTROL_MSG_FORMAT_INVALID }
 
enum  webchan_media_direction { WEBCHAN_MEDIA_DIRECTION_BOTH , WEBCHAN_MEDIA_DIRECTION_OUT , WEBCHAN_MEDIA_DIRECTION_IN }
 

Functions

static void __reg_module (void)
 
static void __unreg_module (void)
 
static char * _create_event_DTMF_END (struct websocket_pvt *instance, const char digit)
 
static char * _create_event_ERROR (struct websocket_pvt *instance, const char *format,...)
 
static char * _create_event_MEDIA_BUFFERING_COMPLETED (struct websocket_pvt *instance, const char *id)
 
static char * _create_event_MEDIA_MARK_PROCESSED (struct websocket_pvt *instance, const char *id)
 
static char * _create_event_MEDIA_START (struct websocket_pvt *instance)
 
static char * _create_event_nodata (struct websocket_pvt *instance, char *event)
 
static char * _create_event_STATUS (struct websocket_pvt *instance)
 
static void _websocket_request_hangup (struct websocket_pvt *instance, int ast_cause, enum ast_websocket_status_code tech_cause, int line, const char *function)
 
struct ast_module * AST_MODULE_SELF_SYM (void)
 
static enum webchan_control_msg_format control_msg_format_from_str (const char *value)
 
static const char * control_msg_format_to_str (enum webchan_control_msg_format value)
 
static struct ast_frame * create_frame_from_buffer (struct websocket_pvt *instance, char *buffer, size_t len)
 
static struct ast_frame * dequeue_frame (struct websocket_pvt *instance)
 
static void * global_alloc (const char *name)
 
static int global_apply (const struct ast_sorcery *sorcery, void *obj)
 
static int global_control_message_format_from_str (const struct aco_option *opt, struct ast_variable *var, void *obj)
 
static int global_control_message_format_to_str (const void *obj, const intptr_t *args, char **buf)
 
static int handle_command (struct websocket_pvt *instance, char *buffer)
 
static void incoming_ws_established_cb (struct ast_websocket *ast_ws_session, struct ast_variable *get_params, struct ast_variable *upgrade_headers)
 
static int incoming_ws_http_callback (struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
 
static void instance_proxy_cb (void *weakproxy, void *data)
 
static int load_config (void)
 
static int load_module (void)
 Function called when our module is loaded.
 
static int process_binary_message (struct websocket_pvt *instance, char *payload, uint64_t payload_len)
 
static int process_text_message (struct websocket_pvt *instance, char *payload, uint64_t payload_len)
 
static int queue_frame_from_buffer (struct websocket_pvt *instance, char *buffer, size_t len)
 Create a frame from buffer and append it to the frame queue.
 
static int queue_option_frame (struct websocket_pvt *instance, char *buffer)
 
static int read_from_ws_and_queue (struct websocket_pvt *instance)
 
static int reload_module (void)
 
static int set_channel_timer (struct websocket_pvt *instance)
 
static int set_channel_variables (struct websocket_pvt *instance)
 
static int unload_module (void)
 Function called when our module is unloaded.
 
static int validate_uri_parameters (const char *uri_params)
 
static int webchan_call (struct ast_channel *ast, const char *dest, int timeout)
 
static int webchan_hangup (struct ast_channel *ast)
 
static struct ast_frame * webchan_read (struct ast_channel *ast)
 
static struct ast_channel * webchan_request (const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
 
static int webchan_send_dtmf_text (struct ast_channel *ast, char digit, unsigned int duration)
 
static int webchan_write (struct ast_channel *ast, struct ast_frame *f)
 Function called when we should write a frame to the channel.
 
static void websocket_destructor (void *data)
 
static int websocket_handoff_to_channel (struct websocket_pvt *instance)
 
static struct websocket_pvt * websocket_new (const char *chan_name, const char *connection_id, struct ast_format *fmt)
 

Variables

static struct ast_module_info __mod_info = { .name = AST_MODULE, .flags = AST_MODFLAG_LOAD_ORDER , .description = "Websocket Media Channel" , .key = ASTERISK_GPL_KEY , .buildopt_sum = AST_BUILDOPT_SUM, .support_level = AST_MODULE_SUPPORT_CORE, .load = load_module, .unload = unload_module, .reload = reload_module, .load_pri = AST_MODPRI_CHANNEL_DRIVER, .requires = "res_http_websocket,res_websocket_client", }
 
static const struct ast_module_info * ast_module_info = &__mod_info
 
static struct ast_websocket_server * ast_ws_server
 
static struct ast_http_uri http_uri
 
static struct ao2_container * instances = NULL
 
static const char * msg_format_map []
 
static struct ast_sorcery * sorcery = NULL
 
static const char * websocket_media_direction_map []
 
static const struct ast_app_option websocket_options [128] = { [ 'c' ] = { .flag = OPT_WS_CODEC , .arg_index = OPT_ARG_WS_CODEC + 1 }, [ 'n' ] = { .flag = OPT_WS_NO_AUTO_ANSWER }, [ 'v' ] = { .flag = OPT_WS_URI_PARAM , .arg_index = OPT_ARG_WS_URI_PARAM + 1 }, [ 'p' ] = { .flag = OPT_WS_PASSTHROUGH }, [ 'f' ] = { .flag = OPT_WS_MSG_FORMAT , .arg_index = OPT_ARG_WS_MSG_FORMAT + 1 }, [ 'd' ] = { .flag = OPT_WS_MEDIA_DIRECTION , .arg_index = OPT_ARG_WS_MEDIA_DIRECTION + 1 }, [ 'u' ] = { .flag = OPT_WS_UNBUFFERED }, }
 
static struct ast_channel_tech websocket_tech
 

Detailed Description

Websocket Media Channel.

Author
George Joseph gjose.nosp@m.ph@s.nosp@m.angom.nosp@m.a.co.nosp@m.m

Definition in file chan_websocket.c.

Macro Definition Documentation

◆ _create_event_MEDIA_XOFF

#define _create_event_MEDIA_XOFF (   _instance)    _create_event_nodata(_instance, "MEDIA_XOFF");

Definition at line 221 of file chan_websocket.c.

◆ _create_event_MEDIA_XON

#define _create_event_MEDIA_XON (   _instance)    _create_event_nodata(_instance, "MEDIA_XON");

Definition at line 220 of file chan_websocket.c.

◆ _create_event_QUEUE_DRAINED

#define _create_event_QUEUE_DRAINED (   _instance)    _create_event_nodata(_instance, "QUEUE_DRAINED");

Definition at line 222 of file chan_websocket.c.

◆ ANSWER_CHANNEL

#define ANSWER_CHANNEL   "ANSWER"

Definition at line 132 of file chan_websocket.c.

◆ CONTINUE_MEDIA

#define CONTINUE_MEDIA   "CONTINUE_MEDIA"

Definition at line 141 of file chan_websocket.c.

◆ create_event

#define create_event (   _instance,
  _event,
  ... 
)     _create_event_ ## _event(_instance, ##__VA_ARGS__)

Use this macro to create events passing in any event-specific parameters.

Definition at line 441 of file chan_websocket.c.

448 { \
449 int _res = -1; \
450 char *_payload = _create_event_ ## _event(_instance, ##__VA_ARGS__); \
451 if (_payload && _instance->websocket) { \
452 _res = ast_websocket_write_string(_instance->websocket, _payload); \
453 if (_res != 0) { \
454 ast_log(LOG_ERROR, "%s: Unable to send event %s\n", \
455 ast_channel_name(instance->channel), _payload); \
456 } else { \
457 ast_debug(3, "%s: Sent %s\n", \
458 ast_channel_name(instance->channel), _payload); \
459 }\
460 ast_free(_payload); \
461 } \
462 (_res); \
463})
464
465/*!
466 * \internal
467 *
468 * This function gets called by webchan_read which is triggered by the channel
469 * timer firing or by a websocket frame being received while in unbuffered mode.
470 * It always gets called at least every 20ms (or whatever the timer is set to)
471 * even if there are no frames in the queue.
472 */
473static struct ast_frame *dequeue_frame(struct websocket_pvt *instance)
474{
475 struct ast_frame *queued_frame = NULL;
476 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
478
479 /*
480 * If the queue is paused, don't read a frame.
481 */
482 if (instance->queue_paused) {
483 return NULL;
484 }
485
486 /*
487 * We need to check if we need to send an XON before anything
488 * else because there are multiple escape paths in this function
489 * and we don't want to accidentally keep the queue in a "full"
490 * state.
491 */
492 if (instance->queue_full && instance->frame_queue_length < QUEUE_LENGTH_XON_LEVEL) {
493 instance->queue_full = 0;
494 ast_debug(4, "%s: WebSocket sending MEDIA_XON\n",
495 ast_channel_name(instance->channel));
496 send_event(instance, MEDIA_XON);
497 }
498
499 queued_frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list);
500
501 /*
502 * If there are no frames in the queue, we need to return NULL.
503 * We also need to send the QUEUE_DRAINED notification if we
504 * were requested to do so.
505 */
506 if (!queued_frame) {
507 if (instance->report_queue_drained) {
508 instance->report_queue_drained = 0;
509 ast_debug(4, "%s: WebSocket sending QUEUE_DRAINED\n",
510 ast_channel_name(instance->channel));
511 send_event(instance, QUEUE_DRAINED);
512 }
513 return NULL;
514 }
515
516 /*
517 * The only way a control frame could be present here is as
518 * a result of us calling queue_option_frame() in response
519 * to an incoming TEXT command from the websocket.
520 * We'll be safe and make sure it's a AST_CONTROL_OPTION
521 * frame anyway.
522 *
523 * It's quite possible that there are multiple control frames
524 * in a row in the queue so we need to process consecutive ones
525 * immediately.
526 *
527 * In any case, processing a control frame MUST not use up
528 * a media timeslot so after all control frames have been
529 * processed, we need to read an audio frame and process it.
530 */
531 while (queued_frame && queued_frame->frametype == AST_FRAME_CONTROL) {
532 if (queued_frame->subclass.integer == AST_CONTROL_OPTION) {
533 /*
534 * We just need to send the data to the websocket.
535 * The data should already be NULL terminated.
536 */
537 int res = ast_websocket_write_string(instance->websocket,
538 queued_frame->data.ptr);
539 if (res != 0) {
540 ast_log(LOG_ERROR, "%s: Unable to send event %s\n",
541 ast_channel_name(instance->channel), (char *)queued_frame->data.ptr);
542 } else {
543 ast_debug(4, "%s: Sent %s\n",
544 ast_channel_name(instance->channel), (char *)queued_frame->data.ptr);
545 }
546 }
547 /*
548 * We do NOT send these to the core so we need to free
549 * the frame and grab the next one. If it's also a
550 * control frame, we need to process it otherwise
551 * continue down in the function.
552 */
553 ast_frame_free(queued_frame, 0);
554 queued_frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list);
555 /*
556 * Jut FYI... We didn't bump the queue length when we added the control
557 * frames so we don't need to decrement it here.
558 */
559 }
560
561 /*
562 * If, after reading all control frames, there are no frames
563 * left in the queue, we need to return NULL.
564 */
565 if (!queued_frame) {
566 return NULL;
567 }
568
569 instance->frame_queue_length--;
570
571 return queued_frame;
572}
573
574static struct ast_frame *create_frame_from_buffer(struct websocket_pvt *instance,
575 char *buffer, size_t len)
576{
577 struct ast_frame fr = { 0, };
578 struct ast_frame *duped_frame = NULL;
579
580 AST_FRAME_SET_BUFFER(&fr, buffer, 0, len);
582 fr.subclass.format = instance->native_format;
583 if (instance->native_codec->samples_count) {
584 fr.samples = instance->native_codec->samples_count(&fr);
585 }
586
587 duped_frame = ast_frisolate(&fr);
588 if (!duped_frame) {
589 ast_log(LOG_WARNING, "%s: Failed to isolate frame\n",
590 ast_channel_name(instance->channel));
591 return NULL;
592 }
593
594 return duped_frame;
595}
596
597/*!
598 * \internal
599 *
600 * There are two file descriptors on this channel that can trigger
601 * this function...
602 *
603 * The timer fd (WS_TIMER_FDNO) which gets triggered at a constant
604 * rate determined by the format. In this case, we need to pull a
605 * frame OFF the queue and return it to the core.
606 *
607 * The websocket fd (WS_WEBSOCKET_FDNO) which gets triggered when
608 * there's incoming data to read from the websocket. In this case,
609 * we read the data and put it ON the queue. If in unbuffered mode,
610 * we'll read it off the queue immediately and return it. If not in
611 * unbuffered mode, we'll return a null frame now and the frame read
612 * will be processed by the timer tick when it comes to the head
613 * of the queue.
614 *
615 * The reason for queueing and dequeueing immediately in unbuffered
616 * mode is that read_from_ws_and_queue does a lot of work before adding
617 * a frame to the frame queue, if it even needs to. It's much simpler
618 * to just queue and dequeue, both from a code organization standpoint
619 * as well as an instruction-path-length standpoint, than it would be
620 * refactor that code so it can return a frame directly.
621 */
622static struct ast_frame *webchan_read(struct ast_channel *ast)
623{
624 struct websocket_pvt *instance = NULL;
625 struct ast_frame *native_frame = NULL;
626 int fdno = ast_channel_fdno(ast);
627
628 instance = ast_channel_tech_pvt(ast);
629 if (!instance) {
630 return NULL;
631 }
632
633 if (fdno != WS_TIMER_FDNO && fdno != WS_WEBSOCKET_FDNO) {
634 return &ast_null_frame;
635 }
636
637 if (fdno == WS_WEBSOCKET_FDNO) {
638 read_from_ws_and_queue(instance);
639 if (!instance->unbuffered) {
640 return &ast_null_frame;
641 }
642 } else {
644 ast_timer_ack(instance->timer, 1);
645 }
646 }
647
648 native_frame = dequeue_frame(instance);
649 if (!native_frame) {
650 if (instance->leftover_len > 0) {
651 native_frame = create_frame_from_buffer(instance, instance->leftover_data, instance->leftover_len);
652 if (native_frame) {
653 ast_debug(4, "%s: Triggered with no frame available but with %d bytes in leftover_data. Returning partial frame.\n",
654 ast_channel_name(ast), (int)instance->leftover_len);
655 instance->leftover_len = 0;
656 return native_frame;
657 }
658 }
659 ast_debug(4, "%s: Triggered with no frame available and no data in leftover_data. Returning NULL frame.\n",
660 ast_channel_name(ast));
661 return &ast_null_frame;
662 }
663
664 ast_debug(5, "%s: Dequeued %d byte frame. Left in buffer: %d\n",
665 ast_channel_name(ast), native_frame->datalen, (int)instance->leftover_len);
666
667 return native_frame;
668}
669
670/*!
671 * \brief Result of queue_frame_from_buffer() when the frame was dropped
672 * because the queue is already at QUEUE_LENGTH_MAX.
673 *
674 * This is not an error; the caller should stop queueing frames from the
675 * current message but otherwise carry on.
676 */
677#define QUEUE_FRAME_DROPPED_FULL 1
678
679/*!
680 * \brief Create a frame from \a buffer and append it to the frame queue.
681 *
682 * The QUEUE_LENGTH_MAX limit is enforced here, per frame, rather than
683 * once per WebSocket message. A single binary message can carry many
684 * frames' worth of audio, so a per-message check alone lets the queue
685 * grow well past its limit.
686 *
687 * \retval 0 Frame queued.
688 * \retval QUEUE_FRAME_DROPPED_FULL Queue is full; frame dropped.
689 * \retval -1 Failure creating the frame.
690 */
691static int queue_frame_from_buffer(struct websocket_pvt *instance,
692 char *buffer, size_t len)
693{
694 struct ast_frame *duped_frame = NULL;
695
696 duped_frame = create_frame_from_buffer(instance, buffer, len);
697 if (!duped_frame) {
698 return -1;
699 }
700
701 {
702 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
704 if (instance->frame_queue_length >= QUEUE_LENGTH_MAX) {
705 ast_frfree(duped_frame);
706 ast_debug(4, "%s: WebSocket queue is full (%d frames). Dropping %d byte frame.\n",
707 ast_channel_name(instance->channel), instance->frame_queue_length, (int)len);
709 }
710 AST_LIST_INSERT_TAIL(&instance->frame_queue, duped_frame, frame_list);
711 instance->frame_queue_length++;
712 if (!instance->queue_full && instance->frame_queue_length >= QUEUE_LENGTH_XOFF_LEVEL) {
713 instance->queue_full = 1;
714 send_event(instance, MEDIA_XOFF);
715 }
716 }
717
718 ast_debug(5, "%s: Queued %d byte frame\n", ast_channel_name(instance->channel),
719 duped_frame->datalen);
720
721 return 0;
722}
723
724static int queue_option_frame(struct websocket_pvt *instance,
725 char *buffer)
726{
727 struct ast_frame fr = { 0, };
728 struct ast_frame *duped_frame = NULL;
729
730 AST_FRAME_SET_BUFFER(&fr, buffer, 0, strlen(buffer) + 1);
733
734 duped_frame = ast_frisolate(&fr);
735 if (!duped_frame) {
736 ast_log(LOG_WARNING, "%s: Failed to isolate frame\n",
737 ast_channel_name(instance->channel));
738 return -1;
739 }
740
741 AST_LIST_LOCK(&instance->frame_queue);
742 AST_LIST_INSERT_TAIL(&instance->frame_queue, duped_frame, frame_list);
743 AST_LIST_UNLOCK(&instance->frame_queue);
744
745 ast_debug(4, "%s: Queued '%s' option frame\n",
746 ast_channel_name(instance->channel), buffer);
747
748 return 0;
749}
750
751#define ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command) \
752({ \
753 if (instance->passthrough) { \
754 send_event(instance, ERROR, "%s not supported in passthrough mode", command); \
755 ast_debug(4, "%s: WebSocket in passthrough mode. Ignoring %s command.\n", \
756 ast_channel_name(instance->channel), command); \
757 return 0; \
758 } \
759})
760
761#define ERROR_ON_UNBUFFERED_MODE_RTN(instance, command) \
762({ \
763 if (instance->unbuffered) { \
764 send_event(instance, ERROR, "%s not supported in unbuffered mode", command); \
765 ast_debug(4, "%s: WebSocket in unbuffered mode. Ignoring %s command.\n", \
766 ast_channel_name(instance->channel), command); \
767 return 0; \
768 } \
769})
770
771#define ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, direction) \
772({ \
773 if (instance->media_direction == direction) { \
774 send_event(instance, ERROR, "%s not supported while media direction " \
775 "is '%s'", command, websocket_media_direction_map[direction]); \
776 ast_debug(4, "%s: WebSocket media direction is '%s'. Ignoring %s command.\n", \
777 ast_channel_name(instance->channel), websocket_media_direction_map[direction], command); \
778 return 0; \
779 } \
780})
781
782/*!
783 * \internal
784 * \brief Handle commands from the websocket
785 *
786 * \param instance
787 * \param buffer Allocated by caller so don't free.
788 * \retval 0 Success
789 * \retval -1 Failure
790 */
791static int handle_command(struct websocket_pvt *instance, char *buffer)
792{
793 int res = 0;
794 RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
795 const char *command = NULL;
796 char *data = NULL;
797
799 struct ast_json_error json_error;
800
801 json = ast_json_load_buf(buffer, strlen(buffer), &json_error);
802 if (!json) {
803 send_event(instance, ERROR, "Unable to parse JSON command");
804 return -1;
805 }
806 command = ast_json_object_string_get(json, "command");
807 } else {
808 command = buffer;
809 data = strchr(buffer, ' ');
810 if (data) {
811 *data = '\0';
812 data++;
813 }
814 }
815
816 if (ast_strings_equal(command, ANSWER_CHANNEL)) {
818
819 } else if (ast_strings_equal(command, HANGUP_CHANNEL)) {
821
822 } else if (ast_strings_equal(command, START_MEDIA_BUFFERING)) {
823 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
825 if (instance->bulk_media_in_progress) {
826 send_event(instance, ERROR, "START_MEDIA_BUFFERING can't be called when media buffering is already active.\n");
827 return 0;
828 }
829
830 AST_LIST_LOCK(&instance->frame_queue);
831 instance->bulk_media_in_progress = 1;
832 instance->last_unbuffered = instance->unbuffered;
833 instance->unbuffered = 0;
834 AST_LIST_UNLOCK(&instance->frame_queue);
835
836 } else if (ast_strings_equal(command, STOP_MEDIA_BUFFERING)) {
837 const char *id;
838 char *option;
839 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
841
843 id = ast_json_object_string_get(json, "correlation_id");
844 } else {
845 id = data;
846 }
847
848 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
850
851 if (!instance->bulk_media_in_progress) {
852 send_event(instance, ERROR, "STOP_MEDIA_BUFFERING can't be called when media buffering isn't active.\n");
853 return 0;
854 }
855
856 ast_debug(4, "%s: WebSocket %s '%s' with %d bytes in leftover_data.\n",
858 (int)instance->leftover_len);
859
860 instance->bulk_media_in_progress = 0;
861 instance->unbuffered = instance->last_unbuffered;
862 if (instance->leftover_len > 0) {
863 res = queue_frame_from_buffer(instance, instance->leftover_data, instance->leftover_len);
864 if (res < 0) {
865 return res;
866 }
867 }
868 instance->leftover_len = 0;
869 option = create_event(instance, MEDIA_BUFFERING_COMPLETED, id);
870 if (!option) {
871 return -1;
872 }
873 res = queue_option_frame(instance, option);
874 ast_free(option);
875
876 } else if (ast_strings_equal(command, MARK_MEDIA)) {
877 const char *id;
878 char *option;
879 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
881
883
885 id = ast_json_object_string_get(json, "correlation_id");
886 } else {
887 id = data;
888 }
889
890 ast_debug(4, "%s: %s %s\n",
891 ast_channel_name(instance->channel), MARK_MEDIA, id);
892
893 option = create_event(instance, MEDIA_MARK_PROCESSED, id);
894 if (!option) {
895 return -1;
896 }
897 res = queue_option_frame(instance, option);
898 ast_free(option);
899
900 } else if (ast_strings_equal(command, FLUSH_MEDIA)) {
901 struct ast_frame *frame = NULL;
902
903 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
904 ERROR_ON_UNBUFFERED_MODE_RTN(instance, command);
905
906 AST_LIST_LOCK(&instance->frame_queue);
907 while ((frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list))) {
908 ast_frfree(frame);
909 }
910 instance->frame_queue_length = 0;
911 instance->bulk_media_in_progress = 0;
912 instance->leftover_len = 0;
913 instance->unbuffered = instance->last_unbuffered;
914 AST_LIST_UNLOCK(&instance->frame_queue);
915
916 } else if (ast_strings_equal(command, REPORT_QUEUE_DRAINED)) {
917 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
918
919 AST_LIST_LOCK(&instance->frame_queue);
920 instance->report_queue_drained = 1;
921 AST_LIST_UNLOCK(&instance->frame_queue);
922
923 } else if (ast_strings_equal(command, GET_DRIVER_STATUS)) {
924 return send_event(instance, STATUS);
925
926 } else if (ast_strings_equal(command, PAUSE_MEDIA)) {
927 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
928 ERROR_ON_UNBUFFERED_MODE_RTN(instance, command);
930 AST_LIST_LOCK(&instance->frame_queue);
931 instance->queue_paused = 1;
932 AST_LIST_UNLOCK(&instance->frame_queue);
933
934 } else if (ast_strings_equal(command, CONTINUE_MEDIA)) {
935 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
936 ERROR_ON_UNBUFFERED_MODE_RTN(instance, command);
938 AST_LIST_LOCK(&instance->frame_queue);
939 instance->queue_paused = 0;
940 AST_LIST_UNLOCK(&instance->frame_queue);
941
942 } else if (ast_strings_equal(command, SET_MEDIA_DIRECTION)) {
943 const char *direction;
944
945 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
946
948 send_event(instance, ERROR, "%s only supports JSON format.\n", command);
949 return 0;
950 }
951
952 direction = ast_json_object_string_get(json, "direction");
953 if (!direction) {
954 send_event(instance, ERROR, "%s requires a 'direction' parameter.\n", command);
955 return 0;
956 }
957
958 if (!strcmp("both", direction)) {
960 return 0;
961 }
962
963 if (!instance->timer) {
964 set_channel_timer(instance);
966 }
967
969
970 } else if (!strcmp("out", direction)) {
972 return 0;
973 }
974
975 if (!instance->timer) {
976 set_channel_timer(instance);
978 }
979
981
982 } else if (!strcmp("in", direction)) {
984 return 0;
985 }
986
987 if (instance->timer) {
989 ast_timer_close(instance->timer);
990 instance->timer = NULL;
992 }
993
995
996 } else {
997 send_event(instance, ERROR, "'%s' is not a valid direction for %s.\n",
998 direction, command);
999 return 0;
1000 }
1001
1002 } else {
1003 ast_log(LOG_WARNING, "%s: WebSocket %s command unknown\n",
1004 ast_channel_name(instance->channel), command);
1005 }
1006
1007 return res;
1008}
1009
1010static int process_text_message(struct websocket_pvt *instance,
1011 char *payload, uint64_t payload_len)
1012{
1013 char *command;
1014
1015 if (payload_len == 0) {
1016 ast_log(LOG_WARNING, "%s: WebSocket TEXT message has 0 length\n",
1017 ast_channel_name(instance->channel));
1018 return 0;
1019 }
1020
1021 if (payload_len > MAX_TEXT_MESSAGE_LEN) {
1022 ast_log(LOG_WARNING, "%s: WebSocket TEXT message of length %d exceeds maximum length of %d\n",
1023 ast_channel_name(instance->channel), (int)payload_len, MAX_TEXT_MESSAGE_LEN);
1024 return 0;
1025 }
1026
1027 /*
1028 * Unfortunately, payload is not NULL terminated even when it's
1029 * a TEXT frame so we need to allocate a new buffer, copy
1030 * the data into it, and NULL terminate it.
1031 */
1032 command = ast_alloca(payload_len + 1);
1033 memcpy(command, payload, payload_len); /* Safe */
1034 command[payload_len] = '\0';
1035 command = ast_strip(command);
1036
1037 ast_debug(4, "%s: Received: %s\n",
1038 ast_channel_name(instance->channel), command);
1039
1040 return handle_command(instance, command);
1041}
1042
1043static int process_binary_message(struct websocket_pvt *instance,
1044 char *payload, uint64_t payload_len)
1045{
1046 char *next_frame_ptr = NULL;
1047 size_t bytes_read = 0;
1048 int res = 0;
1049 size_t bytes_left = 0;
1050
1051 /*
1052 * Fast path: if the queue is already full, don't bother splitting
1053 * the message into frames. This check alone isn't sufficient since
1054 * one message can hold many frames; queue_frame_from_buffer()
1055 * enforces QUEUE_LENGTH_MAX on every frame it queues.
1056 */
1057 {
1058 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
1060 if (instance->frame_queue_length >= QUEUE_LENGTH_MAX) {
1061 ast_debug(4, "%s: WebSocket queue is full. Ignoring incoming binary message.\n",
1062 ast_channel_name(instance->channel));
1063 return 0;
1064 }
1065 }
1066
1067 next_frame_ptr = payload;
1068 instance->bytes_read += payload_len;
1069
1070 if (instance->unbuffered) {
1071 res = queue_frame_from_buffer(instance, payload, payload_len);
1072 return res < 0 ? res : 0;
1073 }
1074
1075 if (instance->bulk_media_in_progress && instance->leftover_len > 0) {
1076 /*
1077 * We have leftover data from a previous websocket message.
1078 * Try to make a complete frame by appending data from
1079 * the current message to the leftover data.
1080 */
1081 char *append_ptr = instance->leftover_data + instance->leftover_len;
1082 size_t bytes_needed_for_frame = instance->optimal_frame_size - instance->leftover_len;
1083 /*
1084 * It's possible that even the current message doesn't have enough
1085 * data to make a complete frame.
1086 */
1087 size_t bytes_avail_to_copy = MIN(bytes_needed_for_frame, payload_len);
1088
1089 /*
1090 * Append whatever we can to the end of the leftover data
1091 * even if it's not enough to make a complete frame.
1092 */
1093 memcpy(append_ptr, payload, bytes_avail_to_copy);
1094
1095 /*
1096 * If leftover data is still short, just return and wait for the
1097 * next websocket message.
1098 */
1099 if (bytes_avail_to_copy < bytes_needed_for_frame) {
1100 ast_debug(4, "%s: Leftover data %d bytes but only %d new bytes available of %d needed. Appending and waiting for next message.\n",
1101 ast_channel_name(instance->channel), (int)instance->leftover_len, (int)bytes_avail_to_copy, (int)bytes_needed_for_frame);
1102 instance->leftover_len += bytes_avail_to_copy;
1103 return 0;
1104 }
1105
1106 res = queue_frame_from_buffer(instance, instance->leftover_data, instance->optimal_frame_size);
1107 if (res < 0) {
1108 return -1;
1109 }
1110 if (res == QUEUE_FRAME_DROPPED_FULL) {
1111 /* Queue filled up. Drop the rest of this message. */
1112 instance->leftover_len = 0;
1113 return 0;
1114 }
1115
1116 /*
1117 * We stole data from the current payload so decrement payload_len
1118 * and set the next frame pointer after the data in payload
1119 * we just copied.
1120 */
1121 payload_len -= bytes_avail_to_copy;
1122 next_frame_ptr = payload + bytes_avail_to_copy;
1123
1124 ast_debug(5, "%s: --- BR: %4d FQ: %4d PL: %4d LOL: %3d P: %p NFP: %p OFF: %4d NPL: %4d BAC: %3d\n",
1125 ast_channel_name(instance->channel),
1126 instance->frame_queue_length,
1127 (int)instance->bytes_read,
1128 (int)(payload_len + bytes_avail_to_copy),
1129 (int)instance->leftover_len,
1130 payload,
1131 next_frame_ptr,
1132 (int)(next_frame_ptr - payload),
1133 (int)payload_len,
1134 (int)bytes_avail_to_copy
1135 );
1136
1137
1138 instance->leftover_len = 0;
1139 }
1140
1141 if (!instance->bulk_media_in_progress && instance->leftover_len > 0) {
1142 instance->leftover_len = 0;
1143 }
1144
1145 bytes_left = payload_len;
1146 while (bytes_read < payload_len && bytes_left >= instance->optimal_frame_size) {
1147 res = queue_frame_from_buffer(instance, next_frame_ptr,
1148 instance->optimal_frame_size);
1149 if (res < 0) {
1150 break;
1151 }
1152 if (res == QUEUE_FRAME_DROPPED_FULL) {
1153 /*
1154 * Queue filled up part way through this message. Drop the
1155 * remainder, including any partial frame, so we don't later
1156 * splice non-contiguous audio together via leftover_data.
1157 */
1158 ast_debug(4, "%s: WebSocket queue filled mid-message. Dropping remaining %d bytes.\n",
1159 ast_channel_name(instance->channel), (int)bytes_left);
1160 instance->leftover_len = 0;
1161 return 0;
1162 }
1163 bytes_read += instance->optimal_frame_size;
1164 next_frame_ptr += instance->optimal_frame_size;
1165 bytes_left -= instance->optimal_frame_size;
1166 }
1167
1168 if (instance->bulk_media_in_progress && bytes_left > 0) {
1169 /*
1170 * We have a partial frame. Save the leftover data.
1171 */
1172 ast_debug(5, "%s: +++ BR: %4d FQ: %4d PL: %4d LOL: %3d P: %p NFP: %p OFF: %4d BL: %4d\n",
1173 ast_channel_name(instance->channel),
1174 (int)instance->bytes_read,
1175 instance->frame_queue_length,
1176 (int)payload_len,
1177 (int)instance->leftover_len,
1178 payload,
1179 next_frame_ptr,
1180 (int)(next_frame_ptr - payload),
1181 (int)bytes_left
1182 );
1183 memcpy(instance->leftover_data, next_frame_ptr, bytes_left);
1184 instance->leftover_len = bytes_left;
1185 }
1186
1187 return 0;
1188}
1189
1190static int read_from_ws_and_queue(struct websocket_pvt *instance)
1191{
1192 uint64_t payload_len = 0;
1193 char *payload = NULL;
1194 enum ast_websocket_opcode opcode;
1195 int fragmented = 0;
1196 int res = 0;
1197
1198 if (!instance->websocket) {
1199 ast_log(LOG_WARNING, "%s: WebSocket session not found\n",
1200 ast_channel_name(instance->channel));
1201 return -1;
1202 }
1203
1204 res = ast_websocket_read(instance->websocket, &payload, &payload_len,
1205 &opcode, &fragmented);
1206
1207 if (res) {
1208 ast_debug(3, "%s: WebSocket read error\n",
1209 ast_channel_name(instance->channel));
1211 return -1;
1212 }
1213 ast_debug(5, "%s: WebSocket read %d bytes\n", ast_channel_name(instance->channel),
1214 (int)payload_len);
1215
1216 if (opcode == AST_WEBSOCKET_OPCODE_TEXT) {
1217 return process_text_message(instance, payload, payload_len);
1218 }
1219
1220 /*
1221 * PINGs and PONGs will have been handled by res_http_websocket.
1222 * We also need to ignore CONTINUATION frames as they will be accumulated
1223 * by res_http_websocket until the threshold set in websocket_handoff_to_channel()
1224 * is reached, then it will send us a TEXT or BINARY frame.
1225 */
1226 if (opcode == AST_WEBSOCKET_OPCODE_PING || opcode == AST_WEBSOCKET_OPCODE_PONG
1227 || opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
1228 return 0;
1229 }
1230
1231 if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
1232 ast_debug(3, "%s: WebSocket closed by remote\n",
1233 ast_channel_name(instance->channel));
1235 return -1;
1236 }
1237
1238 if (opcode == AST_WEBSOCKET_OPCODE_BINARY) {
1239 /* If the application's media direction is 'in', drop any media we receive from it */
1241 ast_debug(5, "%s: WebSocket dropped frame (application media direction is 'in')\n",
1242 ast_channel_name(instance->channel));
1243 return 0;
1244 }
1245 } else {
1246 ast_log(LOG_WARNING, "%s: WebSocket frame type %d not supported\n",
1247 ast_channel_name(instance->channel), (int)opcode);
1249 return 0;
1250 }
1251
1252 return process_binary_message(instance, payload, payload_len);
1253}
1254
1255static int websocket_handoff_to_channel(struct websocket_pvt *instance)
1256{
1257 int res = 0;
1258 int nodelay = 1;
1259 struct ast_sockaddr *remote_addr = ast_websocket_remote_address(instance->websocket);
1260
1261 instance->remote_addr = ast_strdup(ast_sockaddr_stringify(remote_addr));
1262 ast_debug(3, "%s: WebSocket connection with %s established\n",
1263 ast_channel_name(instance->channel), instance->remote_addr);
1264
1265 if (setsockopt(ast_websocket_fd(instance->websocket),
1266 IPPROTO_TCP, TCP_NODELAY, (char *) &nodelay, sizeof(nodelay)) < 0) {
1267 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on websocket connection: %s\n", strerror(errno));
1268 }
1269
1270 /*
1271 * The way write timeouts are handled in iostream requires the socket to be
1272 * in non-blocking mode. This is fine for reads as well because we already
1273 * set the websocket file descriptor on the channel and let it call
1274 * webchan_read() when data is available.
1275 */
1277
1278 /*
1279 * Tell res_http_websocket to accumulate incoming WebSocket CONTINUATION frames
1280 * into chunks of 1024 bytes and send us a TEXT or BINARY frame when the threshold
1281 * is reached.
1282 */
1284
1286
1287 res = send_event(instance, MEDIA_START);
1288 if (res != 0 ) {
1289 if (instance->type == AST_WS_TYPE_SERVER) {
1291 } else {
1292 /*
1293 * We were called by webchan_call so just need to set causes.
1294 * The core will hangup the channel.
1295 */
1298 }
1299 return -1;
1300 }
1301
1302 if (!instance->no_auto_answer) {
1303 ast_debug(3, "%s: ANSWER by auto_answer\n", ast_channel_name(instance->channel));
1305 }
1306
1307 return 0;
1308}
1309
1310static void _websocket_request_hangup(struct websocket_pvt *instance, int ast_cause,
1311 enum ast_websocket_status_code tech_cause, int line, const char *function)
1312{
1313 if (!instance || !instance->channel) {
1314 return;
1315 }
1316 ast_debug(3, "%s:%s: Hangup requested from %s line %d. cause: %s(%d) tech_cause: %s(%d)",
1317 ast_channel_name(instance->channel), instance->remote_addr,
1318 function, line,
1319 ast_cause2str(ast_cause), ast_cause, ast_websocket_status_to_str(tech_cause), tech_cause);
1320
1321 if (tech_cause) {
1322 ast_channel_tech_hangupcause_set(instance->channel, tech_cause);
1323 }
1324 ast_queue_hangup_with_cause(instance->channel, ast_cause);
1325}
1326
1327/*! \brief Function called when we should write a frame to the channel */
1328static int webchan_write(struct ast_channel *ast, struct ast_frame *f)
1329{
1330 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1331 int res = 0;
1332
1333 if (!instance || !instance->websocket) {
1334 ast_log(LOG_WARNING, "%s: WebSocket instance or client not found\n",
1335 ast_channel_name(ast));
1336 return -1;
1337 }
1338
1339 /* The app doesn't want media right now */
1341 return 0;
1342 }
1343
1344 if (f->frametype == AST_FRAME_CNG) {
1345 return 0;
1346 }
1347
1348 if (f->frametype != AST_FRAME_VOICE) {
1349 ast_log(LOG_WARNING, "%s: This WebSocket channel only supports AST_FRAME_VOICE frames\n",
1350 ast_channel_name(ast));
1351 return 0;
1352 }
1353
1355 ast_log(LOG_WARNING, "%s: This WebSocket channel only supports the '%s' format, not '%s'\n",
1358 return -1;
1359 }
1360
1362 (char *)f->data.ptr, (uint64_t)f->datalen);
1363 if (res != 0) {
1364 ast_log(LOG_WARNING, "%s: WebSocket write failure\n", ast_channel_name(ast));
1365 }
1366
1367 return res;
1368}
1369
1370/*!
1371 * \internal
1372 *
1373 * Called by the core to actually call the remote.
1374 * The core will hang up the channel if a non-zero is returned.
1375 * We just need to set hangup causes if appropriate.
1376 */
1377static int webchan_call(struct ast_channel *ast, const char *dest,
1378 int timeout)
1379{
1380 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1382 struct webchan_conf_global *global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1383 int global_write_timeout = global_cfg ? global_cfg->write_timeout : AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
1384
1385 ao2_cleanup(global_cfg);
1386
1387 if (!instance) {
1388 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n",
1389 ast_channel_name(ast));
1391 return -1;
1392 }
1393
1394 if (instance->type == AST_WS_TYPE_SERVER) {
1395 ast_debug(3, "%s: Websocket call incoming\n", ast_channel_name(instance->channel));
1396 return 0;
1397 }
1398 ast_debug(3, "%s: Websocket call outgoing\n", ast_channel_name(instance->channel));
1399
1400 if (!instance->client) {
1401 ast_log(LOG_WARNING, "%s: WebSocket client not found\n",
1402 ast_channel_name(ast));
1404 return -1;
1405 }
1406
1407 ast_debug(3, "%s: WebSocket call requested to %s. cid: %s\n",
1408 ast_channel_name(ast), dest, instance->connection_id);
1409
1410 if (!ast_strlen_zero(instance->uri_params)) {
1412 }
1413
1414 instance->websocket = ast_websocket_client_connect(instance->client,
1415 instance, ast_channel_name(ast), &result);
1416 if (!instance->websocket || result != WS_OK) {
1417 ast_log(LOG_WARNING, "%s: WebSocket connection failed to %s: %s\n",
1420 return -1;
1421 }
1422
1423 /*
1424 * If websocket_client->write_timeout was set in websocket_client.conf, it will
1425 * have been applied to the websocket by ast_websocket_client_connect() above.
1426 * If it wasn't set in websocket_client.conf, the value will be INT_MAX and
1427 * and ast_websocket_client_connect() will have set AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT
1428 * on the websocket. However, the user may have set write_timeout in the global section
1429 * of chan_websocket.conf so if it wasn't set in websocket_client.conf, we'll now set
1430 * the websocket timeout to that. If they haven't set it in chan_websocket.conf either,
1431 * it'll default to AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT as well so the call below will
1432 * basically become a no-op.
1433 */
1434 if (instance->client->write_timeout == INT_MAX) {
1435 ast_websocket_set_timeout(instance->websocket, global_write_timeout);
1436 }
1437
1438 return websocket_handoff_to_channel(instance);
1439}
1440
1441static void websocket_destructor(void *data)
1442{
1443 struct websocket_pvt *instance = data;
1444 struct ast_frame *frame = NULL;
1445 ast_debug(3, "%s: WebSocket instance freed\n", instance->connection_id);
1446
1447 AST_LIST_LOCK(&instance->frame_queue);
1448 while ((frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list))) {
1449 ast_frfree(frame);
1450 }
1451 AST_LIST_UNLOCK(&instance->frame_queue);
1452
1453 if (instance->timer) {
1454 ast_timer_close(instance->timer);
1455 instance->timer = NULL;
1456 }
1457
1458 if (instance->channel) {
1459 ast_channel_unref(instance->channel);
1460 instance->channel = NULL;
1461 }
1462 if (instance->websocket) {
1463 ast_websocket_unref(instance->websocket);
1464 instance->websocket = NULL;
1465 }
1466
1467 ao2_cleanup(instance->client);
1468 instance->client = NULL;
1469
1470 ao2_cleanup(instance->native_codec);
1471 instance->native_codec = NULL;
1472
1473 ao2_cleanup(instance->native_format);
1474 instance->native_format = NULL;
1475
1476 if (instance->leftover_data) {
1477 ast_free(instance->leftover_data);
1478 instance->leftover_data = NULL;
1479 }
1480
1481 ast_free(instance->uri_params);
1482 ast_free(instance->remote_addr);
1483}
1484
1485struct instance_proxy {
1486 AO2_WEAKPROXY();
1487 /*! \brief The name of the module owning this sorcery instance */
1488 char connection_id[0];
1489};
1490
1491static void instance_proxy_cb(void *weakproxy, void *data)
1492{
1493 struct instance_proxy *proxy = weakproxy;
1494 ast_debug(3, "%s: WebSocket instance removed from instances\n", proxy->connection_id);
1495 ao2_unlink(instances, weakproxy);
1496}
1497
1498static struct websocket_pvt* websocket_new(const char *chan_name,
1499 const char *connection_id, struct ast_format *fmt)
1500{
1501 RAII_VAR(struct instance_proxy *, proxy, NULL, ao2_cleanup);
1502 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1503 char uuid[AST_UUID_STR_LEN];
1504 enum ast_websocket_type ws_type;
1505
1506 SCOPED_AO2WRLOCK(locker, instances);
1507
1510 ws_type = AST_WS_TYPE_SERVER;
1511 } else {
1512 ws_type = AST_WS_TYPE_CLIENT;
1513 }
1514
1515 proxy = ao2_weakproxy_alloc(sizeof(*proxy) + strlen(connection_id) + 1, NULL);
1516 if (!proxy) {
1517 return NULL;
1518 }
1519 strcpy(proxy->connection_id, connection_id); /* Safe */
1520
1521 instance = ao2_alloc(sizeof(*instance) + strlen(connection_id) + 1,
1523 if (!instance) {
1524 return NULL;
1525 }
1526 strcpy(instance->connection_id, connection_id); /* Safe */
1527
1528 instance->type = ws_type;
1529 if (ws_type == AST_WS_TYPE_CLIENT) {
1531 if (!instance->client) {
1532 ast_log(LOG_ERROR, "%s: WebSocket client connection '%s' not found\n",
1533 chan_name, instance->connection_id);
1534 return NULL;
1535 }
1536 }
1537
1538 AST_LIST_HEAD_INIT(&instance->frame_queue);
1539
1540 /*
1541 * We need the codec to calculate the number of samples in a frame
1542 * so we'll get it once and store it in the instance.
1543 *
1544 * References for native_format and native_codec are now held by the
1545 * instance and will be released when the instance is destroyed.
1546 */
1547 instance->native_format = fmt;
1548 instance->native_codec = ast_format_get_codec(instance->native_format);
1549 /*
1550 * References for native_format and native_codec are now held by the
1551 * instance and will be released when the instance is destroyed.
1552 */
1553
1554 /*
1555 * It's not possible for us to re-time or re-frame media if the data
1556 * stream can't be broken up on arbitrary byte boundaries. This is usually
1557 * indicated by the codec's minimum_bytes being small (10 bytes or less).
1558 * We need to force the passthrough and unbuffered modes in this case.
1559 */
1560 if (instance->native_codec->minimum_bytes <= 10) {
1561 instance->passthrough = 1;
1562 instance->unbuffered = 1;
1563 instance->optimal_frame_size = 0;
1564 } else {
1565 instance->optimal_frame_size =
1566 (instance->native_codec->default_ms * instance->native_codec->minimum_bytes)
1567 / instance->native_codec->minimum_ms;
1568 instance->leftover_data = ast_calloc(1, instance->optimal_frame_size);
1569 if (!instance->leftover_data) {
1570 return NULL;
1571 }
1572 }
1573
1574 ast_debug(3,
1575 "%s: WebSocket channel native format '%s' Sample rate: %d ptime: %dms minms: %u minbytes: %u passthrough: %d optimal_frame_size: %d\n",
1576 chan_name, ast_format_get_name(instance->native_format),
1581 instance->passthrough,
1582 instance->optimal_frame_size);
1583
1584 /* We have exclusive access to proxy and sorcery, no need for locking here. */
1585 if (ao2_weakproxy_set_object(proxy, instance, OBJ_NOLOCK)) {
1586 return NULL;
1587 }
1588
1590 return NULL;
1591 }
1592
1593 if (!ao2_link_flags(instances, proxy, OBJ_NOLOCK)) {
1594 ast_log(LOG_ERROR, "%s: Unable to link WebSocket instance to instances\n",
1595 proxy->connection_id);
1596 return NULL;
1597 }
1598 ast_debug(3, "%s: WebSocket instance created and linked\n", proxy->connection_id);
1599
1600 return ao2_bump(instance);
1601}
1602
1603static int set_channel_timer(struct websocket_pvt *instance)
1604{
1605 int rate = 0;
1606 instance->timer = ast_timer_open();
1607 if (!instance->timer) {
1608 return -1;
1609 }
1610 /* Rate is the number of ticks per second, not the interval. */
1611 rate = 1000 / ast_format_get_default_ms(instance->native_format);
1612 ast_debug(3, "%s: WebSocket timer rate %d\n",
1613 ast_channel_name(instance->channel), rate);
1614 ast_timer_set_rate(instance->timer, rate);
1615 /*
1616 * Calling ast_channel_set_fd will cause the channel thread to call
1617 * webchan_read at 'rate' times per second.
1618 */
1620
1621 return 0;
1622}
1623
1624static int set_channel_variables(struct websocket_pvt *instance)
1625{
1626 char *pkt_size = NULL;
1627 int res = ast_asprintf(&pkt_size, "%d", instance->optimal_frame_size);
1628 if (res <= 0) {
1629 return -1;
1630 }
1631
1633 pkt_size);
1634 ast_free(pkt_size);
1636 instance->connection_id);
1637
1638 return 0;
1639}
1640
1641static int validate_uri_parameters(const char *uri_params)
1642{
1643 char *params = ast_strdupa(uri_params);
1644 char *nvp = NULL;
1645 char *nv = NULL;
1646
1647 /*
1648 * uri_params should be a comma-separated list of key=value pairs.
1649 * For example:
1650 * name1=value1,name2=value2
1651 * We're verifying that each name and value either doesn't need
1652 * to be encoded or that it already is.
1653 */
1654
1655 while((nvp = ast_strsep(&params, ',', 0))) {
1656 /* nvp will be name1=value1 */
1657 while((nv = ast_strsep(&nvp, '=', 0))) {
1658 /* nv will be either name1 or value1 */
1659 if (!ast_uri_verify_encoded(nv)) {
1660 return 0;
1661 }
1662 }
1663 }
1664
1665 return 1;
1666}
1667
1668enum {
1669 OPT_WS_CODEC = (1 << 0),
1670 OPT_WS_NO_AUTO_ANSWER = (1 << 1),
1671 OPT_WS_URI_PARAM = (1 << 2),
1672 OPT_WS_PASSTHROUGH = (1 << 3),
1673 OPT_WS_MSG_FORMAT = (1 << 4),
1674 OPT_WS_MEDIA_DIRECTION = (1 << 5),
1675 OPT_WS_UNBUFFERED = (1 << 6),
1676};
1677
1678enum {
1687};
1688
1697 END_OPTIONS );
1698
1699static struct ast_channel *webchan_request(const char *type,
1700 struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids,
1701 const struct ast_channel *requestor, const char *data, int *cause)
1702{
1703 char *parse;
1704 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1705 struct ast_channel *chan = NULL;
1706 struct ast_format *fmt = NULL;
1707 struct ast_format_cap *caps = NULL;
1709 AST_APP_ARG(connection_id);
1711 );
1712 struct ast_flags opts = { 0, };
1713 char *opt_args[OPT_ARG_ARRAY_SIZE];
1714 const char *requestor_name = requestor ? ast_channel_name(requestor) :
1715 (assignedids && !ast_strlen_zero(assignedids->uniqueid) ? assignedids->uniqueid : "<unknown>");
1716 RAII_VAR(struct webchan_conf_global *, global_cfg, NULL, ao2_cleanup);
1717
1718 global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1719
1720 ast_debug(3, "%s: WebSocket channel requested\n",
1721 requestor_name);
1722
1723 if (ast_strlen_zero(data)) {
1724 ast_log(LOG_ERROR, "%s: A connection id is required for the 'WebSocket' channel\n",
1725 requestor_name);
1726 goto failure;
1727 }
1728 parse = ast_strdupa(data);
1729 AST_NONSTANDARD_APP_ARGS(args, parse, '/');
1730
1731 if (ast_strlen_zero(args.connection_id)) {
1732 ast_log(LOG_ERROR, "%s: connection_id is required for the 'WebSocket' channel\n",
1733 requestor_name);
1734 goto failure;
1735 }
1736
1737 if (!ast_strlen_zero(args.options)
1738 && ast_app_parse_options(websocket_options, &opts, opt_args,
1739 ast_strdupa(args.options))) {
1740 ast_log(LOG_ERROR, "%s: 'WebSocket' channel options '%s' parse error\n",
1741 requestor_name, args.options);
1742 goto failure;
1743 }
1744
1745 if (ast_test_flag(&opts, OPT_WS_CODEC)
1746 && !ast_strlen_zero(opt_args[OPT_ARG_WS_CODEC])) {
1747 fmt = ast_format_cache_get(opt_args[OPT_ARG_WS_CODEC]);
1748 } else {
1749 /*
1750 * If codec wasn't specified in the dial string,
1751 * use the first format in the capabilities.
1752 */
1753 fmt = ast_format_cap_get_format(cap, 0);
1754 }
1755
1756 if (!fmt) {
1757 ast_log(LOG_WARNING, "%s: No codec found for sending media to connection '%s'\n",
1758 requestor_name, args.connection_id);
1759 goto failure;
1760 }
1761
1762 ast_debug(3, "%s: Using format %s from %s\n",
1763 requestor_name, ast_format_get_name(fmt),
1764 ast_test_flag(&opts, OPT_WS_CODEC) ? "dialstring" : "requester");
1765
1766 instance = websocket_new(requestor_name, args.connection_id, fmt);
1767 if (!instance) {
1768 ast_log(LOG_ERROR, "%s: Failed to allocate WebSocket channel pvt\n",
1769 requestor_name);
1770 goto failure;
1771 }
1772
1775 if (!strcmp("both", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1776 /* The default. Don't need to do anything here other than
1777 * ensure it is an allowed value. */
1778 } else if (!strcmp("out", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1780 } else if (!strcmp("in", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1782 } else {
1783 ast_log(LOG_ERROR, "Unrecognized option for media direction: '%s'.\n",
1784 opt_args[OPT_ARG_WS_MEDIA_DIRECTION]);
1785 goto failure;
1786 }
1787 }
1788
1790
1791 /*
1792 * Passthrough requires unbuffered. If passthrough was forced by choice of
1793 * codec, unbuffered will already have been set. If passthrough was set by
1794 * the dialstring option, we need to force unbuffered.
1795 */
1796 if (!instance->passthrough) {
1797 instance->passthrough = ast_test_flag(&opts, OPT_WS_PASSTHROUGH);
1798 instance->unbuffered = instance->passthrough;
1799 }
1800 /*
1801 * If unbuffered hasn't been forced by passthrough, set it according to the
1802 * dialstring "u" option.
1803 */
1804 if (!instance->unbuffered) {
1805 instance->unbuffered = ast_test_flag(&opts, OPT_WS_UNBUFFERED);
1806 }
1807
1809 && !ast_strlen_zero(opt_args[OPT_ARG_WS_URI_PARAM])) {
1810 char *comma;
1811
1812 if (ast_strings_equal(args.connection_id, INCOMING_CONNECTION_ID)) {
1814 "%s: URI parameters are not allowed for 'WebSocket/INCOMING' channels\n",
1815 requestor_name);
1816 goto failure;
1817 }
1818
1819 ast_debug(3, "%s: Using URI parameters '%s'\n",
1820 requestor_name, opt_args[OPT_ARG_WS_URI_PARAM]);
1821
1823 ast_log(LOG_ERROR, "%s: Invalid URI parameters '%s' in WebSocket/%s dial string\n",
1824 requestor_name, opt_args[OPT_ARG_WS_URI_PARAM],
1825 args.connection_id);
1826 goto failure;
1827 }
1828
1829 instance->uri_params = ast_strdup(opt_args[OPT_ARG_WS_URI_PARAM]);
1830 comma = instance->uri_params;
1831 /*
1832 * The normal separator for query string components is an
1833 * ampersand ('&') but the Dial app interprets them as additional
1834 * channels to dial in parallel so we instruct users to separate
1835 * the parameters with commas (',') instead. We now have to
1836 * convert those commas back to ampersands.
1837 */
1838 while ((comma = strchr(comma,','))) {
1839 *comma = '&';
1840 }
1841 ast_debug(3, "%s: Using final URI '%s'\n", requestor_name, instance->uri_params);
1842 }
1843
1844 if (ast_test_flag(&opts, OPT_WS_MSG_FORMAT)) {
1846
1848 ast_log(LOG_WARNING, "%s: 'f/control message format' dialstring parameter value missing or invalid. "
1849 "Defaulting to 'plain-text'\n",
1850 requestor_name);
1852 }
1853 } else if (global_cfg) {
1854 instance->control_msg_format = global_cfg->control_msg_format;
1855 }
1856
1857 chan = ast_channel_alloc(1, AST_STATE_DOWN, "", "", "", "", "", assignedids,
1858 requestor, 0, "WebSocket/%s/%p", args.connection_id, instance);
1859 if (!chan) {
1860 ast_log(LOG_ERROR, "%s: Unable to alloc channel\n", requestor_name);
1861 goto failure;
1862 }
1863
1864 /* Prevent device state caching as this channel involves ephemeral destinations or sources */
1866 ast_debug(3, "%s: WebSocket channel %s allocated for connection %s\n",
1867 ast_channel_name(chan), requestor_name,
1868 instance->connection_id);
1869
1870 instance->channel = ao2_bump(chan);
1872
1873 /* If the application's media direction is 'both' or 'out', we need the channel timer. */
1875 && set_channel_timer(instance) != 0) {
1876 goto failure;
1877 }
1878
1879 if (set_channel_variables(instance) != 0) {
1880 goto failure;
1881 }
1882
1884 if (!caps) {
1885 ast_log(LOG_ERROR, "%s: Unable to alloc caps\n", requestor_name);
1886 goto failure;
1887 }
1888
1889 ast_format_cap_append(caps, instance->native_format, 0);
1890 ast_channel_nativeformats_set(instance->channel, caps);
1893 ast_channel_set_readformat(instance->channel, instance->native_format);
1895 ast_channel_tech_pvt_set(chan, ao2_bump(instance));
1896 ast_channel_unlock(chan);
1897 ao2_cleanup(caps);
1898
1899 ast_debug(3, "%s: WebSocket channel created to %s\n",
1900 ast_channel_name(chan), args.connection_id);
1901
1902 return chan;
1903
1904failure:
1905 if (chan) {
1906 ast_channel_unlock(chan);
1907 }
1908 *cause = AST_CAUSE_FAILURE;
1909 return NULL;
1910}
1911
1912/*!
1913 * \internal
1914 *
1915 * Called by the core to hang up the channel.
1916 */
1917static int webchan_hangup(struct ast_channel *ast)
1918{
1919 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1920
1921 if (!instance) {
1922 return -1;
1923 }
1924 ast_debug(3, "%s: WebSocket call hangup. cid: %s\n",
1925 ast_channel_name(ast), instance->connection_id);
1926
1927 if (instance->websocket) {
1929 ast_websocket_unref(instance->websocket);
1930 instance->websocket = NULL;
1931 }
1933
1934 /* Clean up the reference from adding the instance to the channel */
1935 ao2_cleanup(instance);
1936
1937 return 0;
1938}
1939
1940static int webchan_send_dtmf_text(struct ast_channel *ast, char digit, unsigned int duration)
1941{
1942 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1943
1944 if (!instance) {
1945 return -1;
1946 }
1947
1948 return send_event(instance, DTMF_END, digit);
1949}
1950
1951/*!
1952 * \internal
1953 *
1954 * Called by res_http_websocket after a client has connected and
1955 * successfully upgraded from HTTP to WebSocket.
1956 *
1957 * Depends on incoming_ws_http_callback parsing the connection_id from
1958 * the HTTP request and storing it in get_params.
1959 */
1960static void incoming_ws_established_cb(struct ast_websocket *ast_ws_session,
1961 struct ast_variable *get_params, struct ast_variable *upgrade_headers)
1962{
1963 RAII_VAR(struct ast_websocket *, s, ast_ws_session, ast_websocket_unref);
1964 struct ast_variable *v;
1965 const char *connection_id = NULL;
1966 struct websocket_pvt *instance = NULL;
1967 struct webchan_conf_global *global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1968 int global_write_timeout = global_cfg ? global_cfg->write_timeout : AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
1969
1970 ao2_cleanup(global_cfg);
1971
1972 ast_debug(3, "WebSocket established\n");
1973
1974 for (v = upgrade_headers; v; v = v->next) {
1975 ast_debug(4, "Header-> %s: %s\n", v->name, v->value);
1976 }
1977 for (v = get_params; v; v = v->next) {
1978 ast_debug(4, " Param-> %s: %s\n", v->name, v->value);
1979 }
1980
1981 connection_id = ast_variable_find_in_list(get_params, "CONNECTION_ID");
1982 if (!connection_id) {
1983 /*
1984 * This can't really happen because websocket_http_callback won't
1985 * let it get this far if it can't add the connection_id to the
1986 * get_params.
1987 * Just in case though...
1988 */
1989 ast_log(LOG_WARNING, "WebSocket connection id not found\n");
1992 return;
1993 }
1994
1995 instance = ao2_weakproxy_find(instances, connection_id, OBJ_SEARCH_KEY | OBJ_NOLOCK, "");
1996 if (!instance) {
1997 /*
1998 * This also can't really happen because websocket_http_callback won't
1999 * let it get this far if it can't find the instance.
2000 * Just in case though...
2001 */
2002 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n", connection_id);
2005 return;
2006 }
2007 instance->websocket = ao2_bump(ast_ws_session);
2008
2009 ast_websocket_set_timeout(instance->websocket, global_write_timeout);
2010
2012 ao2_cleanup(instance);
2013 /*
2014 * The instance is the channel's responsibility now.
2015 * We just return here.
2016 */
2017}
2018
2019/*!
2020 * \internal
2021 *
2022 * Called by the core http server after a client connects but before
2023 * the upgrade from HTTP to Websocket. We need to save the URI in
2024 * the CONNECTION_ID in a get_param because it contains the connection UUID
2025 * we gave to the client when they used externalMedia to create the channel.
2026 * incoming_ws_established_cb() will use this to retrieve the chan_websocket
2027 * instance.
2028 */
2030 const struct ast_http_uri *urih, const char *uri,
2031 enum ast_http_method method, struct ast_variable *get_params,
2032 struct ast_variable *headers)
2033{
2034 struct ast_http_uri fake_urih = {
2036 };
2037 int res = 0;
2038 /*
2039 * Normally the http server will destroy the get_params
2040 * when the session ends but if there weren't any initially
2041 * and we create some and add them to the list, the http server
2042 * won't know about it so we have to destroy it ourselves.
2043 */
2044 int destroy_get_params = (get_params == NULL);
2045 struct ast_variable *v = NULL;
2046 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
2047
2048 ast_debug(2, "URI: %s Starting\n", uri);
2049
2050 /*
2051 * The client will have issued the GET request with a URI of
2052 * /media/<connection_id>
2053 *
2054 * Since this callback is registered for the /media URI prefix the
2055 * http server will strip that off the front of the URI passing in
2056 * only the path components after that in the 'uri' parameter.
2057 * This should leave only the connection id without a leading '/'.
2058 */
2059 instance = ao2_weakproxy_find(instances, uri, OBJ_SEARCH_KEY | OBJ_NOLOCK, "");
2060 if (!instance) {
2061 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n", uri);
2062 ast_http_error(ser, 404, "Not found", "WebSocket instance not found");
2063 return -1;
2064 }
2065
2066 /*
2067 * We don't allow additional connections using the same connection id.
2068 */
2069 if (instance->websocket) {
2070 ast_log(LOG_WARNING, "%s: Websocket already connected for channel '%s'\n",
2071 uri, instance->channel ? ast_channel_name(instance->channel) : "unknown");
2072 ast_http_error(ser, 409, "Conflict", "Another websocket connection exists for this connection id");
2073 return -1;
2074 }
2075
2076 v = ast_variable_new("CONNECTION_ID", uri, "");
2077 if (!v) {
2078 ast_http_error(ser, 500, "Server error", "");
2079 return -1;
2080 }
2081 ast_variable_list_append(&get_params, v);
2082
2083 for (v = get_params; v; v = v->next) {
2084 ast_debug(4, " Param-> %s: %s\n", v->name, v->value);
2085 }
2086
2087 /*
2088 * This will ultimately call internal_ws_established_cb() so
2089 * this function will block until the websocket is closed and
2090 * internal_ws_established_cb() returns;
2091 */
2092 res = ast_websocket_uri_cb(ser, &fake_urih, uri, method,
2093 get_params, headers);
2094 if (destroy_get_params) {
2095 ast_variables_destroy(get_params);
2096 }
2097
2098 ast_debug(2, "URI: %s DONE\n", uri);
2099
2100 return res;
2101}
2102
2103static struct ast_http_uri http_uri = {
2105 .description = "Media over Websocket",
2106 .uri = "media",
2107 .has_subtree = 1,
2108 .data = NULL,
2109 .key = __FILE__,
2110 .no_decode_uri = 1,
2111};
2112
2116
2117static int global_control_message_format_from_str(const struct aco_option *opt,
2118 struct ast_variable *var, void *obj)
2119{
2120 struct webchan_conf_global *cfg = obj;
2121
2123
2125 ast_log(LOG_ERROR, "chan_websocket.conf: Invalid value '%s' for "
2126 "control_mesage_format. Must be 'plain-text' or 'json'\n",
2127 var->value);
2128 return -1;
2129 }
2130
2131 return 0;
2132}
2133
2134static int global_control_message_format_to_str(const void *obj, const intptr_t *args, char **buf)
2135{
2136 const struct webchan_conf_global *cfg = obj;
2137
2139
2140 return 0;
2141}
2142
2143static void *global_alloc(const char *name)
2144{
2146 sizeof(*cfg), NULL);
2147
2148 if (!cfg) {
2149 return NULL;
2150 }
2151
2152 return cfg;
2153}
2154
2155static int global_apply(const struct ast_sorcery *sorcery, void *obj)
2156{
2157 struct webchan_conf_global *cfg = obj;
2158
2159 ast_debug(1, "control_msg_format: %s\n",
2161
2162 if (cfg->write_timeout <= 0) {
2163 ast_log(LOG_WARNING, "The write_timeout parameter must be > 0\n");
2164 return -1;
2165 }
2166
2167 return 0;
2168}
2169
2170static int load_config(void)
2171{
2172 ast_debug(2, "Initializing Websocket Client Configuration\n");
2174 if (!sorcery) {
2175 ast_log(LOG_ERROR, "Failed to open sorcery\n");
2176 return -1;
2177 }
2178
2179 ast_sorcery_apply_default(sorcery, "global", "config",
2180 "chan_websocket.conf,criteria=type=global,single_object=yes,explicit_name=global");
2181
2183 ast_log(LOG_ERROR, "Failed to register chan_websocket global object with sorcery\n");
2185 sorcery = NULL;
2186 return -1;
2187 }
2188
2189 ast_sorcery_object_field_register_nodoc(sorcery, "global", "type", "", OPT_NOOP_T, 0, 0);
2190 ast_sorcery_register_cust(global, control_message_format, "plain-text");
2193
2195
2196 return 0;
2197}
2198
2199/*! \brief Function called when our module is unloaded */
2200static int unload_module(void)
2201{
2205
2209
2211 instances = NULL;
2212
2214 sorcery = NULL;
2215
2216 return 0;
2217}
2218
2219static int reload_module(void)
2220{
2221 ast_debug(2, "Reloading chan_websocket configuration\n");
2223
2224 return 0;
2225}
2226
2227/*! \brief Function called when our module is loaded */
2228static int load_module(void)
2229{
2230 int res = 0;
2231 struct ast_websocket_protocol *protocol;
2232
2233 res = load_config();
2234 if (res != 0) {
2236 }
2237
2240 }
2241
2244 ast_log(LOG_ERROR, "Unable to register channel class 'WebSocket'\n");
2245 unload_module();
2247 }
2248
2250 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, 17, instance_proxy_hash_fn,
2251 instance_proxy_sort_fn, instance_proxy_cmp_fn);
2252 if (!instances) {
2254 "Failed to allocate the chan_websocket instance registry\n");
2255 unload_module();
2257 }
2258
2260 if (!ast_ws_server) {
2261 unload_module();
2263 }
2264
2265 protocol = ast_websocket_sub_protocol_alloc("media");
2266 if (!protocol) {
2267 unload_module();
2269 }
2272
2274
2276}
2277
2278AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Websocket Media Channel",
2279 .support_level = AST_MODULE_SUPPORT_CORE,
2280 .load = load_module,
2281 .unload = unload_module,
2283 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2284 .requires = "res_http_websocket,res_websocket_client",
2285);
char digit
enum queue_result id
Definition app_queue.c:1790
#define var
Definition ast_expr2f.c:605
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition astmm.h:288
#define ast_free(a)
Definition astmm.h:180
#define ast_strdup(str)
A wrapper for strdup()
Definition astmm.h:241
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition astmm.h:298
#define ast_asprintf(ret, fmt,...)
A wrapper for asprintf()
Definition astmm.h:267
#define ast_calloc(num, len)
A wrapper for calloc()
Definition astmm.h:202
#define ast_log
Definition astobj2.c:42
#define ao2_weakproxy_set_object(weakproxy, obj, flags)
Associate weakproxy with obj.
Definition astobj2.h:579
int ao2_weakproxy_subscribe(void *weakproxy, ao2_weakproxy_notification_cb cb, void *data, int flags)
Request notification when weakproxy points to NULL.
Definition astobj2.c:934
@ AO2_ALLOC_OPT_LOCK_RWLOCK
Definition astobj2.h:365
#define AO2_STRING_FIELD_CMP_FN(stype, field)
Creates a compare function for a structure string field.
Definition astobj2.h:2048
#define ao2_cleanup(obj)
Definition astobj2.h:1934
#define ao2_unlink(container, obj)
Remove an object from a container.
Definition astobj2.h:1578
#define ao2_link_flags(container, obj, flags)
Add an object to a container.
Definition astobj2.h:1554
#define AO2_STRING_FIELD_SORT_FN(stype, field)
Creates a sort function for a structure string field.
Definition astobj2.h:2064
#define ao2_weakproxy_find(c, arg, flags, tag)
Perform an ao2_find on a container with ao2_weakproxy objects, returning the real object.
Definition astobj2.h:1748
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
Definition astobj2.h:480
#define ao2_weakproxy_alloc(data_size, destructor_fn)
Allocate an ao2_weakproxy object.
Definition astobj2.h:550
#define AO2_STRING_FIELD_HASH_FN(stype, field)
Creates a hash function for a structure string field.
Definition astobj2.h:2032
@ OBJ_NOLOCK
Assume that the ao2_container is already locked.
Definition astobj2.h:1063
@ OBJ_SEARCH_KEY
The arg parameter is a search key, but is not an object.
Definition astobj2.h:1101
#define ao2_alloc(data_size, destructor_fn)
Definition astobj2.h:409
#define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn)
Allocate and initialize a hash container with the desired number of buckets.
Definition astobj2.h:1303
@ AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE
Replace objects with duplicate keys in container.
Definition astobj2.h:1211
#define AST_CAUSE_FAILURE
Definition causes.h:150
#define AST_CAUSE_NORMAL
Definition causes.h:151
#define AST_CAUSE_NETWORK_OUT_OF_ORDER
Definition causes.h:121
#define AST_CAUSE_NO_ROUTE_DESTINATION
Definition causes.h:100
static PGresult * result
Definition cel_pgsql.c:84
static const char type[]
#define ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command)
#define FLUSH_MEDIA
static void _websocket_request_hangup(struct websocket_pvt *instance, int ast_cause, enum ast_websocket_status_code tech_cause, int line, const char *function)
#define QUEUE_FRAME_DROPPED_FULL
Result of queue_frame_from_buffer() when the frame was dropped because the queue is already at QUEUE_...
#define QUEUE_LENGTH_XON_LEVEL
#define MARK_MEDIA
#define send_event(_instance, _event,...)
Use this macro to create and send events passing in any event-specific parameters.
static int incoming_ws_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
#define ANSWER_CHANNEL
static void instance_proxy_cb(void *weakproxy, void *data)
static struct ast_frame * dequeue_frame(struct websocket_pvt *instance)
static void * global_alloc(const char *name)
@ OPT_WS_MEDIA_DIRECTION
@ OPT_WS_CODEC
@ OPT_WS_PASSTHROUGH
@ OPT_WS_URI_PARAM
@ OPT_WS_MSG_FORMAT
@ OPT_WS_NO_AUTO_ANSWER
@ OPT_WS_UNBUFFERED
static const char * control_msg_format_to_str(enum webchan_control_msg_format value)
static int validate_uri_parameters(const char *uri_params)
static int webchan_write(struct ast_channel *ast, struct ast_frame *f)
Function called when we should write a frame to the channel.
static int webchan_hangup(struct ast_channel *ast)
static struct ast_channel_tech websocket_tech
#define HANGUP_CHANNEL
static struct ast_frame * webchan_read(struct ast_channel *ast)
#define websocket_request_hangup(_instance, _cause, _tech)
#define MEDIA_WEBSOCKET_CONNECTION_ID
#define WS_WEBSOCKET_FDNO
static int read_from_ws_and_queue(struct websocket_pvt *instance)
@ WEBCHAN_CONTROL_MSG_FORMAT_JSON
@ WEBCHAN_CONTROL_MSG_FORMAT_PLAIN
@ WEBCHAN_CONTROL_MSG_FORMAT_INVALID
static int handle_command(struct websocket_pvt *instance, char *buffer)
static int global_control_message_format_from_str(const struct aco_option *opt, struct ast_variable *var, void *obj)
static int webchan_send_dtmf_text(struct ast_channel *ast, char digit, unsigned int duration)
static struct ast_http_uri http_uri
static int reload_module(void)
#define GET_DRIVER_STATUS
static int set_channel_variables(struct websocket_pvt *instance)
@ WEBCHAN_MEDIA_DIRECTION_BOTH
@ WEBCHAN_MEDIA_DIRECTION_OUT
@ WEBCHAN_MEDIA_DIRECTION_IN
static int process_text_message(struct websocket_pvt *instance, char *payload, uint64_t payload_len)
static void websocket_destructor(void *data)
static int queue_frame_from_buffer(struct websocket_pvt *instance, char *buffer, size_t len)
Create a frame from buffer and append it to the frame queue.
#define WS_TIMER_FDNO
static struct ast_sorcery * sorcery
#define ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, direction)
#define START_MEDIA_BUFFERING
static int set_channel_timer(struct websocket_pvt *instance)
static struct ast_frame * create_frame_from_buffer(struct websocket_pvt *instance, char *buffer, size_t len)
#define QUEUE_LENGTH_XOFF_LEVEL
static const struct ast_app_option websocket_options[128]
#define PAUSE_MEDIA
#define create_event(_instance, _event,...)
Use this macro to create events passing in any event-specific parameters.
static struct ao2_container * instances
#define MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE
#define INCOMING_CONNECTION_ID
static struct websocket_pvt * websocket_new(const char *chan_name, const char *connection_id, struct ast_format *fmt)
#define REPORT_QUEUE_DRAINED
#define CONTINUE_MEDIA
#define STOP_MEDIA_BUFFERING
#define ERROR_ON_UNBUFFERED_MODE_RTN(instance, command)
static int load_module(void)
Function called when our module is loaded.
static int webchan_call(struct ast_channel *ast, const char *dest, int timeout)
static enum webchan_control_msg_format control_msg_format_from_str(const char *value)
static int process_binary_message(struct websocket_pvt *instance, char *payload, uint64_t payload_len)
static struct ast_websocket_server * ast_ws_server
#define SET_MEDIA_DIRECTION
static int unload_module(void)
Function called when our module is unloaded.
static int global_control_message_format_to_str(const void *obj, const intptr_t *args, char **buf)
#define MAX_TEXT_MESSAGE_LEN
static void incoming_ws_established_cb(struct ast_websocket *ast_ws_session, struct ast_variable *get_params, struct ast_variable *upgrade_headers)
#define QUEUE_LENGTH_MAX
static int websocket_handoff_to_channel(struct websocket_pvt *instance)
static struct ast_channel * webchan_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
static int load_config(void)
static int global_apply(const struct ast_sorcery *sorcery, void *obj)
static int queue_option_frame(struct websocket_pvt *instance, char *buffer)
@ OPT_ARG_WS_PASSTHROUGH
@ OPT_ARG_WS_URI_PARAM
@ OPT_ARG_WS_MEDIA_DIRECTION
@ OPT_ARG_WS_MSG_FORMAT
@ OPT_ARG_WS_CODEC
@ OPT_ARG_WS_NO_AUTO_ANSWER
@ OPT_ARG_WS_UNBUFFERED
@ OPT_ARG_ARRAY_SIZE
const char * ast_channel_name(const struct ast_channel *chan)
int ast_channel_tech_hangupcause(const struct ast_channel *chan)
void * ast_channel_tech_pvt(const struct ast_channel *chan)
void ast_channel_tech_hangupcause_set(struct ast_channel *chan, int value)
#define ast_channel_alloc(needqueue, state, cid_num, cid_name, acctcode, exten, context, assignedids, requestor, amaflag,...)
Create a channel structure.
Definition channel.h:1299
void ast_channel_nativeformats_set(struct ast_channel *chan, struct ast_format_cap *value)
int ast_channel_fdno(const struct ast_channel *chan)
@ AST_FLAG_DISABLE_DEVSTATE_CACHE
Definition channel.h:1049
void ast_channel_unregister(const struct ast_channel_tech *tech)
Unregister a channel technology.
Definition channel.c:571
int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
Queue a control frame without payload.
Definition channel.c:1289
struct ast_flags * ast_channel_flags(struct ast_channel *chan)
int ast_queue_frame(struct ast_channel *chan, struct ast_frame *f)
Queue one or more frames to a channel's frame queue.
Definition channel.c:1171
int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
Queue a hangup frame with hangupcause set.
Definition channel.c:1213
void ast_channel_set_rawreadformat(struct ast_channel *chan, struct ast_format *format)
void ast_channel_tech_pvt_set(struct ast_channel *chan, void *value)
void ast_channel_set_rawwriteformat(struct ast_channel *chan, struct ast_format *format)
void ast_channel_set_readformat(struct ast_channel *chan, struct ast_format *format)
int ast_channel_register(const struct ast_channel_tech *tech)
Register a channel technology (a new channel driver) Called by a channel module to register the kind ...
Definition channel.c:540
#define ast_channel_unref(c)
Decrease channel reference count.
Definition channel.h:3019
const char * ast_cause2str(int cause) attribute_pure
Gives the string form of a given cause code.
Definition channel.c:613
void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
Definition channel.c:2417
void ast_channel_internal_fd_clear(struct ast_channel *chan, int which)
void ast_channel_hangupcause_set(struct ast_channel *chan, int value)
void ast_channel_tech_set(struct ast_channel *chan, const struct ast_channel_tech *value)
#define ast_channel_unlock(chan)
Definition channel.h:2984
void ast_channel_set_writeformat(struct ast_channel *chan, struct ast_format *format)
@ AST_STATE_DOWN
@ AST_MEDIA_TYPE_UNKNOWN
Definition codec.h:31
@ OPT_NOOP_T
Type for a default handler that should do nothing.
char buf[BUFSIZE]
Definition eagi_proxy.c:66
struct ast_codec * ast_format_get_codec(const struct ast_format *format)
Get the codec associated with a format.
Definition format.c:324
unsigned int ast_format_get_minimum_bytes(const struct ast_format *format)
Get the minimum number of bytes expected in a frame for this format.
Definition format.c:374
unsigned int ast_format_get_sample_rate(const struct ast_format *format)
Get the sample rate of a media format.
Definition format.c:379
unsigned int ast_format_get_minimum_ms(const struct ast_format *format)
Get the minimum amount of media carried in this format.
Definition format.c:364
enum ast_format_cmp_res ast_format_cmp(const struct ast_format *format1, const struct ast_format *format2)
Compare two formats.
Definition format.c:201
@ AST_FORMAT_CMP_NOT_EQUAL
Definition format.h:38
const char * ast_format_get_name(const struct ast_format *format)
Get the name associated with a format.
Definition format.c:334
unsigned int ast_format_get_default_ms(const struct ast_format *format)
Get the default framing size (in milliseconds) for a format.
Definition format.c:359
#define ast_format_cache_get(name)
Retrieve a named format from the cache.
int ast_format_cap_append_by_type(struct ast_format_cap *cap, enum ast_media_type type)
Add all codecs Asterisk knows about for a specific type to the capabilities structure.
Definition format_cap.c:216
struct ast_format * ast_format_cap_get_format(const struct ast_format_cap *cap, int position)
Get the format at a specific index.
Definition format_cap.c:408
@ AST_FORMAT_CAP_FLAG_DEFAULT
Definition format_cap.h:38
#define ast_format_cap_append(cap, format, framing)
Add format capability to capabilities structure.
Definition format_cap.h:99
#define ast_format_cap_alloc(flags)
Allocate a new ast_format_cap structure.
Definition format_cap.h:49
static const char name[]
Definition format_mp3.c:68
direction
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
static int uuid(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition func_uuid.c:52
ast_http_method
HTTP Request methods known by Asterisk.
Definition http.h:58
void ast_http_uri_unlink(struct ast_http_uri *urihandler)
Unregister a URI handler.
Definition http.c:779
void ast_http_error(struct ast_tcptls_session_instance *ser, int status, const char *title, const char *text)
Send HTTP error message and close socket.
Definition http.c:722
int ast_http_uri_link(struct ast_http_uri *urihandler)
Register a URI handler.
Definition http.c:747
int AST_OPTIONAL_API_NAME() ast_websocket_write(struct ast_websocket *session, enum ast_websocket_opcode opcode, char *payload, uint64_t payload_size)
Construct and transmit a WebSocket frame.
ast_websocket_status_code
Websocket Status Codes from RFC-6455.
@ AST_WEBSOCKET_STATUS_UNSUPPORTED_DATA
@ AST_WEBSOCKET_STATUS_NORMAL
@ AST_WEBSOCKET_STATUS_GOING_AWAY
@ AST_WEBSOCKET_STATUS_INTERNAL_ERROR
int AST_OPTIONAL_API_NAME() ast_websocket_server_add_protocol2(struct ast_websocket_server *server, struct ast_websocket_protocol *protocol)
Add a sub-protocol handler to the given server.
int AST_OPTIONAL_API_NAME() ast_websocket_write_string(struct ast_websocket *ws, const char *buf)
Construct and transmit a WebSocket frame containing string data.
void AST_OPTIONAL_API_NAME() ast_websocket_reconstruct_enable(struct ast_websocket *session, size_t bytes)
Enable multi-frame reconstruction up to a certain number of bytes.
struct ast_sockaddr *AST_OPTIONAL_API_NAME() ast_websocket_remote_address(struct ast_websocket *session)
Get the remote address for a WebSocket connected session.
int AST_OPTIONAL_API_NAME() 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)
Callback suitable for use with a ast_http_uri.
ast_websocket_result
Result code for a websocket client.
@ WS_OK
int AST_OPTIONAL_API_NAME() ast_websocket_fd(struct ast_websocket *session)
Get the file descriptor for a WebSocket session.
#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT
Default websocket write timeout, in ms.
ast_websocket_opcode
WebSocket operation codes.
@ AST_WEBSOCKET_OPCODE_PING
@ AST_WEBSOCKET_OPCODE_PONG
@ AST_WEBSOCKET_OPCODE_CONTINUATION
@ AST_WEBSOCKET_OPCODE_BINARY
@ AST_WEBSOCKET_OPCODE_CLOSE
@ AST_WEBSOCKET_OPCODE_TEXT
int AST_OPTIONAL_API_NAME() ast_websocket_set_nonblock(struct ast_websocket *session)
Set the socket of a WebSocket session to be non-blocking.
const char *AST_OPTIONAL_API_NAME() ast_websocket_status_to_str(enum ast_websocket_status_code code)
Convert a websocket status code to a string.
ast_websocket_type
WebSocket connection/configuration types.
@ AST_WS_TYPE_CLIENT
@ AST_WS_TYPE_SERVER
struct ast_websocket_protocol *AST_OPTIONAL_API_NAME() ast_websocket_sub_protocol_alloc(const char *name)
Allocate a websocket sub-protocol instance.
int AST_OPTIONAL_API_NAME() ast_websocket_set_timeout(struct ast_websocket *session, int timeout)
Set the timeout on a non-blocking WebSocket session.
int AST_OPTIONAL_API_NAME() ast_websocket_read(struct ast_websocket *session, char **payload, uint64_t *payload_len, enum ast_websocket_opcode *opcode, int *fragmented)
Read a WebSocket frame and handle it.
int AST_OPTIONAL_API_NAME() ast_websocket_close(struct ast_websocket *session, uint16_t reason)
Close a WebSocket session by sending a message with the CLOSE opcode and an optional code.
struct ast_websocket_server *AST_OPTIONAL_API_NAME() ast_websocket_server_create(void)
Creates a ast_websocket_server.
void AST_OPTIONAL_API_NAME() ast_websocket_unref(struct ast_websocket *session)
Decrease the reference count for a WebSocket session.
const char *AST_OPTIONAL_API_NAME() ast_websocket_result_to_str(enum ast_websocket_result result)
Convert a websocket result code to a string.
#define AST_APP_ARG(name)
Define an application argument.
#define END_OPTIONS
#define AST_APP_OPTIONS(holder, options...)
Declares an array of options for an application.
#define AST_APP_OPTION_ARG(option, flagno, argno)
Declares an application option that accepts an argument.
#define AST_DECLARE_APP_ARGS(name, arglist)
Declare a structure to hold an application's arguments.
#define BEGIN_OPTIONS
#define AST_APP_OPTION(option, flagno)
Declares an application option that does not accept an argument.
#define AST_NONSTANDARD_APP_ARGS(args, parse, sep)
Performs the 'nonstandard' argument separation process for an application.
int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
Parses a string containing application options and sets flags/arguments.
Definition main/app.c:3067
const char * ast_variable_find_in_list(const struct ast_variable *list, const char *variable)
Gets the value of a variable from a variable list by name.
#define ast_variable_new(name, value, filename)
#define ast_variable_list_append(head, new_var)
void ast_variables_destroy(struct ast_variable *var)
Free variable list.
Definition extconf.c:1260
#define ast_frisolate(fr)
Makes a frame independent of any static storage.
void ast_frame_free(struct ast_frame *frame, int cache)
Frees a frame or list of frames.
Definition main/frame.c:176
#define ast_frfree(fr)
#define AST_FRAME_SET_BUFFER(fr, _base, _ofs, _datalen)
@ AST_FRAME_CONTROL
@ AST_CONTROL_ANSWER
@ AST_CONTROL_OPTION
struct ast_frame ast_null_frame
Definition main/frame.c:79
#define ast_debug(level,...)
Log a DEBUG message.
#define LOG_ERROR
#define LOG_WARNING
#define ast_json_object_string_get(object, key)
Get a string field from a JSON object.
Definition json.h:600
void ast_json_unref(struct ast_json *value)
Decrease refcount on value. If refcount reaches zero, value is freed.
Definition json.c:73
struct ast_json * ast_json_load_buf(const char *buffer, size_t buflen, struct ast_json_error *error)
Parse buffer with known length into a JSON object or array.
Definition json.c:585
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
#define AST_LIST_LOCK(head)
Locks a list.
Definition linkedlists.h:40
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
#define SCOPED_AO2WRLOCK(varname, obj)
scoped lock specialization for ao2 write locks.
Definition lock.h:621
#define SCOPED_LOCK(varname, lock, lockfunc, unlockfunc)
Scoped Locks.
Definition lock.h:590
int errno
@ AST_MODFLAG_LOAD_ORDER
Definition module.h:331
#define AST_MODULE_INFO(keystr, flags_to_set, desc, fields...)
Definition module.h:557
@ AST_MODPRI_CHANNEL_DRIVER
Definition module.h:341
@ AST_MODULE_SUPPORT_CORE
Definition module.h:121
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition module.h:46
@ AST_MODULE_LOAD_SUCCESS
Definition module.h:70
@ AST_MODULE_LOAD_DECLINE
Module has failed to load, may be in an inconsistent state.
Definition module.h:78
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition netsock2.h:256
int pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
Add a variable to the channel variable stack, removing the most recently set value for the same name.
static int reload(void)
const char * method
Definition res_pjsip.c:1277
static struct @523 args
#define NULL
Definition resample.c:96
#define ast_sorcery_unref(sorcery)
Decrease the reference count of a sorcery structure.
Definition sorcery.h:1500
#define ast_sorcery_object_field_register_nodoc(sorcery, type, name, default_val, opt_type, flags,...)
Register a field within an object without documentation.
Definition sorcery.h:987
#define ast_sorcery_register_cust(object, option, def_value)
Register a custom field within an object.
Definition sorcery.h:1767
void ast_sorcery_load(const struct ast_sorcery *sorcery)
Inform any wizards to load persistent objects.
Definition sorcery.c:1441
void * ast_sorcery_retrieve_by_id(const struct ast_sorcery *sorcery, const char *type, const char *id)
Retrieve an object using its unique identifier.
Definition sorcery.c:1917
#define ast_sorcery_object_register(sorcery, type, alloc, transform, apply)
Register an object type.
Definition sorcery.h:837
void ast_sorcery_reload(const struct ast_sorcery *sorcery)
Inform any wizards to reload persistent objects.
Definition sorcery.c:1472
void * ast_sorcery_generic_alloc(size_t size, ao2_destructor_fn destructor)
Allocate a generic sorcery capable object.
Definition sorcery.c:1792
#define ast_sorcery_register_int(object, structure, option, field, def_value)
Register an int field as type OPT_INT_T within an object.
Definition sorcery.h:1710
#define ast_sorcery_apply_default(sorcery, type, name, data)
Definition sorcery.h:476
#define ast_sorcery_open()
Open a new sorcery structure.
Definition sorcery.h:406
int ast_strings_equal(const char *str1, const char *str2)
Compare strings for equality checking for NULL.
Definition strings.c:238
static force_inline int attribute_pure ast_strlen_zero(const char *s)
Definition strings.h:65
char * ast_strip(char *s)
Strip leading/trailing whitespace from a string.
Definition strings.h:223
char * ast_strsep(char **s, const char sep, uint32_t flags)
Act like strsep but ignore separators inside quotes.
Definition utils.c:1869
Structure to pass both assignedid values to channel drivers.
Definition channel.h:606
struct ast_format_cap * capabilities
Definition channel.h:652
Main Channel structure associated with a channel.
const char * data
unsigned int minimum_bytes
Length in bytes of the data payload of a minimum_ms frame.
Definition codec.h:60
unsigned int default_ms
Default length of media carried (in milliseconds) in a frame.
Definition codec.h:58
int(* samples_count)(struct ast_frame *frame)
Retrieve the number of samples in a frame.
Definition codec.h:68
unsigned int minimum_ms
Minimum length of media that can be carried (in milliseconds) in a frame.
Definition codec.h:54
Structure used to handle boolean flags.
Definition utils.h:220
Format capabilities structure, holds formats + preference order + etc.
Definition format_cap.c:54
Definition of a media format.
Definition format.c:43
struct ast_format * format
Data structure associated with a single frame of data.
struct ast_frame_subclass subclass
enum ast_frame_type frametype
union ast_frame::@237 data
Definition of a URI handler.
Definition http.h:102
ast_http_callback callback
Definition http.h:107
void * data
Definition http.h:116
JSON parsing error information.
Definition json.h:887
Abstract JSON element (object, array, string, int, ...).
Socket address structure.
Definition netsock2.h:97
Full structure for sorcery.
Definition sorcery.c:231
describes a server instance
Definition tcptls.h:151
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
A websocket protocol implementation.
ast_websocket_callback session_established
Callback called when a new session is established. Mandatory.
Structure definition for session.
char connection_id[0]
The name of the module owning this sorcery instance.
enum webchan_control_msg_format control_msg_format
char connection_id[0]
struct ast_format * native_format
struct ast_channel * channel
enum webchan_control_msg_format control_msg_format
struct websocket_pvt::@141 frame_queue
enum ast_websocket_type type
struct ast_timer * timer
struct ast_codec * native_codec
struct ast_websocket_client * client
struct ast_websocket * websocket
static struct aco_type global
static struct test_options options
void ast_timer_close(struct ast_timer *handle)
Close an opened timing handle.
Definition timing.c:154
int ast_timer_ack(const struct ast_timer *handle, unsigned int quantity)
Acknowledge a timer event.
Definition timing.c:171
int ast_timer_set_rate(const struct ast_timer *handle, unsigned int rate)
Set the timing tick rate.
Definition timing.c:166
enum ast_timer_event ast_timer_get_event(const struct ast_timer *handle)
Retrieve timing event.
Definition timing.c:186
struct ast_timer * ast_timer_open(void)
Open a timer.
Definition timing.c:122
@ AST_TIMING_EVENT_EXPIRED
Definition timing.h:58
int ast_timer_fd(const struct ast_timer *handle)
Get a poll()-able file descriptor for a timer.
Definition timing.c:161
#define ast_test_flag(p, flag)
Definition utils.h:64
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition utils.h:981
#define MIN(a, b)
Definition utils.h:252
#define ast_set_flag(p, flag)
Definition utils.h:71
int ast_uri_verify_encoded(const char *string)
Verify if a string is valid as a URI component.
Definition utils.c:779
#define AST_UUID_STR_LEN
Definition uuid.h:27
char * ast_uuid_generate_str(char *buf, size_t size)
Generate a UUID string.
Definition uuid.c:141
void ast_websocket_client_add_uri_params(struct ast_websocket_client *wc, const char *uri_params)
Add additional parameters to the URI.
struct ast_websocket_client * ast_websocket_client_retrieve_by_id(const char *id)
Retrieve a websocket client object by ID.
struct ast_websocket * ast_websocket_client_connect(struct ast_websocket_client *wc, void *lock_obj, const char *display_name, enum ast_websocket_result *result)
Connect to a websocket server using the configured authentication, retry and TLS options.

◆ ERROR_ON_INVALID_MEDIA_DIRECTION_RTN

#define ERROR_ON_INVALID_MEDIA_DIRECTION_RTN (   instance,
  command,
  direction 
)

Definition at line 772 of file chan_websocket.c.

773 { \
774 if (instance->media_direction == direction) { \
775 send_event(instance, ERROR, "%s not supported while media direction " \
776 "is '%s'", command, websocket_media_direction_map[direction]); \
777 ast_debug(4, "%s: WebSocket media direction is '%s'. Ignoring %s command.\n", \
778 ast_channel_name(instance->channel), websocket_media_direction_map[direction], command); \
779 return 0; \
780 } \
781})
static const char * websocket_media_direction_map[]

◆ ERROR_ON_PASSTHROUGH_MODE_RTN

#define ERROR_ON_PASSTHROUGH_MODE_RTN (   instance,
  command 
)

Definition at line 752 of file chan_websocket.c.

753 { \
754 if (instance->passthrough) { \
755 send_event(instance, ERROR, "%s not supported in passthrough mode", command); \
756 ast_debug(4, "%s: WebSocket in passthrough mode. Ignoring %s command.\n", \
757 ast_channel_name(instance->channel), command); \
758 return 0; \
759 } \
760})

◆ ERROR_ON_UNBUFFERED_MODE_RTN

#define ERROR_ON_UNBUFFERED_MODE_RTN (   instance,
  command 
)

Definition at line 762 of file chan_websocket.c.

763 { \
764 if (instance->unbuffered) { \
765 send_event(instance, ERROR, "%s not supported in unbuffered mode", command); \
766 ast_debug(4, "%s: WebSocket in unbuffered mode. Ignoring %s command.\n", \
767 ast_channel_name(instance->channel), command); \
768 return 0; \
769 } \
770})

◆ FLUSH_MEDIA

#define FLUSH_MEDIA   "FLUSH_MEDIA"

Definition at line 137 of file chan_websocket.c.

◆ GET_DRIVER_STATUS

#define GET_DRIVER_STATUS   "GET_STATUS"

Definition at line 138 of file chan_websocket.c.

◆ HANGUP_CHANNEL

#define HANGUP_CHANNEL   "HANGUP"

Definition at line 133 of file chan_websocket.c.

◆ INCOMING_CONNECTION_ID

#define INCOMING_CONNECTION_ID   "INCOMING"

Definition at line 130 of file chan_websocket.c.

◆ MARK_MEDIA

#define MARK_MEDIA   "MARK_MEDIA"

Definition at line 136 of file chan_websocket.c.

◆ MAX_TEXT_MESSAGE_LEN

#define MAX_TEXT_MESSAGE_LEN   MIN(128, (AST_WEBSOCKET_MAX_RX_PAYLOAD_SIZE - 1))

Definition at line 147 of file chan_websocket.c.

◆ MEDIA_WEBSOCKET_CONNECTION_ID

#define MEDIA_WEBSOCKET_CONNECTION_ID   "MEDIA_WEBSOCKET_CONNECTION_ID"

Definition at line 129 of file chan_websocket.c.

◆ MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE

#define MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE   "MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE"

Definition at line 128 of file chan_websocket.c.

◆ PAUSE_MEDIA

#define PAUSE_MEDIA   "PAUSE_MEDIA"

Definition at line 140 of file chan_websocket.c.

◆ QUEUE_FRAME_DROPPED_FULL

#define QUEUE_FRAME_DROPPED_FULL   1

Result of queue_frame_from_buffer() when the frame was dropped because the queue is already at QUEUE_LENGTH_MAX.

This is not an error; the caller should stop queueing frames from the current message but otherwise carry on.

Definition at line 678 of file chan_websocket.c.

◆ QUEUE_LENGTH_MAX

#define QUEUE_LENGTH_MAX   1000

Definition at line 144 of file chan_websocket.c.

◆ QUEUE_LENGTH_XOFF_LEVEL

#define QUEUE_LENGTH_XOFF_LEVEL   900

Definition at line 145 of file chan_websocket.c.

◆ QUEUE_LENGTH_XON_LEVEL

#define QUEUE_LENGTH_XON_LEVEL   800

Definition at line 146 of file chan_websocket.c.

◆ REPORT_QUEUE_DRAINED

#define REPORT_QUEUE_DRAINED   "REPORT_QUEUE_DRAINED"

Definition at line 139 of file chan_websocket.c.

◆ send_event

#define send_event (   _instance,
  _event,
  ... 
)

Use this macro to create and send events passing in any event-specific parameters.

Definition at line 448 of file chan_websocket.c.

449 { \
450 int _res = -1; \
451 char *_payload = _create_event_ ## _event(_instance, ##__VA_ARGS__); \
452 if (_payload && _instance->websocket) { \
453 _res = ast_websocket_write_string(_instance->websocket, _payload); \
454 if (_res != 0) { \
455 ast_log(LOG_ERROR, "%s: Unable to send event %s\n", \
456 ast_channel_name(instance->channel), _payload); \
457 } else { \
458 ast_debug(3, "%s: Sent %s\n", \
459 ast_channel_name(instance->channel), _payload); \
460 }\
461 ast_free(_payload); \
462 } \
463 (_res); \
464})

◆ SET_MEDIA_DIRECTION

#define SET_MEDIA_DIRECTION   "SET_MEDIA_DIRECTION"

Definition at line 142 of file chan_websocket.c.

◆ START_MEDIA_BUFFERING

#define START_MEDIA_BUFFERING   "START_MEDIA_BUFFERING"

Definition at line 134 of file chan_websocket.c.

◆ STOP_MEDIA_BUFFERING

#define STOP_MEDIA_BUFFERING   "STOP_MEDIA_BUFFERING"

Definition at line 135 of file chan_websocket.c.

◆ websocket_request_hangup

#define websocket_request_hangup (   _instance,
  _cause,
  _tech 
)     _websocket_request_hangup(_instance, _cause, _tech, __LINE__, __FUNCTION__)

Definition at line 161 of file chan_websocket.c.

◆ WS_TIMER_FDNO

#define WS_TIMER_FDNO   (AST_EXTENDED_FDS + 1)

Definition at line 125 of file chan_websocket.c.

◆ WS_WEBSOCKET_FDNO

#define WS_WEBSOCKET_FDNO   (AST_EXTENDED_FDS + 2)

Definition at line 126 of file chan_websocket.c.

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
OPT_WS_CODEC 
OPT_WS_NO_AUTO_ANSWER 
OPT_WS_URI_PARAM 
OPT_WS_PASSTHROUGH 
OPT_WS_MSG_FORMAT 
OPT_WS_MEDIA_DIRECTION 
OPT_WS_UNBUFFERED 

Definition at line 1669 of file chan_websocket.c.

1669 {
1670 OPT_WS_CODEC = (1 << 0),
1671 OPT_WS_NO_AUTO_ANSWER = (1 << 1),
1672 OPT_WS_URI_PARAM = (1 << 2),
1673 OPT_WS_PASSTHROUGH = (1 << 3),
1674 OPT_WS_MSG_FORMAT = (1 << 4),
1675 OPT_WS_MEDIA_DIRECTION = (1 << 5),
1676 OPT_WS_UNBUFFERED = (1 << 6),
1677};

◆ anonymous enum

anonymous enum
Enumerator
OPT_ARG_WS_CODEC 
OPT_ARG_WS_NO_AUTO_ANSWER 
OPT_ARG_WS_URI_PARAM 
OPT_ARG_WS_PASSTHROUGH 
OPT_ARG_WS_MSG_FORMAT 
OPT_ARG_WS_MEDIA_DIRECTION 
OPT_ARG_WS_UNBUFFERED 
OPT_ARG_ARRAY_SIZE 

Definition at line 1679 of file chan_websocket.c.

◆ webchan_control_msg_format

Enumerator
WEBCHAN_CONTROL_MSG_FORMAT_PLAIN 
WEBCHAN_CONTROL_MSG_FORMAT_JSON 
WEBCHAN_CONTROL_MSG_FORMAT_INVALID 

Definition at line 56 of file chan_websocket.c.

◆ webchan_media_direction

Enumerator
WEBCHAN_MEDIA_DIRECTION_BOTH 
WEBCHAN_MEDIA_DIRECTION_OUT 
WEBCHAN_MEDIA_DIRECTION_IN 

Definition at line 75 of file chan_websocket.c.

Function Documentation

◆ __reg_module()

static void __reg_module ( void  )
static

Definition at line 2286 of file chan_websocket.c.

◆ __unreg_module()

static void __unreg_module ( void  )
static

Definition at line 2286 of file chan_websocket.c.

◆ _create_event_DTMF_END()

static char * _create_event_DTMF_END ( struct websocket_pvt *  instance,
const char  digit 
)
static

Definition at line 334 of file chan_websocket.c.

336{
337 char *payload = NULL;
339 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s#}",
340 "event", "DTMF_END",
341 "channel_id", ast_channel_uniqueid(instance->channel),
342 "digit", &digit, 1
343 );
344 if (!msg) {
345 return NULL;
346 }
348 ast_json_unref(msg);
349 } else {
350 ast_asprintf(&payload, "%s digit:%c channel_id:%s",
351 "DTMF_END", digit, ast_channel_uniqueid(instance->channel));
352 }
353
354 return payload;
355}
const char * ast_channel_uniqueid(const struct ast_channel *chan)
struct ast_json * ast_json_pack(char const *format,...)
Helper for creating complex JSON values.
Definition json.c:612
@ AST_JSON_COMPACT
Definition json.h:793
char * ast_json_dump_string_format(struct ast_json *root, enum ast_json_encoding_format format)
Encode a JSON value to a string.
Definition json.c:484

References ast_asprintf, ast_channel_uniqueid(), AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), websocket_pvt::channel, websocket_pvt::control_msg_format, digit, NULL, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _create_event_ERROR()

static char * _create_event_ERROR ( struct websocket_pvt *  instance,
const char *  format,
  ... 
)
static

Definition at line 402 of file chan_websocket.c.

404{
405 char *payload = NULL;
406 char *error_text = NULL;
407 va_list ap;
408 int res = 0;
409
410 va_start(ap, format);
411 res = ast_vasprintf(&error_text, format, ap);
412 va_end(ap);
413 if (res < 0 || !error_text) {
414 return NULL;
415 }
416
418 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s}",
419 "event", "ERROR",
420 "channel_id", ast_channel_uniqueid(instance->channel),
421 "error_text", error_text);
422 ast_free(error_text);
423 if (!msg) {
424 return NULL;
425 }
427 ast_json_unref(msg);
428 } else {
429 ast_asprintf(&payload, "%s channel_id:%s error_text:%s",
430 "ERROR", ast_channel_uniqueid(instance->channel), error_text);
431 ast_free(error_text);
432 }
433
434 return payload;
435}
#define ast_vasprintf(ret, fmt, ap)
A wrapper for vasprintf()
Definition astmm.h:278

References ast_asprintf, ast_channel_uniqueid(), ast_free, AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), ast_vasprintf, NULL, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _create_event_MEDIA_BUFFERING_COMPLETED()

static char * _create_event_MEDIA_BUFFERING_COMPLETED ( struct websocket_pvt *  instance,
const char *  id 
)
static

Definition at line 274 of file chan_websocket.c.

276{
277 char *payload = NULL;
279 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s}",
280 "event", "MEDIA_BUFFERING_COMPLETED",
281 "channel_id", ast_channel_uniqueid(instance->channel),
282 "correlation_id", S_OR(id, "")
283 );
284 if (!msg) {
285 return NULL;
286 }
288 ast_json_unref(msg);
289 } else {
290 ast_asprintf(&payload, "%s%s%s",
291 "MEDIA_BUFFERING_COMPLETED",
292 S_COR(id, " ",""), S_OR(id, ""));
293
294 }
295
296 return payload;
297}
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one.
Definition strings.h:80
#define S_COR(a, b, c)
returns the equivalent of logic or for strings, with an additional boolean check: second one if not e...
Definition strings.h:87

References ast_asprintf, ast_channel_uniqueid(), AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), websocket_pvt::channel, websocket_pvt::control_msg_format, NULL, S_COR, S_OR, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _create_event_MEDIA_MARK_PROCESSED()

static char * _create_event_MEDIA_MARK_PROCESSED ( struct websocket_pvt *  instance,
const char *  id 
)
static

Definition at line 304 of file chan_websocket.c.

306{
307 char *payload = NULL;
309 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s}",
310 "event", "MEDIA_MARK_PROCESSED",
311 "channel_id", ast_channel_uniqueid(instance->channel),
312 "correlation_id", S_OR(id, "")
313 );
314 if (!msg) {
315 return NULL;
316 }
318 ast_json_unref(msg);
319 } else {
320 ast_asprintf(&payload, "%s%s%s",
321 "MEDIA_MARK_PROCESSED",
322 S_COR(id, " ",""), S_OR(id, ""));
323
324 }
325
326 return payload;
327}

References ast_asprintf, ast_channel_uniqueid(), AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), websocket_pvt::channel, websocket_pvt::control_msg_format, NULL, S_COR, S_OR, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _create_event_MEDIA_START()

static char * _create_event_MEDIA_START ( struct websocket_pvt *  instance)
static

Definition at line 229 of file chan_websocket.c.

230{
231 char *payload = NULL;
232
234 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s, s:s, s:s, s:i, s:i, s:b, s:b, s:o }",
235 "event", "MEDIA_START",
236 "connection_id", instance->connection_id,
237 "channel", ast_channel_name(instance->channel),
238 "channel_id", ast_channel_uniqueid(instance->channel),
239 "format", ast_format_get_name(instance->native_format),
240 "optimal_frame_size", instance->optimal_frame_size,
241 "ptime", instance->native_codec->default_ms,
242 "passthrough", instance->passthrough,
243 "unbuffered", instance->unbuffered,
244 "channel_variables", ast_json_channel_vars(ast_channel_varshead(
245 instance->channel))
246 );
247 if (!msg) {
248 return NULL;
249 }
251 ast_json_unref(msg);
252 } else {
253 ast_asprintf(&payload, "%s %s:%s %s:%s %s:%s %s:%s %s:%d %s:%d %s:%s %s:%s",
254 "MEDIA_START",
255 "connection_id", instance->connection_id,
256 "channel", ast_channel_name(instance->channel),
257 "channel_id", ast_channel_uniqueid(instance->channel),
258 "format", ast_format_get_name(instance->native_format),
259 "optimal_frame_size", instance->optimal_frame_size,
260 "ptime", instance->native_codec->default_ms,
261 "passthrough", instance->passthrough ? "true" : "false",
262 "unbuffered", instance->unbuffered ? "true" : "false"
263 );
264 }
265
266 return payload;
267}
struct varshead * ast_channel_varshead(struct ast_channel *chan)
struct ast_json * ast_json_channel_vars(struct varshead *channelvars)
Construct a JSON object from a ast_var_t list.
Definition json.c:941

References ast_asprintf, ast_channel_name(), ast_channel_uniqueid(), ast_channel_varshead(), ast_format_get_name(), ast_json_channel_vars(), AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), websocket_pvt::channel, websocket_pvt::connection_id, websocket_pvt::control_msg_format, ast_codec::default_ms, websocket_pvt::native_codec, websocket_pvt::native_format, NULL, websocket_pvt::optimal_frame_size, websocket_pvt::passthrough, websocket_pvt::unbuffered, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _create_event_nodata()

static char * _create_event_nodata ( struct websocket_pvt *  instance,
char *  event 
)
static

Definition at line 201 of file chan_websocket.c.

202{
203 char *payload = NULL;
205 struct ast_json * msg = ast_json_pack("{ s:s s:s }",
206 "event", event,
207 "channel_id", ast_channel_uniqueid(instance->channel));
208 if (!msg) {
209 return NULL;
210 }
212 ast_json_unref(msg);
213 } else {
214 payload = ast_strdup(event);
215 }
216
217 return payload;
218}

References ast_channel_uniqueid(), AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), ast_strdup, websocket_pvt::channel, websocket_pvt::control_msg_format, NULL, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _create_event_STATUS()

static char * _create_event_STATUS ( struct websocket_pvt *  instance)
static

Definition at line 362 of file chan_websocket.c.

363{
364 char *payload = NULL;
365
367 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:i, s:i, s:i, s:b, s:b, s:b }",
368 "event", "STATUS",
369 "channel_id", ast_channel_uniqueid(instance->channel),
370 "queue_length", instance->frame_queue_length,
371 "xon_level", QUEUE_LENGTH_XON_LEVEL,
372 "xoff_level", QUEUE_LENGTH_XOFF_LEVEL,
373 "queue_full", instance->queue_full,
374 "bulk_media", instance->bulk_media_in_progress,
375 "media_paused", instance->queue_paused
376 );
377 if (!msg) {
378 return NULL;
379 }
381 ast_json_unref(msg);
382 } else {
383 ast_asprintf(&payload, "%s channel_id:%s queue_length:%d xon_level:%d xoff_level:%d queue_full:%s bulk_media:%s media_paused:%s",
384 "STATUS",
385 ast_channel_uniqueid(instance->channel),
388 S_COR(instance->queue_full, "true", "false"),
389 S_COR(instance->bulk_media_in_progress, "true", "false"),
390 S_COR(instance->queue_paused, "true", "false")
391 );
392 }
393
394 return payload;
395}

References ast_asprintf, ast_channel_uniqueid(), AST_JSON_COMPACT, ast_json_dump_string_format(), ast_json_pack(), ast_json_unref(), websocket_pvt::bulk_media_in_progress, websocket_pvt::channel, websocket_pvt::control_msg_format, websocket_pvt::frame_queue_length, NULL, websocket_pvt::queue_full, QUEUE_LENGTH_XOFF_LEVEL, QUEUE_LENGTH_XON_LEVEL, websocket_pvt::queue_paused, S_COR, and WEBCHAN_CONTROL_MSG_FORMAT_JSON.

◆ _websocket_request_hangup()

static void _websocket_request_hangup ( struct websocket_pvt *  instance,
int  ast_cause,
enum ast_websocket_status_code  tech_cause,
int  line,
const char *  function 
)
static

Definition at line 1311 of file chan_websocket.c.

1313{
1314 if (!instance || !instance->channel) {
1315 return;
1316 }
1317 ast_debug(3, "%s:%s: Hangup requested from %s line %d. cause: %s(%d) tech_cause: %s(%d)",
1318 ast_channel_name(instance->channel), instance->remote_addr,
1319 function, line,
1320 ast_cause2str(ast_cause), ast_cause, ast_websocket_status_to_str(tech_cause), tech_cause);
1321
1322 if (tech_cause) {
1323 ast_channel_tech_hangupcause_set(instance->channel, tech_cause);
1324 }
1325 ast_queue_hangup_with_cause(instance->channel, ast_cause);
1326}

References ast_cause2str(), ast_channel_name(), ast_channel_tech_hangupcause_set(), ast_debug, ast_queue_hangup_with_cause(), ast_websocket_status_to_str(), websocket_pvt::channel, and websocket_pvt::remote_addr.

◆ AST_MODULE_SELF_SYM()

struct ast_module * AST_MODULE_SELF_SYM ( void  )

Definition at line 2286 of file chan_websocket.c.

◆ control_msg_format_from_str()

static enum webchan_control_msg_format control_msg_format_from_str ( const char *  value)
static

◆ control_msg_format_to_str()

static const char * control_msg_format_to_str ( enum webchan_control_msg_format  value)
static

Definition at line 188 of file chan_websocket.c.

189{
191 return NULL;
192 }
193 return msg_format_map[value];
194}
#define ARRAY_IN_BOUNDS(v, a)
Checks to see if value is within the bounds of the given array.
Definition utils.h:727

References ARRAY_IN_BOUNDS, msg_format_map, NULL, and value.

Referenced by global_apply(), and global_control_message_format_to_str().

◆ create_frame_from_buffer()

static struct ast_frame * create_frame_from_buffer ( struct websocket_pvt *  instance,
char *  buffer,
size_t  len 
)
static

Definition at line 575 of file chan_websocket.c.

577{
578 struct ast_frame fr = { 0, };
579 struct ast_frame *duped_frame = NULL;
580
581 AST_FRAME_SET_BUFFER(&fr, buffer, 0, len);
583 fr.subclass.format = instance->native_format;
584 if (instance->native_codec->samples_count) {
585 fr.samples = instance->native_codec->samples_count(&fr);
586 }
587
588 duped_frame = ast_frisolate(&fr);
589 if (!duped_frame) {
590 ast_log(LOG_WARNING, "%s: Failed to isolate frame\n",
591 ast_channel_name(instance->channel));
592 return NULL;
593 }
594
595 return duped_frame;
596}

References ast_channel_name(), AST_FRAME_SET_BUFFER, AST_FRAME_VOICE, ast_frisolate, ast_log, websocket_pvt::channel, ast_frame_subclass::format, ast_frame::frametype, len(), LOG_WARNING, websocket_pvt::native_codec, websocket_pvt::native_format, NULL, ast_frame::samples, ast_codec::samples_count, and ast_frame::subclass.

Referenced by queue_frame_from_buffer(), and webchan_read().

◆ dequeue_frame()

static struct ast_frame * dequeue_frame ( struct websocket_pvt *  instance)
static

Definition at line 474 of file chan_websocket.c.

475{
476 struct ast_frame *queued_frame = NULL;
477 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
479
480 /*
481 * If the queue is paused, don't read a frame.
482 */
483 if (instance->queue_paused) {
484 return NULL;
485 }
486
487 /*
488 * We need to check if we need to send an XON before anything
489 * else because there are multiple escape paths in this function
490 * and we don't want to accidentally keep the queue in a "full"
491 * state.
492 */
493 if (instance->queue_full && instance->frame_queue_length < QUEUE_LENGTH_XON_LEVEL) {
494 instance->queue_full = 0;
495 ast_debug(4, "%s: WebSocket sending MEDIA_XON\n",
496 ast_channel_name(instance->channel));
497 send_event(instance, MEDIA_XON);
498 }
499
500 queued_frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list);
501
502 /*
503 * If there are no frames in the queue, we need to return NULL.
504 * We also need to send the QUEUE_DRAINED notification if we
505 * were requested to do so.
506 */
507 if (!queued_frame) {
508 if (instance->report_queue_drained) {
509 instance->report_queue_drained = 0;
510 ast_debug(4, "%s: WebSocket sending QUEUE_DRAINED\n",
511 ast_channel_name(instance->channel));
512 send_event(instance, QUEUE_DRAINED);
513 }
514 return NULL;
515 }
516
517 /*
518 * The only way a control frame could be present here is as
519 * a result of us calling queue_option_frame() in response
520 * to an incoming TEXT command from the websocket.
521 * We'll be safe and make sure it's a AST_CONTROL_OPTION
522 * frame anyway.
523 *
524 * It's quite possible that there are multiple control frames
525 * in a row in the queue so we need to process consecutive ones
526 * immediately.
527 *
528 * In any case, processing a control frame MUST not use up
529 * a media timeslot so after all control frames have been
530 * processed, we need to read an audio frame and process it.
531 */
532 while (queued_frame && queued_frame->frametype == AST_FRAME_CONTROL) {
533 if (queued_frame->subclass.integer == AST_CONTROL_OPTION) {
534 /*
535 * We just need to send the data to the websocket.
536 * The data should already be NULL terminated.
537 */
538 int res = ast_websocket_write_string(instance->websocket,
539 queued_frame->data.ptr);
540 if (res != 0) {
541 ast_log(LOG_ERROR, "%s: Unable to send event %s\n",
542 ast_channel_name(instance->channel), (char *)queued_frame->data.ptr);
543 } else {
544 ast_debug(4, "%s: Sent %s\n",
545 ast_channel_name(instance->channel), (char *)queued_frame->data.ptr);
546 }
547 }
548 /*
549 * We do NOT send these to the core so we need to free
550 * the frame and grab the next one. If it's also a
551 * control frame, we need to process it otherwise
552 * continue down in the function.
553 */
554 ast_frame_free(queued_frame, 0);
555 queued_frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list);
556 /*
557 * Jut FYI... We didn't bump the queue length when we added the control
558 * frames so we don't need to decrement it here.
559 */
560 }
561
562 /*
563 * If, after reading all control frames, there are no frames
564 * left in the queue, we need to return NULL.
565 */
566 if (!queued_frame) {
567 return NULL;
568 }
569
570 instance->frame_queue_length--;
571
572 return queued_frame;
573}

References ast_channel_name(), AST_CONTROL_OPTION, ast_debug, AST_FRAME_CONTROL, ast_frame_free(), AST_LIST_LOCK, AST_LIST_REMOVE_HEAD, AST_LIST_UNLOCK, ast_log, ast_websocket_write_string(), websocket_pvt::channel, ast_frame::data, websocket_pvt::frame_queue, websocket_pvt::frame_queue_length, ast_frame::frametype, ast_frame_subclass::integer, LOG_ERROR, NULL, ast_frame::ptr, websocket_pvt::queue_full, QUEUE_LENGTH_XON_LEVEL, websocket_pvt::queue_paused, websocket_pvt::report_queue_drained, SCOPED_LOCK, send_event, ast_frame::subclass, and websocket_pvt::websocket.

Referenced by webchan_read().

◆ global_alloc()

static void * global_alloc ( const char *  name)
static

Definition at line 2144 of file chan_websocket.c.

2145{
2147 sizeof(*cfg), NULL);
2148
2149 if (!cfg) {
2150 return NULL;
2151 }
2152
2153 return cfg;
2154}

References ast_sorcery_generic_alloc(), and NULL.

Referenced by load_config().

◆ global_apply()

static int global_apply ( const struct ast_sorcery *  sorcery,
void *  obj 
)
static

Definition at line 2156 of file chan_websocket.c.

2157{
2158 struct webchan_conf_global *cfg = obj;
2159
2160 ast_debug(1, "control_msg_format: %s\n",
2162
2163 if (cfg->write_timeout <= 0) {
2164 ast_log(LOG_WARNING, "The write_timeout parameter must be > 0\n");
2165 return -1;
2166 }
2167
2168 return 0;
2169}

References ast_debug, ast_log, webchan_conf_global::control_msg_format, control_msg_format_to_str(), LOG_WARNING, and webchan_conf_global::write_timeout.

Referenced by load_config().

◆ global_control_message_format_from_str()

static int global_control_message_format_from_str ( const struct aco_option *  opt,
struct ast_variable *  var,
void *  obj 
)
static

Definition at line 2118 of file chan_websocket.c.

2120{
2121 struct webchan_conf_global *cfg = obj;
2122
2124
2126 ast_log(LOG_ERROR, "chan_websocket.conf: Invalid value '%s' for "
2127 "control_mesage_format. Must be 'plain-text' or 'json'\n",
2128 var->value);
2129 return -1;
2130 }
2131
2132 return 0;
2133}

References ast_log, webchan_conf_global::control_msg_format, control_msg_format_from_str(), LOG_ERROR, var, and WEBCHAN_CONTROL_MSG_FORMAT_INVALID.

◆ global_control_message_format_to_str()

static int global_control_message_format_to_str ( const void *  obj,
const intptr_t *  args,
char **  buf 
)
static

Definition at line 2135 of file chan_websocket.c.

2136{
2137 const struct webchan_conf_global *cfg = obj;
2138
2140
2141 return 0;
2142}

References ast_strdup, buf, webchan_conf_global::control_msg_format, and control_msg_format_to_str().

◆ handle_command()

static int handle_command ( struct websocket_pvt *  instance,
char *  buffer 
)
static

Definition at line 792 of file chan_websocket.c.

793{
794 int res = 0;
795 RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
796 const char *command = NULL;
797 char *data = NULL;
798
800 struct ast_json_error json_error;
801
802 json = ast_json_load_buf(buffer, strlen(buffer), &json_error);
803 if (!json) {
804 send_event(instance, ERROR, "Unable to parse JSON command");
805 return -1;
806 }
807 command = ast_json_object_string_get(json, "command");
808 } else {
809 command = buffer;
810 data = strchr(buffer, ' ');
811 if (data) {
812 *data = '\0';
813 data++;
814 }
815 }
816
817 if (ast_strings_equal(command, ANSWER_CHANNEL)) {
819
820 } else if (ast_strings_equal(command, HANGUP_CHANNEL)) {
822
823 } else if (ast_strings_equal(command, START_MEDIA_BUFFERING)) {
824 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
826 if (instance->bulk_media_in_progress) {
827 send_event(instance, ERROR, "START_MEDIA_BUFFERING can't be called when media buffering is already active.\n");
828 return 0;
829 }
830
831 AST_LIST_LOCK(&instance->frame_queue);
832 instance->bulk_media_in_progress = 1;
833 instance->last_unbuffered = instance->unbuffered;
834 instance->unbuffered = 0;
835 AST_LIST_UNLOCK(&instance->frame_queue);
836
837 } else if (ast_strings_equal(command, STOP_MEDIA_BUFFERING)) {
838 const char *id;
839 char *option;
840 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
842
844 id = ast_json_object_string_get(json, "correlation_id");
845 } else {
846 id = data;
847 }
848
849 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
851
852 if (!instance->bulk_media_in_progress) {
853 send_event(instance, ERROR, "STOP_MEDIA_BUFFERING can't be called when media buffering isn't active.\n");
854 return 0;
855 }
856
857 ast_debug(4, "%s: WebSocket %s '%s' with %d bytes in leftover_data.\n",
859 (int)instance->leftover_len);
860
861 instance->bulk_media_in_progress = 0;
862 instance->unbuffered = instance->last_unbuffered;
863 if (instance->leftover_len > 0) {
864 res = queue_frame_from_buffer(instance, instance->leftover_data, instance->leftover_len);
865 if (res < 0) {
866 return res;
867 }
868 }
869 instance->leftover_len = 0;
870 option = create_event(instance, MEDIA_BUFFERING_COMPLETED, id);
871 if (!option) {
872 return -1;
873 }
874 res = queue_option_frame(instance, option);
875 ast_free(option);
876
877 } else if (ast_strings_equal(command, MARK_MEDIA)) {
878 const char *id;
879 char *option;
880 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
882
884
886 id = ast_json_object_string_get(json, "correlation_id");
887 } else {
888 id = data;
889 }
890
891 ast_debug(4, "%s: %s %s\n",
892 ast_channel_name(instance->channel), MARK_MEDIA, id);
893
894 option = create_event(instance, MEDIA_MARK_PROCESSED, id);
895 if (!option) {
896 return -1;
897 }
898 res = queue_option_frame(instance, option);
899 ast_free(option);
900
901 } else if (ast_strings_equal(command, FLUSH_MEDIA)) {
902 struct ast_frame *frame = NULL;
903
904 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
905 ERROR_ON_UNBUFFERED_MODE_RTN(instance, command);
906
907 AST_LIST_LOCK(&instance->frame_queue);
908 while ((frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list))) {
909 ast_frfree(frame);
910 }
911 instance->frame_queue_length = 0;
912 instance->bulk_media_in_progress = 0;
913 instance->leftover_len = 0;
914 instance->unbuffered = instance->last_unbuffered;
915 AST_LIST_UNLOCK(&instance->frame_queue);
916
917 } else if (ast_strings_equal(command, REPORT_QUEUE_DRAINED)) {
918 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
919
920 AST_LIST_LOCK(&instance->frame_queue);
921 instance->report_queue_drained = 1;
922 AST_LIST_UNLOCK(&instance->frame_queue);
923
924 } else if (ast_strings_equal(command, GET_DRIVER_STATUS)) {
925 return send_event(instance, STATUS);
926
927 } else if (ast_strings_equal(command, PAUSE_MEDIA)) {
928 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
929 ERROR_ON_UNBUFFERED_MODE_RTN(instance, command);
931 AST_LIST_LOCK(&instance->frame_queue);
932 instance->queue_paused = 1;
933 AST_LIST_UNLOCK(&instance->frame_queue);
934
935 } else if (ast_strings_equal(command, CONTINUE_MEDIA)) {
936 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
937 ERROR_ON_UNBUFFERED_MODE_RTN(instance, command);
939 AST_LIST_LOCK(&instance->frame_queue);
940 instance->queue_paused = 0;
941 AST_LIST_UNLOCK(&instance->frame_queue);
942
943 } else if (ast_strings_equal(command, SET_MEDIA_DIRECTION)) {
944 const char *direction;
945
946 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
947
949 send_event(instance, ERROR, "%s only supports JSON format.\n", command);
950 return 0;
951 }
952
953 direction = ast_json_object_string_get(json, "direction");
954 if (!direction) {
955 send_event(instance, ERROR, "%s requires a 'direction' parameter.\n", command);
956 return 0;
957 }
958
959 if (!strcmp("both", direction)) {
961 return 0;
962 }
963
964 if (!instance->timer) {
965 set_channel_timer(instance);
967 }
968
970
971 } else if (!strcmp("out", direction)) {
973 return 0;
974 }
975
976 if (!instance->timer) {
977 set_channel_timer(instance);
979 }
980
982
983 } else if (!strcmp("in", direction)) {
985 return 0;
986 }
987
988 if (instance->timer) {
990 ast_timer_close(instance->timer);
991 instance->timer = NULL;
993 }
994
996
997 } else {
998 send_event(instance, ERROR, "'%s' is not a valid direction for %s.\n",
999 direction, command);
1000 return 0;
1001 }
1002
1003 } else {
1004 ast_log(LOG_WARNING, "%s: WebSocket %s command unknown\n",
1005 ast_channel_name(instance->channel), command);
1006 }
1007
1008 return res;
1009}

References ANSWER_CHANNEL, AST_CAUSE_NORMAL, ast_channel_internal_fd_clear(), ast_channel_name(), AST_CONTROL_ANSWER, ast_debug, ast_free, ast_frfree, ast_json_load_buf(), ast_json_object_string_get, ast_json_unref(), AST_LIST_LOCK, AST_LIST_REMOVE_HEAD, AST_LIST_UNLOCK, ast_log, ast_null_frame, ast_queue_control(), ast_queue_frame(), ast_strings_equal(), ast_timer_close(), AST_WEBSOCKET_STATUS_NORMAL, websocket_pvt::bulk_media_in_progress, websocket_pvt::channel, CONTINUE_MEDIA, websocket_pvt::control_msg_format, create_event, ast_frame::data, ERROR_ON_INVALID_MEDIA_DIRECTION_RTN, ERROR_ON_PASSTHROUGH_MODE_RTN, ERROR_ON_UNBUFFERED_MODE_RTN, FLUSH_MEDIA, websocket_pvt::frame_queue, websocket_pvt::frame_queue_length, GET_DRIVER_STATUS, HANGUP_CHANNEL, id, websocket_pvt::last_unbuffered, websocket_pvt::leftover_data, websocket_pvt::leftover_len, LOG_WARNING, MARK_MEDIA, websocket_pvt::media_direction, NULL, PAUSE_MEDIA, queue_frame_from_buffer(), queue_option_frame(), websocket_pvt::queue_paused, RAII_VAR, websocket_pvt::report_queue_drained, REPORT_QUEUE_DRAINED, SCOPED_LOCK, send_event, set_channel_timer(), SET_MEDIA_DIRECTION, START_MEDIA_BUFFERING, STOP_MEDIA_BUFFERING, websocket_pvt::timer, websocket_pvt::unbuffered, WEBCHAN_CONTROL_MSG_FORMAT_JSON, WEBCHAN_MEDIA_DIRECTION_BOTH, WEBCHAN_MEDIA_DIRECTION_IN, WEBCHAN_MEDIA_DIRECTION_OUT, websocket_request_hangup, and WS_TIMER_FDNO.

Referenced by process_text_message().

◆ incoming_ws_established_cb()

static void incoming_ws_established_cb ( struct ast_websocket *  ast_ws_session,
struct ast_variable *  get_params,
struct ast_variable *  upgrade_headers 
)
static

Definition at line 1961 of file chan_websocket.c.

1963{
1964 RAII_VAR(struct ast_websocket *, s, ast_ws_session, ast_websocket_unref);
1965 struct ast_variable *v;
1966 const char *connection_id = NULL;
1967 struct websocket_pvt *instance = NULL;
1968 struct webchan_conf_global *global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1969 int global_write_timeout = global_cfg ? global_cfg->write_timeout : AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
1970
1971 ao2_cleanup(global_cfg);
1972
1973 ast_debug(3, "WebSocket established\n");
1974
1975 for (v = upgrade_headers; v; v = v->next) {
1976 ast_debug(4, "Header-> %s: %s\n", v->name, v->value);
1977 }
1978 for (v = get_params; v; v = v->next) {
1979 ast_debug(4, " Param-> %s: %s\n", v->name, v->value);
1980 }
1981
1982 connection_id = ast_variable_find_in_list(get_params, "CONNECTION_ID");
1983 if (!connection_id) {
1984 /*
1985 * This can't really happen because websocket_http_callback won't
1986 * let it get this far if it can't add the connection_id to the
1987 * get_params.
1988 * Just in case though...
1989 */
1990 ast_log(LOG_WARNING, "WebSocket connection id not found\n");
1993 return;
1994 }
1995
1996 instance = ao2_weakproxy_find(instances, connection_id, OBJ_SEARCH_KEY | OBJ_NOLOCK, "");
1997 if (!instance) {
1998 /*
1999 * This also can't really happen because websocket_http_callback won't
2000 * let it get this far if it can't find the instance.
2001 * Just in case though...
2002 */
2003 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n", connection_id);
2006 return;
2007 }
2008 instance->websocket = ao2_bump(ast_ws_session);
2009
2010 ast_websocket_set_timeout(instance->websocket, global_write_timeout);
2011
2013 ao2_cleanup(instance);
2014 /*
2015 * The instance is the channel's responsibility now.
2016 * We just return here.
2017 */
2018}

References ao2_bump, ao2_cleanup, ao2_weakproxy_find, AST_CAUSE_FAILURE, ast_debug, AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT, ast_log, ast_sorcery_retrieve_by_id(), ast_variable_find_in_list(), ast_websocket_close(), ast_websocket_set_timeout(), AST_WEBSOCKET_STATUS_INTERNAL_ERROR, ast_websocket_unref(), instances, LOG_WARNING, ast_variable::name, ast_variable::next, NULL, OBJ_NOLOCK, OBJ_SEARCH_KEY, RAII_VAR, sorcery, ast_variable::value, websocket_pvt::websocket, websocket_handoff_to_channel(), websocket_request_hangup, and webchan_conf_global::write_timeout.

Referenced by load_module().

◆ incoming_ws_http_callback()

static int incoming_ws_http_callback ( struct ast_tcptls_session_instance *  ser,
const struct ast_http_uri *  urih,
const char *  uri,
enum ast_http_method  method,
struct ast_variable *  get_params,
struct ast_variable *  headers 
)
static

Definition at line 2030 of file chan_websocket.c.

2034{
2035 struct ast_http_uri fake_urih = {
2037 };
2038 int res = 0;
2039 /*
2040 * Normally the http server will destroy the get_params
2041 * when the session ends but if there weren't any initially
2042 * and we create some and add them to the list, the http server
2043 * won't know about it so we have to destroy it ourselves.
2044 */
2045 int destroy_get_params = (get_params == NULL);
2046 struct ast_variable *v = NULL;
2047 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
2048
2049 ast_debug(2, "URI: %s Starting\n", uri);
2050
2051 /*
2052 * The client will have issued the GET request with a URI of
2053 * /media/<connection_id>
2054 *
2055 * Since this callback is registered for the /media URI prefix the
2056 * http server will strip that off the front of the URI passing in
2057 * only the path components after that in the 'uri' parameter.
2058 * This should leave only the connection id without a leading '/'.
2059 */
2060 instance = ao2_weakproxy_find(instances, uri, OBJ_SEARCH_KEY | OBJ_NOLOCK, "");
2061 if (!instance) {
2062 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n", uri);
2063 ast_http_error(ser, 404, "Not found", "WebSocket instance not found");
2064 return -1;
2065 }
2066
2067 /*
2068 * We don't allow additional connections using the same connection id.
2069 */
2070 if (instance->websocket) {
2071 ast_log(LOG_WARNING, "%s: Websocket already connected for channel '%s'\n",
2072 uri, instance->channel ? ast_channel_name(instance->channel) : "unknown");
2073 ast_http_error(ser, 409, "Conflict", "Another websocket connection exists for this connection id");
2074 return -1;
2075 }
2076
2077 v = ast_variable_new("CONNECTION_ID", uri, "");
2078 if (!v) {
2079 ast_http_error(ser, 500, "Server error", "");
2080 return -1;
2081 }
2082 ast_variable_list_append(&get_params, v);
2083
2084 for (v = get_params; v; v = v->next) {
2085 ast_debug(4, " Param-> %s: %s\n", v->name, v->value);
2086 }
2087
2088 /*
2089 * This will ultimately call internal_ws_established_cb() so
2090 * this function will block until the websocket is closed and
2091 * internal_ws_established_cb() returns;
2092 */
2093 res = ast_websocket_uri_cb(ser, &fake_urih, uri, method,
2094 get_params, headers);
2095 if (destroy_get_params) {
2096 ast_variables_destroy(get_params);
2097 }
2098
2099 ast_debug(2, "URI: %s DONE\n", uri);
2100
2101 return res;
2102}

References ao2_cleanup, ao2_weakproxy_find, ast_channel_name(), ast_debug, ast_http_error(), ast_log, ast_variable_list_append, ast_variable_new, ast_variables_destroy(), ast_websocket_uri_cb(), ast_ws_server, ast_http_uri::data, instances, LOG_WARNING, method, ast_variable::name, ast_variable::next, NULL, OBJ_NOLOCK, OBJ_SEARCH_KEY, RAII_VAR, and ast_variable::value.

◆ instance_proxy_cb()

static void instance_proxy_cb ( void *  weakproxy,
void *  data 
)
static

Definition at line 1492 of file chan_websocket.c.

1493{
1494 struct instance_proxy *proxy = weakproxy;
1495 ast_debug(3, "%s: WebSocket instance removed from instances\n", proxy->connection_id);
1496 ao2_unlink(instances, weakproxy);
1497}

References ao2_unlink, ast_debug, instance_proxy::connection_id, and instances.

Referenced by websocket_new().

◆ load_config()

static int load_config ( void  )
static

Definition at line 2171 of file chan_websocket.c.

2172{
2173 ast_debug(2, "Initializing Websocket Client Configuration\n");
2175 if (!sorcery) {
2176 ast_log(LOG_ERROR, "Failed to open sorcery\n");
2177 return -1;
2178 }
2179
2180 ast_sorcery_apply_default(sorcery, "global", "config",
2181 "chan_websocket.conf,criteria=type=global,single_object=yes,explicit_name=global");
2182
2184 ast_log(LOG_ERROR, "Failed to register chan_websocket global object with sorcery\n");
2186 sorcery = NULL;
2187 return -1;
2188 }
2189
2190 ast_sorcery_object_field_register_nodoc(sorcery, "global", "type", "", OPT_NOOP_T, 0, 0);
2191 ast_sorcery_register_cust(global, control_message_format, "plain-text");
2192 ast_sorcery_register_int(global, webchan_conf_global, write_timeout, write_timeout,
2194
2196
2197 return 0;
2198}

References ast_debug, AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT, ast_log, ast_sorcery_apply_default, ast_sorcery_load(), ast_sorcery_object_field_register_nodoc, ast_sorcery_object_register, ast_sorcery_open, ast_sorcery_register_cust, ast_sorcery_register_int, ast_sorcery_unref, global, global_alloc(), global_apply(), LOG_ERROR, NULL, OPT_NOOP_T, sorcery, and webchan_conf_global::write_timeout.

Referenced by load_module().

◆ load_module()

static int load_module ( void  )
static

Function called when our module is loaded.

Definition at line 2229 of file chan_websocket.c.

2230{
2231 int res = 0;
2232 struct ast_websocket_protocol *protocol;
2233
2234 res = load_config();
2235 if (res != 0) {
2237 }
2238
2241 }
2242
2245 ast_log(LOG_ERROR, "Unable to register channel class 'WebSocket'\n");
2246 unload_module();
2248 }
2249
2251 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, 17, instance_proxy_hash_fn,
2252 instance_proxy_sort_fn, instance_proxy_cmp_fn);
2253 if (!instances) {
2255 "Failed to allocate the chan_websocket instance registry\n");
2256 unload_module();
2258 }
2259
2261 if (!ast_ws_server) {
2262 unload_module();
2264 }
2265
2266 protocol = ast_websocket_sub_protocol_alloc("media");
2267 if (!protocol) {
2268 unload_module();
2270 }
2273
2275
2277}

References AO2_ALLOC_OPT_LOCK_RWLOCK, ao2_container_alloc_hash, AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, ast_channel_register(), ast_format_cap_alloc, ast_format_cap_append_by_type(), AST_FORMAT_CAP_FLAG_DEFAULT, ast_http_uri_link(), ast_log, AST_MEDIA_TYPE_UNKNOWN, AST_MODULE_LOAD_DECLINE, AST_MODULE_LOAD_SUCCESS, ast_websocket_server_add_protocol2(), ast_websocket_server_create(), ast_websocket_sub_protocol_alloc(), ast_ws_server, ast_channel_tech::capabilities, http_uri, incoming_ws_established_cb(), instances, load_config(), LOG_ERROR, LOG_WARNING, ast_websocket_protocol::session_established, unload_module(), and websocket_tech.

◆ process_binary_message()

static int process_binary_message ( struct websocket_pvt *  instance,
char *  payload,
uint64_t  payload_len 
)
static

Definition at line 1044 of file chan_websocket.c.

1046{
1047 char *next_frame_ptr = NULL;
1048 size_t bytes_read = 0;
1049 int res = 0;
1050 size_t bytes_left = 0;
1051
1052 /*
1053 * Fast path: if the queue is already full, don't bother splitting
1054 * the message into frames. This check alone isn't sufficient since
1055 * one message can hold many frames; queue_frame_from_buffer()
1056 * enforces QUEUE_LENGTH_MAX on every frame it queues.
1057 */
1058 {
1059 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
1061 if (instance->frame_queue_length >= QUEUE_LENGTH_MAX) {
1062 ast_debug(4, "%s: WebSocket queue is full. Ignoring incoming binary message.\n",
1063 ast_channel_name(instance->channel));
1064 return 0;
1065 }
1066 }
1067
1068 next_frame_ptr = payload;
1069 instance->bytes_read += payload_len;
1070
1071 if (instance->unbuffered) {
1072 res = queue_frame_from_buffer(instance, payload, payload_len);
1073 return res < 0 ? res : 0;
1074 }
1075
1076 if (instance->bulk_media_in_progress && instance->leftover_len > 0) {
1077 /*
1078 * We have leftover data from a previous websocket message.
1079 * Try to make a complete frame by appending data from
1080 * the current message to the leftover data.
1081 */
1082 char *append_ptr = instance->leftover_data + instance->leftover_len;
1083 size_t bytes_needed_for_frame = instance->optimal_frame_size - instance->leftover_len;
1084 /*
1085 * It's possible that even the current message doesn't have enough
1086 * data to make a complete frame.
1087 */
1088 size_t bytes_avail_to_copy = MIN(bytes_needed_for_frame, payload_len);
1089
1090 /*
1091 * Append whatever we can to the end of the leftover data
1092 * even if it's not enough to make a complete frame.
1093 */
1094 memcpy(append_ptr, payload, bytes_avail_to_copy);
1095
1096 /*
1097 * If leftover data is still short, just return and wait for the
1098 * next websocket message.
1099 */
1100 if (bytes_avail_to_copy < bytes_needed_for_frame) {
1101 ast_debug(4, "%s: Leftover data %d bytes but only %d new bytes available of %d needed. Appending and waiting for next message.\n",
1102 ast_channel_name(instance->channel), (int)instance->leftover_len, (int)bytes_avail_to_copy, (int)bytes_needed_for_frame);
1103 instance->leftover_len += bytes_avail_to_copy;
1104 return 0;
1105 }
1106
1107 res = queue_frame_from_buffer(instance, instance->leftover_data, instance->optimal_frame_size);
1108 if (res < 0) {
1109 return -1;
1110 }
1111 if (res == QUEUE_FRAME_DROPPED_FULL) {
1112 /* Queue filled up. Drop the rest of this message. */
1113 instance->leftover_len = 0;
1114 return 0;
1115 }
1116
1117 /*
1118 * We stole data from the current payload so decrement payload_len
1119 * and set the next frame pointer after the data in payload
1120 * we just copied.
1121 */
1122 payload_len -= bytes_avail_to_copy;
1123 next_frame_ptr = payload + bytes_avail_to_copy;
1124
1125 ast_debug(5, "%s: --- BR: %4d FQ: %4d PL: %4d LOL: %3d P: %p NFP: %p OFF: %4d NPL: %4d BAC: %3d\n",
1126 ast_channel_name(instance->channel),
1127 instance->frame_queue_length,
1128 (int)instance->bytes_read,
1129 (int)(payload_len + bytes_avail_to_copy),
1130 (int)instance->leftover_len,
1131 payload,
1132 next_frame_ptr,
1133 (int)(next_frame_ptr - payload),
1134 (int)payload_len,
1135 (int)bytes_avail_to_copy
1136 );
1137
1138
1139 instance->leftover_len = 0;
1140 }
1141
1142 if (!instance->bulk_media_in_progress && instance->leftover_len > 0) {
1143 instance->leftover_len = 0;
1144 }
1145
1146 bytes_left = payload_len;
1147 while (bytes_read < payload_len && bytes_left >= instance->optimal_frame_size) {
1148 res = queue_frame_from_buffer(instance, next_frame_ptr,
1149 instance->optimal_frame_size);
1150 if (res < 0) {
1151 break;
1152 }
1153 if (res == QUEUE_FRAME_DROPPED_FULL) {
1154 /*
1155 * Queue filled up part way through this message. Drop the
1156 * remainder, including any partial frame, so we don't later
1157 * splice non-contiguous audio together via leftover_data.
1158 */
1159 ast_debug(4, "%s: WebSocket queue filled mid-message. Dropping remaining %d bytes.\n",
1160 ast_channel_name(instance->channel), (int)bytes_left);
1161 instance->leftover_len = 0;
1162 return 0;
1163 }
1164 bytes_read += instance->optimal_frame_size;
1165 next_frame_ptr += instance->optimal_frame_size;
1166 bytes_left -= instance->optimal_frame_size;
1167 }
1168
1169 if (instance->bulk_media_in_progress && bytes_left > 0) {
1170 /*
1171 * We have a partial frame. Save the leftover data.
1172 */
1173 ast_debug(5, "%s: +++ BR: %4d FQ: %4d PL: %4d LOL: %3d P: %p NFP: %p OFF: %4d BL: %4d\n",
1174 ast_channel_name(instance->channel),
1175 (int)instance->bytes_read,
1176 instance->frame_queue_length,
1177 (int)payload_len,
1178 (int)instance->leftover_len,
1179 payload,
1180 next_frame_ptr,
1181 (int)(next_frame_ptr - payload),
1182 (int)bytes_left
1183 );
1184 memcpy(instance->leftover_data, next_frame_ptr, bytes_left);
1185 instance->leftover_len = bytes_left;
1186 }
1187
1188 return 0;
1189}

References ast_channel_name(), ast_debug, AST_LIST_LOCK, AST_LIST_UNLOCK, websocket_pvt::bulk_media_in_progress, websocket_pvt::bytes_read, websocket_pvt::channel, websocket_pvt::frame_queue, websocket_pvt::frame_queue_length, websocket_pvt::leftover_data, websocket_pvt::leftover_len, MIN, NULL, websocket_pvt::optimal_frame_size, QUEUE_FRAME_DROPPED_FULL, queue_frame_from_buffer(), QUEUE_LENGTH_MAX, SCOPED_LOCK, and websocket_pvt::unbuffered.

Referenced by read_from_ws_and_queue().

◆ process_text_message()

static int process_text_message ( struct websocket_pvt *  instance,
char *  payload,
uint64_t  payload_len 
)
static

Definition at line 1011 of file chan_websocket.c.

1013{
1014 char *command;
1015
1016 if (payload_len == 0) {
1017 ast_log(LOG_WARNING, "%s: WebSocket TEXT message has 0 length\n",
1018 ast_channel_name(instance->channel));
1019 return 0;
1020 }
1021
1022 if (payload_len > MAX_TEXT_MESSAGE_LEN) {
1023 ast_log(LOG_WARNING, "%s: WebSocket TEXT message of length %d exceeds maximum length of %d\n",
1024 ast_channel_name(instance->channel), (int)payload_len, MAX_TEXT_MESSAGE_LEN);
1025 return 0;
1026 }
1027
1028 /*
1029 * Unfortunately, payload is not NULL terminated even when it's
1030 * a TEXT frame so we need to allocate a new buffer, copy
1031 * the data into it, and NULL terminate it.
1032 */
1033 command = ast_alloca(payload_len + 1);
1034 memcpy(command, payload, payload_len); /* Safe */
1035 command[payload_len] = '\0';
1036 command = ast_strip(command);
1037
1038 ast_debug(4, "%s: Received: %s\n",
1039 ast_channel_name(instance->channel), command);
1040
1041 return handle_command(instance, command);
1042}

References ast_alloca, ast_channel_name(), ast_debug, ast_log, ast_strip(), websocket_pvt::channel, handle_command(), LOG_WARNING, and MAX_TEXT_MESSAGE_LEN.

Referenced by read_from_ws_and_queue().

◆ queue_frame_from_buffer()

static int queue_frame_from_buffer ( struct websocket_pvt *  instance,
char *  buffer,
size_t  len 
)
static

Create a frame from buffer and append it to the frame queue.

The QUEUE_LENGTH_MAX limit is enforced here, per frame, rather than once per WebSocket message. A single binary message can carry many frames' worth of audio, so a per-message check alone lets the queue grow well past its limit.

Return values
0Frame queued.
QUEUE_FRAME_DROPPED_FULLQueue is full; frame dropped.
-1Failure creating the frame.

Definition at line 692 of file chan_websocket.c.

694{
695 struct ast_frame *duped_frame = NULL;
696
697 duped_frame = create_frame_from_buffer(instance, buffer, len);
698 if (!duped_frame) {
699 return -1;
700 }
701
702 {
703 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
705 if (instance->frame_queue_length >= QUEUE_LENGTH_MAX) {
706 ast_frfree(duped_frame);
707 ast_debug(4, "%s: WebSocket queue is full (%d frames). Dropping %d byte frame.\n",
708 ast_channel_name(instance->channel), instance->frame_queue_length, (int)len);
710 }
711 AST_LIST_INSERT_TAIL(&instance->frame_queue, duped_frame, frame_list);
712 instance->frame_queue_length++;
713 if (!instance->queue_full && instance->frame_queue_length >= QUEUE_LENGTH_XOFF_LEVEL) {
714 instance->queue_full = 1;
715 send_event(instance, MEDIA_XOFF);
716 }
717 }
718
719 ast_debug(5, "%s: Queued %d byte frame\n", ast_channel_name(instance->channel),
720 duped_frame->datalen);
721
722 return 0;
723}

References ast_channel_name(), ast_debug, ast_frfree, AST_LIST_INSERT_TAIL, AST_LIST_LOCK, AST_LIST_UNLOCK, websocket_pvt::channel, create_frame_from_buffer(), ast_frame::datalen, websocket_pvt::frame_queue, websocket_pvt::frame_queue_length, len(), NULL, QUEUE_FRAME_DROPPED_FULL, websocket_pvt::queue_full, QUEUE_LENGTH_MAX, QUEUE_LENGTH_XOFF_LEVEL, SCOPED_LOCK, and send_event.

Referenced by handle_command(), and process_binary_message().

◆ queue_option_frame()

static int queue_option_frame ( struct websocket_pvt *  instance,
char *  buffer 
)
static

Definition at line 725 of file chan_websocket.c.

727{
728 struct ast_frame fr = { 0, };
729 struct ast_frame *duped_frame = NULL;
730
731 AST_FRAME_SET_BUFFER(&fr, buffer, 0, strlen(buffer) + 1);
734
735 duped_frame = ast_frisolate(&fr);
736 if (!duped_frame) {
737 ast_log(LOG_WARNING, "%s: Failed to isolate frame\n",
738 ast_channel_name(instance->channel));
739 return -1;
740 }
741
742 AST_LIST_LOCK(&instance->frame_queue);
743 AST_LIST_INSERT_TAIL(&instance->frame_queue, duped_frame, frame_list);
744 AST_LIST_UNLOCK(&instance->frame_queue);
745
746 ast_debug(4, "%s: Queued '%s' option frame\n",
747 ast_channel_name(instance->channel), buffer);
748
749 return 0;
750}

References ast_channel_name(), AST_CONTROL_OPTION, ast_debug, AST_FRAME_CONTROL, AST_FRAME_SET_BUFFER, ast_frisolate, AST_LIST_INSERT_TAIL, AST_LIST_LOCK, AST_LIST_UNLOCK, ast_log, websocket_pvt::channel, websocket_pvt::frame_queue, ast_frame::frametype, ast_frame_subclass::integer, LOG_WARNING, NULL, and ast_frame::subclass.

Referenced by handle_command().

◆ read_from_ws_and_queue()

static int read_from_ws_and_queue ( struct websocket_pvt *  instance)
static

Definition at line 1191 of file chan_websocket.c.

1192{
1193 uint64_t payload_len = 0;
1194 char *payload = NULL;
1195 enum ast_websocket_opcode opcode;
1196 int fragmented = 0;
1197 int res = 0;
1198
1199 if (!instance->websocket) {
1200 ast_log(LOG_WARNING, "%s: WebSocket session not found\n",
1201 ast_channel_name(instance->channel));
1202 return -1;
1203 }
1204
1205 res = ast_websocket_read(instance->websocket, &payload, &payload_len,
1206 &opcode, &fragmented);
1207
1208 if (res) {
1209 ast_debug(3, "%s: WebSocket read error\n",
1210 ast_channel_name(instance->channel));
1212 return -1;
1213 }
1214 ast_debug(5, "%s: WebSocket read %d bytes\n", ast_channel_name(instance->channel),
1215 (int)payload_len);
1216
1217 if (opcode == AST_WEBSOCKET_OPCODE_TEXT) {
1218 return process_text_message(instance, payload, payload_len);
1219 }
1220
1221 /*
1222 * PINGs and PONGs will have been handled by res_http_websocket.
1223 * We also need to ignore CONTINUATION frames as they will be accumulated
1224 * by res_http_websocket until the threshold set in websocket_handoff_to_channel()
1225 * is reached, then it will send us a TEXT or BINARY frame.
1226 */
1227 if (opcode == AST_WEBSOCKET_OPCODE_PING || opcode == AST_WEBSOCKET_OPCODE_PONG
1228 || opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
1229 return 0;
1230 }
1231
1232 if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
1233 ast_debug(3, "%s: WebSocket closed by remote\n",
1234 ast_channel_name(instance->channel));
1236 return -1;
1237 }
1238
1239 if (opcode == AST_WEBSOCKET_OPCODE_BINARY) {
1240 /* If the application's media direction is 'in', drop any media we receive from it */
1242 ast_debug(5, "%s: WebSocket dropped frame (application media direction is 'in')\n",
1243 ast_channel_name(instance->channel));
1244 return 0;
1245 }
1246 } else {
1247 ast_log(LOG_WARNING, "%s: WebSocket frame type %d not supported\n",
1248 ast_channel_name(instance->channel), (int)opcode);
1250 return 0;
1251 }
1252
1253 return process_binary_message(instance, payload, payload_len);
1254}

References AST_CAUSE_FAILURE, AST_CAUSE_NETWORK_OUT_OF_ORDER, AST_CAUSE_NORMAL, ast_channel_name(), ast_debug, ast_log, AST_WEBSOCKET_OPCODE_BINARY, AST_WEBSOCKET_OPCODE_CLOSE, AST_WEBSOCKET_OPCODE_CONTINUATION, AST_WEBSOCKET_OPCODE_PING, AST_WEBSOCKET_OPCODE_PONG, AST_WEBSOCKET_OPCODE_TEXT, ast_websocket_read(), AST_WEBSOCKET_STATUS_GOING_AWAY, AST_WEBSOCKET_STATUS_UNSUPPORTED_DATA, websocket_pvt::channel, LOG_WARNING, websocket_pvt::media_direction, NULL, process_binary_message(), process_text_message(), WEBCHAN_MEDIA_DIRECTION_IN, websocket_pvt::websocket, and websocket_request_hangup.

Referenced by webchan_read().

◆ reload_module()

static int reload_module ( void  )
static

Definition at line 2220 of file chan_websocket.c.

2221{
2222 ast_debug(2, "Reloading chan_websocket configuration\n");
2224
2225 return 0;
2226}

References ast_debug, ast_sorcery_reload(), and sorcery.

◆ set_channel_timer()

static int set_channel_timer ( struct websocket_pvt *  instance)
static

Definition at line 1604 of file chan_websocket.c.

1605{
1606 int rate = 0;
1607 instance->timer = ast_timer_open();
1608 if (!instance->timer) {
1609 return -1;
1610 }
1611 /* Rate is the number of ticks per second, not the interval. */
1612 rate = 1000 / ast_format_get_default_ms(instance->native_format);
1613 ast_debug(3, "%s: WebSocket timer rate %d\n",
1614 ast_channel_name(instance->channel), rate);
1615 ast_timer_set_rate(instance->timer, rate);
1616 /*
1617 * Calling ast_channel_set_fd will cause the channel thread to call
1618 * webchan_read at 'rate' times per second.
1619 */
1621
1622 return 0;
1623}

References ast_channel_name(), ast_channel_set_fd(), ast_debug, ast_format_get_default_ms(), ast_timer_fd(), ast_timer_open(), ast_timer_set_rate(), websocket_pvt::channel, websocket_pvt::native_format, websocket_pvt::timer, and WS_TIMER_FDNO.

Referenced by handle_command(), and webchan_request().

◆ set_channel_variables()

static int set_channel_variables ( struct websocket_pvt *  instance)
static

Definition at line 1625 of file chan_websocket.c.

1626{
1627 char *pkt_size = NULL;
1628 int res = ast_asprintf(&pkt_size, "%d", instance->optimal_frame_size);
1629 if (res <= 0) {
1630 return -1;
1631 }
1632
1634 pkt_size);
1635 ast_free(pkt_size);
1637 instance->connection_id);
1638
1639 return 0;
1640}

References ast_asprintf, ast_free, websocket_pvt::channel, websocket_pvt::connection_id, MEDIA_WEBSOCKET_CONNECTION_ID, MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE, NULL, websocket_pvt::optimal_frame_size, and pbx_builtin_setvar_helper().

Referenced by webchan_request().

◆ unload_module()

static int unload_module ( void  )
static

◆ validate_uri_parameters()

static int validate_uri_parameters ( const char *  uri_params)
static

Definition at line 1642 of file chan_websocket.c.

1643{
1644 char *params = ast_strdupa(uri_params);
1645 char *nvp = NULL;
1646 char *nv = NULL;
1647
1648 /*
1649 * uri_params should be a comma-separated list of key=value pairs.
1650 * For example:
1651 * name1=value1,name2=value2
1652 * We're verifying that each name and value either doesn't need
1653 * to be encoded or that it already is.
1654 */
1655
1656 while((nvp = ast_strsep(&params, ',', 0))) {
1657 /* nvp will be name1=value1 */
1658 while((nv = ast_strsep(&nvp, '=', 0))) {
1659 /* nv will be either name1 or value1 */
1660 if (!ast_uri_verify_encoded(nv)) {
1661 return 0;
1662 }
1663 }
1664 }
1665
1666 return 1;
1667}

References ast_strdupa, ast_strsep(), ast_uri_verify_encoded(), NULL, and websocket_pvt::uri_params.

Referenced by webchan_request().

◆ webchan_call()

static int webchan_call ( struct ast_channel *  ast,
const char *  dest,
int  timeout 
)
static

Definition at line 1378 of file chan_websocket.c.

1380{
1381 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1383 struct webchan_conf_global *global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1384 int global_write_timeout = global_cfg ? global_cfg->write_timeout : AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
1385
1386 ao2_cleanup(global_cfg);
1387
1388 if (!instance) {
1389 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n",
1390 ast_channel_name(ast));
1392 return -1;
1393 }
1394
1395 if (instance->type == AST_WS_TYPE_SERVER) {
1396 ast_debug(3, "%s: Websocket call incoming\n", ast_channel_name(instance->channel));
1397 return 0;
1398 }
1399 ast_debug(3, "%s: Websocket call outgoing\n", ast_channel_name(instance->channel));
1400
1401 if (!instance->client) {
1402 ast_log(LOG_WARNING, "%s: WebSocket client not found\n",
1403 ast_channel_name(ast));
1405 return -1;
1406 }
1407
1408 ast_debug(3, "%s: WebSocket call requested to %s. cid: %s\n",
1409 ast_channel_name(ast), dest, instance->connection_id);
1410
1411 if (!ast_strlen_zero(instance->uri_params)) {
1413 }
1414
1415 instance->websocket = ast_websocket_client_connect(instance->client,
1416 instance, ast_channel_name(ast), &result);
1417 if (!instance->websocket || result != WS_OK) {
1418 ast_log(LOG_WARNING, "%s: WebSocket connection failed to %s: %s\n",
1421 return -1;
1422 }
1423
1424 /*
1425 * If websocket_client->write_timeout was set in websocket_client.conf, it will
1426 * have been applied to the websocket by ast_websocket_client_connect() above.
1427 * If it wasn't set in websocket_client.conf, the value will be INT_MAX and
1428 * and ast_websocket_client_connect() will have set AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT
1429 * on the websocket. However, the user may have set write_timeout in the global section
1430 * of chan_websocket.conf so if it wasn't set in websocket_client.conf, we'll now set
1431 * the websocket timeout to that. If they haven't set it in chan_websocket.conf either,
1432 * it'll default to AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT as well so the call below will
1433 * basically become a no-op.
1434 */
1435 if (instance->client->write_timeout == INT_MAX) {
1436 ast_websocket_set_timeout(instance->websocket, global_write_timeout);
1437 }
1438
1439 return websocket_handoff_to_channel(instance);
1440}

References ao2_cleanup, AST_CAUSE_FAILURE, AST_CAUSE_NO_ROUTE_DESTINATION, ast_channel_hangupcause_set(), ast_channel_name(), ast_channel_tech_pvt(), ast_debug, AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT, ast_log, ast_sorcery_retrieve_by_id(), ast_strlen_zero(), ast_websocket_client_add_uri_params(), ast_websocket_client_connect(), ast_websocket_result_to_str(), ast_websocket_set_timeout(), AST_WS_TYPE_SERVER, websocket_pvt::channel, websocket_pvt::client, websocket_pvt::connection_id, LOG_WARNING, result, sorcery, websocket_pvt::type, websocket_pvt::uri_params, websocket_pvt::websocket, websocket_handoff_to_channel(), webchan_conf_global::write_timeout, ast_websocket_client::write_timeout, and WS_OK.

◆ webchan_hangup()

static int webchan_hangup ( struct ast_channel *  ast)
static

Definition at line 1918 of file chan_websocket.c.

1919{
1920 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1921
1922 if (!instance) {
1923 return -1;
1924 }
1925 ast_debug(3, "%s: WebSocket call hangup. cid: %s\n",
1926 ast_channel_name(ast), instance->connection_id);
1927
1928 if (instance->websocket) {
1930 ast_websocket_unref(instance->websocket);
1931 instance->websocket = NULL;
1932 }
1934
1935 /* Clean up the reference from adding the instance to the channel */
1936 ao2_cleanup(instance);
1937
1938 return 0;
1939}

References ao2_cleanup, ast_channel_name(), ast_channel_tech_hangupcause(), ast_channel_tech_pvt(), ast_channel_tech_pvt_set(), ast_debug, ast_websocket_close(), ast_websocket_unref(), websocket_pvt::connection_id, NULL, and websocket_pvt::websocket.

◆ webchan_read()

static struct ast_frame * webchan_read ( struct ast_channel *  ast)
static

Definition at line 623 of file chan_websocket.c.

624{
625 struct websocket_pvt *instance = NULL;
626 struct ast_frame *native_frame = NULL;
627 int fdno = ast_channel_fdno(ast);
628
629 instance = ast_channel_tech_pvt(ast);
630 if (!instance) {
631 return NULL;
632 }
633
634 if (fdno != WS_TIMER_FDNO && fdno != WS_WEBSOCKET_FDNO) {
635 return &ast_null_frame;
636 }
637
638 if (fdno == WS_WEBSOCKET_FDNO) {
639 read_from_ws_and_queue(instance);
640 if (!instance->unbuffered) {
641 return &ast_null_frame;
642 }
643 } else {
645 ast_timer_ack(instance->timer, 1);
646 }
647 }
648
649 native_frame = dequeue_frame(instance);
650 if (!native_frame) {
651 if (instance->leftover_len > 0) {
652 native_frame = create_frame_from_buffer(instance, instance->leftover_data, instance->leftover_len);
653 if (native_frame) {
654 ast_debug(4, "%s: Triggered with no frame available but with %d bytes in leftover_data. Returning partial frame.\n",
655 ast_channel_name(ast), (int)instance->leftover_len);
656 instance->leftover_len = 0;
657 return native_frame;
658 }
659 }
660 ast_debug(4, "%s: Triggered with no frame available and no data in leftover_data. Returning NULL frame.\n",
661 ast_channel_name(ast));
662 return &ast_null_frame;
663 }
664
665 ast_debug(5, "%s: Dequeued %d byte frame. Left in buffer: %d\n",
666 ast_channel_name(ast), native_frame->datalen, (int)instance->leftover_len);
667
668 return native_frame;
669}

References ast_channel_fdno(), ast_channel_name(), ast_channel_tech_pvt(), ast_debug, ast_null_frame, ast_timer_ack(), ast_timer_get_event(), AST_TIMING_EVENT_EXPIRED, create_frame_from_buffer(), ast_frame::datalen, dequeue_frame(), websocket_pvt::leftover_data, websocket_pvt::leftover_len, NULL, read_from_ws_and_queue(), websocket_pvt::timer, websocket_pvt::unbuffered, WS_TIMER_FDNO, and WS_WEBSOCKET_FDNO.

◆ webchan_request()

static struct ast_channel * webchan_request ( const char *  type,
struct ast_format_cap *  cap,
const struct ast_assigned_ids *  assignedids,
const struct ast_channel *  requestor,
const char *  data,
int *  cause 
)
static

Definition at line 1700 of file chan_websocket.c.

1703{
1704 char *parse;
1705 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1706 struct ast_channel *chan = NULL;
1707 struct ast_format *fmt = NULL;
1708 struct ast_format_cap *caps = NULL;
1710 AST_APP_ARG(connection_id);
1712 );
1713 struct ast_flags opts = { 0, };
1714 char *opt_args[OPT_ARG_ARRAY_SIZE];
1715 const char *requestor_name = requestor ? ast_channel_name(requestor) :
1716 (assignedids && !ast_strlen_zero(assignedids->uniqueid) ? assignedids->uniqueid : "<unknown>");
1717 RAII_VAR(struct webchan_conf_global *, global_cfg, NULL, ao2_cleanup);
1718
1719 global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1720
1721 ast_debug(3, "%s: WebSocket channel requested\n",
1722 requestor_name);
1723
1724 if (ast_strlen_zero(data)) {
1725 ast_log(LOG_ERROR, "%s: A connection id is required for the 'WebSocket' channel\n",
1726 requestor_name);
1727 goto failure;
1728 }
1729 parse = ast_strdupa(data);
1730 AST_NONSTANDARD_APP_ARGS(args, parse, '/');
1731
1732 if (ast_strlen_zero(args.connection_id)) {
1733 ast_log(LOG_ERROR, "%s: connection_id is required for the 'WebSocket' channel\n",
1734 requestor_name);
1735 goto failure;
1736 }
1737
1738 if (!ast_strlen_zero(args.options)
1739 && ast_app_parse_options(websocket_options, &opts, opt_args,
1740 ast_strdupa(args.options))) {
1741 ast_log(LOG_ERROR, "%s: 'WebSocket' channel options '%s' parse error\n",
1742 requestor_name, args.options);
1743 goto failure;
1744 }
1745
1746 if (ast_test_flag(&opts, OPT_WS_CODEC)
1747 && !ast_strlen_zero(opt_args[OPT_ARG_WS_CODEC])) {
1748 fmt = ast_format_cache_get(opt_args[OPT_ARG_WS_CODEC]);
1749 } else {
1750 /*
1751 * If codec wasn't specified in the dial string,
1752 * use the first format in the capabilities.
1753 */
1754 fmt = ast_format_cap_get_format(cap, 0);
1755 }
1756
1757 if (!fmt) {
1758 ast_log(LOG_WARNING, "%s: No codec found for sending media to connection '%s'\n",
1759 requestor_name, args.connection_id);
1760 goto failure;
1761 }
1762
1763 ast_debug(3, "%s: Using format %s from %s\n",
1764 requestor_name, ast_format_get_name(fmt),
1765 ast_test_flag(&opts, OPT_WS_CODEC) ? "dialstring" : "requester");
1766
1767 instance = websocket_new(requestor_name, args.connection_id, fmt);
1768 if (!instance) {
1769 ast_log(LOG_ERROR, "%s: Failed to allocate WebSocket channel pvt\n",
1770 requestor_name);
1771 goto failure;
1772 }
1773
1774 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_BOTH;
1776 if (!strcmp("both", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1777 /* The default. Don't need to do anything here other than
1778 * ensure it is an allowed value. */
1779 } else if (!strcmp("out", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1780 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_OUT;
1781 } else if (!strcmp("in", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1782 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_IN;
1783 } else {
1784 ast_log(LOG_ERROR, "Unrecognized option for media direction: '%s'.\n",
1785 opt_args[OPT_ARG_WS_MEDIA_DIRECTION]);
1786 goto failure;
1787 }
1788 }
1789
1790 instance->no_auto_answer = ast_test_flag(&opts, OPT_WS_NO_AUTO_ANSWER);
1791
1792 /*
1793 * Passthrough requires unbuffered. If passthrough was forced by choice of
1794 * codec, unbuffered will already have been set. If passthrough was set by
1795 * the dialstring option, we need to force unbuffered.
1796 */
1797 if (!instance->passthrough) {
1798 instance->passthrough = ast_test_flag(&opts, OPT_WS_PASSTHROUGH);
1799 instance->unbuffered = instance->passthrough;
1800 }
1801 /*
1802 * If unbuffered hasn't been forced by passthrough, set it according to the
1803 * dialstring "u" option.
1804 */
1805 if (!instance->unbuffered) {
1806 instance->unbuffered = ast_test_flag(&opts, OPT_WS_UNBUFFERED);
1807 }
1808
1810 && !ast_strlen_zero(opt_args[OPT_ARG_WS_URI_PARAM])) {
1811 char *comma;
1812
1813 if (ast_strings_equal(args.connection_id, INCOMING_CONNECTION_ID)) {
1815 "%s: URI parameters are not allowed for 'WebSocket/INCOMING' channels\n",
1816 requestor_name);
1817 goto failure;
1818 }
1819
1820 ast_debug(3, "%s: Using URI parameters '%s'\n",
1821 requestor_name, opt_args[OPT_ARG_WS_URI_PARAM]);
1822
1824 ast_log(LOG_ERROR, "%s: Invalid URI parameters '%s' in WebSocket/%s dial string\n",
1825 requestor_name, opt_args[OPT_ARG_WS_URI_PARAM],
1826 args.connection_id);
1827 goto failure;
1828 }
1829
1830 instance->uri_params = ast_strdup(opt_args[OPT_ARG_WS_URI_PARAM]);
1831 comma = instance->uri_params;
1832 /*
1833 * The normal separator for query string components is an
1834 * ampersand ('&') but the Dial app interprets them as additional
1835 * channels to dial in parallel so we instruct users to separate
1836 * the parameters with commas (',') instead. We now have to
1837 * convert those commas back to ampersands.
1838 */
1839 while ((comma = strchr(comma,','))) {
1840 *comma = '&';
1841 }
1842 ast_debug(3, "%s: Using final URI '%s'\n", requestor_name, instance->uri_params);
1843 }
1844
1845 if (ast_test_flag(&opts, OPT_WS_MSG_FORMAT)) {
1846 instance->control_msg_format = control_msg_format_from_str(opt_args[OPT_ARG_WS_MSG_FORMAT]);
1847
1848 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_INVALID) {
1849 ast_log(LOG_WARNING, "%s: 'f/control message format' dialstring parameter value missing or invalid. "
1850 "Defaulting to 'plain-text'\n",
1851 requestor_name);
1852 instance->control_msg_format = WEBCHAN_CONTROL_MSG_FORMAT_PLAIN;
1853 }
1854 } else if (global_cfg) {
1855 instance->control_msg_format = global_cfg->control_msg_format;
1856 }
1857
1858 chan = ast_channel_alloc(1, AST_STATE_DOWN, "", "", "", "", "", assignedids,
1859 requestor, 0, "WebSocket/%s/%p", args.connection_id, instance);
1860 if (!chan) {
1861 ast_log(LOG_ERROR, "%s: Unable to alloc channel\n", requestor_name);
1862 goto failure;
1863 }
1864
1865 /* Prevent device state caching as this channel involves ephemeral destinations or sources */
1867 ast_debug(3, "%s: WebSocket channel %s allocated for connection %s\n",
1868 ast_channel_name(chan), requestor_name,
1869 instance->connection_id);
1870
1871 instance->channel = ao2_bump(chan);
1872 ast_channel_tech_set(instance->channel, &websocket_tech);
1873
1874 /* If the application's media direction is 'both' or 'out', we need the channel timer. */
1875 if (instance->media_direction != WEBCHAN_MEDIA_DIRECTION_IN
1876 && set_channel_timer(instance) != 0) {
1877 goto failure;
1878 }
1879
1880 if (set_channel_variables(instance) != 0) {
1881 goto failure;
1882 }
1883
1885 if (!caps) {
1886 ast_log(LOG_ERROR, "%s: Unable to alloc caps\n", requestor_name);
1887 goto failure;
1888 }
1889
1890 ast_format_cap_append(caps, instance->native_format, 0);
1891 ast_channel_nativeformats_set(instance->channel, caps);
1892 ast_channel_set_writeformat(instance->channel, instance->native_format);
1893 ast_channel_set_rawwriteformat(instance->channel, instance->native_format);
1894 ast_channel_set_readformat(instance->channel, instance->native_format);
1895 ast_channel_set_rawreadformat(instance->channel, instance->native_format);
1896 ast_channel_tech_pvt_set(chan, ao2_bump(instance));
1897 ast_channel_unlock(chan);
1898 ao2_cleanup(caps);
1899
1900 ast_debug(3, "%s: WebSocket channel created to %s\n",
1901 ast_channel_name(chan), args.connection_id);
1902
1903 return chan;
1904
1905failure:
1906 if (chan) {
1907 ast_channel_unlock(chan);
1908 }
1909 *cause = AST_CAUSE_FAILURE;
1910 return NULL;
1911}

References ao2_bump, ao2_cleanup, args, AST_APP_ARG, ast_app_parse_options(), AST_CAUSE_FAILURE, ast_channel_alloc, ast_channel_flags(), ast_channel_name(), ast_channel_nativeformats_set(), ast_channel_set_rawreadformat(), ast_channel_set_rawwriteformat(), ast_channel_set_readformat(), ast_channel_set_writeformat(), ast_channel_tech_pvt_set(), ast_channel_tech_set(), ast_channel_unlock, ast_debug, AST_DECLARE_APP_ARGS, AST_FLAG_DISABLE_DEVSTATE_CACHE, ast_format_cache_get, ast_format_cap_alloc, ast_format_cap_append, AST_FORMAT_CAP_FLAG_DEFAULT, ast_format_cap_get_format(), ast_format_get_name(), ast_log, AST_NONSTANDARD_APP_ARGS, ast_set_flag, ast_sorcery_retrieve_by_id(), AST_STATE_DOWN, ast_strdup, ast_strdupa, ast_strings_equal(), ast_strlen_zero(), ast_test_flag, control_msg_format_from_str(), INCOMING_CONNECTION_ID, LOG_ERROR, LOG_WARNING, NULL, OPT_ARG_ARRAY_SIZE, OPT_ARG_WS_CODEC, OPT_ARG_WS_MEDIA_DIRECTION, OPT_ARG_WS_MSG_FORMAT, OPT_ARG_WS_URI_PARAM, OPT_WS_CODEC, OPT_WS_MEDIA_DIRECTION, OPT_WS_MSG_FORMAT, OPT_WS_NO_AUTO_ANSWER, OPT_WS_PASSTHROUGH, OPT_WS_UNBUFFERED, OPT_WS_URI_PARAM, options, RAII_VAR, set_channel_timer(), set_channel_variables(), sorcery, ast_assigned_ids::uniqueid, validate_uri_parameters(), WEBCHAN_CONTROL_MSG_FORMAT_INVALID, WEBCHAN_CONTROL_MSG_FORMAT_PLAIN, WEBCHAN_MEDIA_DIRECTION_BOTH, WEBCHAN_MEDIA_DIRECTION_IN, WEBCHAN_MEDIA_DIRECTION_OUT, websocket_new(), websocket_options, and websocket_tech.

◆ webchan_send_dtmf_text()

static int webchan_send_dtmf_text ( struct ast_channel *  ast,
char  digit,
unsigned int  duration 
)
static

Definition at line 1941 of file chan_websocket.c.

1942{
1943 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1944
1945 if (!instance) {
1946 return -1;
1947 }
1948
1949 return send_event(instance, DTMF_END, digit);
1950}

References ast_channel_tech_pvt(), digit, and send_event.

◆ webchan_write()

static int webchan_write ( struct ast_channel *  ast,
struct ast_frame *  f 
)
static

Function called when we should write a frame to the channel.

Definition at line 1329 of file chan_websocket.c.

1330{
1331 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1332 int res = 0;
1333
1334 if (!instance || !instance->websocket) {
1335 ast_log(LOG_WARNING, "%s: WebSocket instance or client not found\n",
1336 ast_channel_name(ast));
1337 return -1;
1338 }
1339
1340 /* The app doesn't want media right now */
1342 return 0;
1343 }
1344
1345 if (f->frametype == AST_FRAME_CNG) {
1346 return 0;
1347 }
1348
1349 if (f->frametype != AST_FRAME_VOICE) {
1350 ast_log(LOG_WARNING, "%s: This WebSocket channel only supports AST_FRAME_VOICE frames\n",
1351 ast_channel_name(ast));
1352 return 0;
1353 }
1354
1356 ast_log(LOG_WARNING, "%s: This WebSocket channel only supports the '%s' format, not '%s'\n",
1359 return -1;
1360 }
1361
1363 (char *)f->data.ptr, (uint64_t)f->datalen);
1364 if (res != 0) {
1365 ast_log(LOG_WARNING, "%s: WebSocket write failure\n", ast_channel_name(ast));
1366 }
1367
1368 return res;
1369}

References ast_channel_name(), ast_channel_tech_pvt(), ast_format_cmp(), AST_FORMAT_CMP_NOT_EQUAL, ast_format_get_name(), AST_FRAME_CNG, AST_FRAME_VOICE, ast_log, AST_WEBSOCKET_OPCODE_BINARY, ast_websocket_write(), ast_frame::data, ast_frame::datalen, ast_frame_subclass::format, ast_frame::frametype, LOG_WARNING, websocket_pvt::media_direction, websocket_pvt::native_format, ast_frame::ptr, ast_frame::subclass, WEBCHAN_MEDIA_DIRECTION_OUT, and websocket_pvt::websocket.

◆ websocket_destructor()

static void websocket_destructor ( void *  data)
static

Definition at line 1442 of file chan_websocket.c.

1443{
1444 struct websocket_pvt *instance = data;
1445 struct ast_frame *frame = NULL;
1446 ast_debug(3, "%s: WebSocket instance freed\n", instance->connection_id);
1447
1448 AST_LIST_LOCK(&instance->frame_queue);
1449 while ((frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list))) {
1450 ast_frfree(frame);
1451 }
1452 AST_LIST_UNLOCK(&instance->frame_queue);
1453
1454 if (instance->timer) {
1455 ast_timer_close(instance->timer);
1456 instance->timer = NULL;
1457 }
1458
1459 if (instance->channel) {
1460 ast_channel_unref(instance->channel);
1461 instance->channel = NULL;
1462 }
1463 if (instance->websocket) {
1464 ast_websocket_unref(instance->websocket);
1465 instance->websocket = NULL;
1466 }
1467
1468 ao2_cleanup(instance->client);
1469 instance->client = NULL;
1470
1471 ao2_cleanup(instance->native_codec);
1472 instance->native_codec = NULL;
1473
1474 ao2_cleanup(instance->native_format);
1475 instance->native_format = NULL;
1476
1477 if (instance->leftover_data) {
1478 ast_free(instance->leftover_data);
1479 instance->leftover_data = NULL;
1480 }
1481
1482 ast_free(instance->uri_params);
1483 ast_free(instance->remote_addr);
1484}

References ao2_cleanup, ast_channel_unref, ast_debug, ast_free, ast_frfree, AST_LIST_LOCK, AST_LIST_REMOVE_HEAD, AST_LIST_UNLOCK, ast_timer_close(), ast_websocket_unref(), websocket_pvt::channel, websocket_pvt::client, websocket_pvt::connection_id, websocket_pvt::frame_queue, websocket_pvt::leftover_data, websocket_pvt::native_codec, websocket_pvt::native_format, NULL, websocket_pvt::remote_addr, websocket_pvt::timer, websocket_pvt::uri_params, and websocket_pvt::websocket.

Referenced by websocket_new().

◆ websocket_handoff_to_channel()

static int websocket_handoff_to_channel ( struct websocket_pvt *  instance)
static

Definition at line 1256 of file chan_websocket.c.

1257{
1258 int res = 0;
1259 int nodelay = 1;
1260 struct ast_sockaddr *remote_addr = ast_websocket_remote_address(instance->websocket);
1261
1262 instance->remote_addr = ast_strdup(ast_sockaddr_stringify(remote_addr));
1263 ast_debug(3, "%s: WebSocket connection with %s established\n",
1264 ast_channel_name(instance->channel), instance->remote_addr);
1265
1266 if (setsockopt(ast_websocket_fd(instance->websocket),
1267 IPPROTO_TCP, TCP_NODELAY, (char *) &nodelay, sizeof(nodelay)) < 0) {
1268 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on websocket connection: %s\n", strerror(errno));
1269 }
1270
1271 /*
1272 * The way write timeouts are handled in iostream requires the socket to be
1273 * in non-blocking mode. This is fine for reads as well because we already
1274 * set the websocket file descriptor on the channel and let it call
1275 * webchan_read() when data is available.
1276 */
1278
1279 /*
1280 * Tell res_http_websocket to accumulate incoming WebSocket CONTINUATION frames
1281 * into chunks of 1024 bytes and send us a TEXT or BINARY frame when the threshold
1282 * is reached.
1283 */
1285
1287
1288 res = send_event(instance, MEDIA_START);
1289 if (res != 0 ) {
1290 if (instance->type == AST_WS_TYPE_SERVER) {
1292 } else {
1293 /*
1294 * We were called by webchan_call so just need to set causes.
1295 * The core will hangup the channel.
1296 */
1299 }
1300 return -1;
1301 }
1302
1303 if (!instance->no_auto_answer) {
1304 ast_debug(3, "%s: ANSWER by auto_answer\n", ast_channel_name(instance->channel));
1306 }
1307
1308 return 0;
1309}

References AST_CAUSE_NETWORK_OUT_OF_ORDER, ast_channel_hangupcause_set(), ast_channel_name(), ast_channel_set_fd(), ast_channel_tech_hangupcause_set(), AST_CONTROL_ANSWER, ast_debug, ast_log, ast_queue_control(), ast_sockaddr_stringify(), ast_strdup, ast_websocket_fd(), ast_websocket_reconstruct_enable(), ast_websocket_remote_address(), ast_websocket_set_nonblock(), AST_WEBSOCKET_STATUS_GOING_AWAY, AST_WS_TYPE_SERVER, websocket_pvt::channel, errno, LOG_WARNING, websocket_pvt::no_auto_answer, websocket_pvt::remote_addr, send_event, websocket_pvt::type, websocket_pvt::websocket, websocket_request_hangup, and WS_WEBSOCKET_FDNO.

Referenced by incoming_ws_established_cb(), and webchan_call().

◆ websocket_new()

static struct websocket_pvt * websocket_new ( const char *  chan_name,
const char *  connection_id,
struct ast_format *  fmt 
)
static

Definition at line 1499 of file chan_websocket.c.

1501{
1502 RAII_VAR(struct instance_proxy *, proxy, NULL, ao2_cleanup);
1503 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1504 char uuid[AST_UUID_STR_LEN];
1505 enum ast_websocket_type ws_type;
1506
1507 SCOPED_AO2WRLOCK(locker, instances);
1508
1509 if (ast_strings_equal(connection_id, INCOMING_CONNECTION_ID)) {
1510 connection_id = ast_uuid_generate_str(uuid, sizeof(uuid));
1511 ws_type = AST_WS_TYPE_SERVER;
1512 } else {
1513 ws_type = AST_WS_TYPE_CLIENT;
1514 }
1515
1516 proxy = ao2_weakproxy_alloc(sizeof(*proxy) + strlen(connection_id) + 1, NULL);
1517 if (!proxy) {
1518 return NULL;
1519 }
1520 strcpy(proxy->connection_id, connection_id); /* Safe */
1521
1522 instance = ao2_alloc(sizeof(*instance) + strlen(connection_id) + 1,
1524 if (!instance) {
1525 return NULL;
1526 }
1527 strcpy(instance->connection_id, connection_id); /* Safe */
1528
1529 instance->type = ws_type;
1530 if (ws_type == AST_WS_TYPE_CLIENT) {
1531 instance->client = ast_websocket_client_retrieve_by_id(instance->connection_id);
1532 if (!instance->client) {
1533 ast_log(LOG_ERROR, "%s: WebSocket client connection '%s' not found\n",
1534 chan_name, instance->connection_id);
1535 return NULL;
1536 }
1537 }
1538
1539 AST_LIST_HEAD_INIT(&instance->frame_queue);
1540
1541 /*
1542 * We need the codec to calculate the number of samples in a frame
1543 * so we'll get it once and store it in the instance.
1544 *
1545 * References for native_format and native_codec are now held by the
1546 * instance and will be released when the instance is destroyed.
1547 */
1548 instance->native_format = fmt;
1549 instance->native_codec = ast_format_get_codec(instance->native_format);
1550 /*
1551 * References for native_format and native_codec are now held by the
1552 * instance and will be released when the instance is destroyed.
1553 */
1554
1555 /*
1556 * It's not possible for us to re-time or re-frame media if the data
1557 * stream can't be broken up on arbitrary byte boundaries. This is usually
1558 * indicated by the codec's minimum_bytes being small (10 bytes or less).
1559 * We need to force the passthrough and unbuffered modes in this case.
1560 */
1561 if (instance->native_codec->minimum_bytes <= 10) {
1562 instance->passthrough = 1;
1563 instance->unbuffered = 1;
1564 instance->optimal_frame_size = 0;
1565 } else {
1566 instance->optimal_frame_size =
1567 (instance->native_codec->default_ms * instance->native_codec->minimum_bytes)
1568 / instance->native_codec->minimum_ms;
1569 instance->leftover_data = ast_calloc(1, instance->optimal_frame_size);
1570 if (!instance->leftover_data) {
1571 return NULL;
1572 }
1573 }
1574
1575 ast_debug(3,
1576 "%s: WebSocket channel native format '%s' Sample rate: %d ptime: %dms minms: %u minbytes: %u passthrough: %d optimal_frame_size: %d\n",
1577 chan_name, ast_format_get_name(instance->native_format),
1578 ast_format_get_sample_rate(instance->native_format),
1579 ast_format_get_default_ms(instance->native_format),
1580 ast_format_get_minimum_ms(instance->native_format),
1581 ast_format_get_minimum_bytes(instance->native_format),
1582 instance->passthrough,
1583 instance->optimal_frame_size);
1584
1585 /* We have exclusive access to proxy and sorcery, no need for locking here. */
1586 if (ao2_weakproxy_set_object(proxy, instance, OBJ_NOLOCK)) {
1587 return NULL;
1588 }
1589
1591 return NULL;
1592 }
1593
1594 if (!ao2_link_flags(instances, proxy, OBJ_NOLOCK)) {
1595 ast_log(LOG_ERROR, "%s: Unable to link WebSocket instance to instances\n",
1596 proxy->connection_id);
1597 return NULL;
1598 }
1599 ast_debug(3, "%s: WebSocket instance created and linked\n", proxy->connection_id);
1600
1601 return ao2_bump(instance);
1602}

References ao2_alloc, ao2_bump, ao2_cleanup, ao2_link_flags, ao2_weakproxy_alloc, ao2_weakproxy_set_object, ao2_weakproxy_subscribe(), ast_calloc, ast_debug, ast_format_get_codec(), ast_format_get_default_ms(), ast_format_get_minimum_bytes(), ast_format_get_minimum_ms(), ast_format_get_name(), ast_format_get_sample_rate(), AST_LIST_HEAD_INIT, ast_log, ast_strings_equal(), ast_uuid_generate_str(), AST_UUID_STR_LEN, ast_websocket_client_retrieve_by_id(), AST_WS_TYPE_CLIENT, AST_WS_TYPE_SERVER, websocket_pvt::connection_id, INCOMING_CONNECTION_ID, instance_proxy_cb(), instances, LOG_ERROR, NULL, OBJ_NOLOCK, RAII_VAR, SCOPED_AO2WRLOCK, uuid(), and websocket_destructor().

Referenced by webchan_request().

Variable Documentation

◆ __mod_info

struct ast_module_info __mod_info = { .name = AST_MODULE, .flags = AST_MODFLAG_LOAD_ORDER , .description = "Websocket Media Channel" , .key = ASTERISK_GPL_KEY , .buildopt_sum = AST_BUILDOPT_SUM, .support_level = AST_MODULE_SUPPORT_CORE, .load = load_module, .unload = unload_module, .reload = reload_module, .load_pri = AST_MODPRI_CHANNEL_DRIVER, .requires = "res_http_websocket,res_websocket_client", }
static

Definition at line 2286 of file chan_websocket.c.

◆ ast_module_info

const struct ast_module_info* ast_module_info = &__mod_info
static

Definition at line 2286 of file chan_websocket.c.

◆ ast_ws_server

struct ast_websocket_server* ast_ws_server
static

Definition at line 87 of file chan_websocket.c.

Referenced by incoming_ws_http_callback(), load_module(), and unload_module().

◆ http_uri

struct ast_http_uri http_uri
static

Definition at line 2104 of file chan_websocket.c.

2104 {
2105 .callback = incoming_ws_http_callback,
2106 .description = "Media over Websocket",
2107 .uri = "media",
2108 .has_subtree = 1,
2109 .data = NULL,
2110 .key = __FILE__,
2111 .no_decode_uri = 1,
2112};

Referenced by load_module(), and unload_module().

◆ instances

struct ao2_container* instances = NULL
static

◆ msg_format_map

const char* msg_format_map[]
static
Initial value:

Definition at line 62 of file chan_websocket.c.

62 {
63 [WEBCHAN_CONTROL_MSG_FORMAT_PLAIN] = "plain-text",
66};

Referenced by control_msg_format_from_str(), and control_msg_format_to_str().

◆ sorcery

struct ast_sorcery* sorcery = NULL
static

Definition at line 54 of file chan_websocket.c.

Referenced by __ast_sorcery_apply_config(), __ast_sorcery_apply_default(), __ast_sorcery_apply_wizard_mapping(), __ast_sorcery_insert_wizard_mapping(), __ast_sorcery_object_field_register(), __ast_sorcery_object_register(), __ast_sorcery_object_type_insert_wizard(), __ast_sorcery_object_type_remove_wizard(), __ast_sorcery_open(), __ast_sorcery_remove_wizard_mapping(), alloc_and_initialize_sorcery(), alloc_and_initialize_sorcery(), alloc_and_initialize_sorcery(), apply_list_configuration(), as_config_load(), as_config_reload(), ast_ari_asterisk_delete_object(), ast_ari_asterisk_get_object(), ast_ari_asterisk_update_object(), ast_sip_destroy_sorcery_global(), ast_sip_initialize_sorcery_auth(), ast_sip_initialize_sorcery_domain_alias(), ast_sip_initialize_sorcery_global(), ast_sip_initialize_sorcery_location(), ast_sip_initialize_sorcery_transport(), ast_sorcery_alloc(), ast_sorcery_copy(), ast_sorcery_create(), ast_sorcery_delete(), ast_sorcery_diff(), ast_sorcery_force_reload(), ast_sorcery_force_reload_object(), ast_sorcery_get_module(), ast_sorcery_get_object_type(), ast_sorcery_get_wizard_mapping(), ast_sorcery_get_wizard_mapping_count(), ast_sorcery_instance_observer_add(), ast_sorcery_instance_observer_remove(), ast_sorcery_is_stale(), ast_sorcery_load(), ast_sorcery_load_object(), ast_sorcery_object_fields_register(), ast_sorcery_object_set_congestion_levels(), ast_sorcery_object_set_copy_handler(), ast_sorcery_object_set_diff_handler(), ast_sorcery_object_unregister(), ast_sorcery_objectset_apply(), ast_sorcery_objectset_create2(), ast_sorcery_objectset_json_create(), ast_sorcery_observer_add(), ast_sorcery_observer_remove(), ast_sorcery_ref(), ast_sorcery_reload(), ast_sorcery_reload_object(), ast_sorcery_retrieve_by_fields(), ast_sorcery_retrieve_by_id(), ast_sorcery_retrieve_by_prefix(), ast_sorcery_retrieve_by_regex(), ast_sorcery_update(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), AST_TEST_DEFINE(), bucket_file_wizard_create(), bucket_file_wizard_delete(), bucket_file_wizard_is_stale(), bucket_file_wizard_retrieve(), bucket_file_wizard_update(), bucket_http_wizard_retrieve_id(), bucket_wizard_create(), bucket_wizard_delete(), bucket_wizard_is_stale(), bucket_wizard_retrieve(), can_reuse_registration(), create_object(), deinitialize_sorcery(), deinitialize_sorcery(), global_loaded_observer(), handle_aor(), handle_auth(), handle_auths(), handle_endpoint(), handle_export_primitives(), handle_identify(), handle_phoneprov(), handle_registrations(), incoming_ws_established_cb(), instance_created_observer(), instance_destroying_observer(), load_config(), load_module(), memory_cache_full_update(), memory_cache_populate_external(), memory_cache_populate_internal(), memory_cache_stale_check(), memory_cache_stale_check_object(), memory_cache_stale_update_full(), memory_cache_stale_update_object(), mock_retrieve_id(), object_type_loaded_observer(), object_type_registered_observer(), profile_load(), profile_reload(), reload_module(), return_sorcery_object(), sorcery_astdb_create(), sorcery_astdb_filter_objectset(), sorcery_astdb_retrieve_fields(), sorcery_astdb_retrieve_fields_common(), sorcery_astdb_retrieve_id(), sorcery_astdb_retrieve_multiple(), sorcery_astdb_retrieve_prefix(), sorcery_astdb_retrieve_regex(), sorcery_astdb_update(), sorcery_config_internal_load(), sorcery_config_load(), sorcery_config_reload(), sorcery_config_retrieve_fields(), sorcery_config_retrieve_multiple(), sorcery_config_retrieve_prefix(), sorcery_config_retrieve_regex(), sorcery_destructor(), sorcery_function_read(), sorcery_is_configuration_met(), sorcery_is_explicit_name_met(), sorcery_memory_cache_ami_populate(), sorcery_memory_cache_create(), sorcery_memory_cache_load(), sorcery_memory_cache_populate(), sorcery_memory_cache_retrieve_fields(), sorcery_memory_cache_retrieve_id(), sorcery_memory_cache_retrieve_multiple(), sorcery_memory_cache_retrieve_prefix(), sorcery_memory_cache_retrieve_regex(), sorcery_memory_cached_object_alloc(), sorcery_memory_retrieve_fields(), sorcery_memory_retrieve_multiple(), sorcery_memory_retrieve_prefix(), sorcery_memory_retrieve_regex(), sorcery_realtime_create(), sorcery_realtime_filter_objectset(), sorcery_realtime_retrieve_fields(), sorcery_realtime_retrieve_id(), sorcery_realtime_retrieve_multiple(), sorcery_realtime_retrieve_prefix(), sorcery_realtime_retrieve_regex(), sorcery_realtime_update(), sorcery_reloadable(), sorcery_test_retrieve_id(), sorcery_wizard_load(), stale_cache_update_task_data_alloc(), stale_update_task_data_alloc(), tn_config_load(), tn_config_reload(), transport_apply(), unload_module(), vs_config_load(), vs_config_reload(), webchan_call(), webchan_request(), and wizard_apply_handler().

◆ websocket_media_direction_map

const char* websocket_media_direction_map[]
static
Initial value:

Definition at line 81 of file chan_websocket.c.

81 {
85};

◆ websocket_options

const struct ast_app_option websocket_options[128] = { [ 'c' ] = { .flag = OPT_WS_CODEC , .arg_index = OPT_ARG_WS_CODEC + 1 }, [ 'n' ] = { .flag = OPT_WS_NO_AUTO_ANSWER }, [ 'v' ] = { .flag = OPT_WS_URI_PARAM , .arg_index = OPT_ARG_WS_URI_PARAM + 1 }, [ 'p' ] = { .flag = OPT_WS_PASSTHROUGH }, [ 'f' ] = { .flag = OPT_WS_MSG_FORMAT , .arg_index = OPT_ARG_WS_MSG_FORMAT + 1 }, [ 'd' ] = { .flag = OPT_WS_MEDIA_DIRECTION , .arg_index = OPT_ARG_WS_MEDIA_DIRECTION + 1 }, [ 'u' ] = { .flag = OPT_WS_UNBUFFERED }, }
static

Definition at line 1698 of file chan_websocket.c.

Referenced by webchan_request().

◆ websocket_tech

struct ast_channel_tech websocket_tech
static

Definition at line 164 of file chan_websocket.c.

164 {
165 .type = "WebSocket",
166 .description = "Media over WebSocket Channel Driver",
167 .requester = webchan_request,
168 .call = webchan_call,
169 .read = webchan_read,
170 .write = webchan_write,
171 .hangup = webchan_hangup,
172 .send_digit_end = webchan_send_dtmf_text,
173};

Referenced by load_module(), unload_module(), and webchan_request().