Debian Codegraph @

channels/chan_websocket.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2025, Sangoma Technologies Corporation
5 *
6 * George Joseph <[email protected]>
7 *
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
13 *
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
17 */
18
19 /*! \file
20 *
21 * \author George Joseph <[email protected]>
22 *
23 * \brief Websocket Media Channel
24 *
25 * \ingroup channel_drivers
26 */
27
28 /*** MODULEINFO
29 <depend>res_http_websocket</depend>
30 <depend>res_websocket_client</depend>
31 <support_level>core</support_level>
32 ***/
33
34 #include "asterisk.h"
35
36 #include "asterisk/app.h"
37 #include "asterisk/causes.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/codec.h"
40 #include "asterisk/http_websocket.h"
41 #include "asterisk/format_cache.h"
42 #include "asterisk/frame.h"
43 #include "asterisk/json.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/mod_format.h"
46 #include "asterisk/module.h"
47 #include "asterisk/pbx.h"
48 #include "asterisk/uuid.h"
49 #include "asterisk/timing.h"
50 #include "asterisk/translate.h"
51 #include "asterisk/websocket_client.h"
52 #include "asterisk/sorcery.h"
53
54 static struct ast_sorcery *sorcery = NULL;
55
56 enum webchan_control_msg_format {
57 WEBCHAN_CONTROL_MSG_FORMAT_PLAIN = 0,
58 WEBCHAN_CONTROL_MSG_FORMAT_JSON,
59 WEBCHAN_CONTROL_MSG_FORMAT_INVALID,
60 };
61
62 static const char *msg_format_map[] = {
63 [WEBCHAN_CONTROL_MSG_FORMAT_PLAIN] = "plain-text",
64 [WEBCHAN_CONTROL_MSG_FORMAT_JSON] = "json",
65 [WEBCHAN_CONTROL_MSG_FORMAT_INVALID] = "invalid",
66 };
67
68 struct webchan_conf_global {
69 SORCERY_OBJECT(details);
70 enum webchan_control_msg_format control_msg_format;
71 };
72
73 /* This is from the perspective of the app, NOT Asterisk */
74 enum webchan_media_direction {
75 WEBCHAN_MEDIA_DIRECTION_BOTH,
76 WEBCHAN_MEDIA_DIRECTION_OUT,
77 WEBCHAN_MEDIA_DIRECTION_IN,
78 };
79
80 static const char *websocket_media_direction_map[] = {
81 [WEBCHAN_MEDIA_DIRECTION_BOTH] = "both",
82 [WEBCHAN_MEDIA_DIRECTION_OUT] = "out",
83 [WEBCHAN_MEDIA_DIRECTION_IN] = "in",
84 };
85
86 static struct ast_websocket_server *ast_ws_server;
87
88 static struct ao2_container *instances = NULL;
89
90 struct websocket_pvt {
91 enum ast_websocket_type type;
92 struct ast_websocket_client *client;
93 struct ast_websocket *websocket;
94 struct ast_format *native_format;
95 struct ast_codec *native_codec;
96 struct ast_channel *channel;
97 struct ast_timer *timer;
98 AST_LIST_HEAD(, ast_frame) frame_queue;
99 pthread_t outbound_read_thread;
100 size_t bytes_read;
101 size_t leftover_len;
102 char *remote_addr;
103 char *uri_params;
104 char *leftover_data;
105 enum webchan_control_msg_format control_msg_format;
106 int no_auto_answer;
107 int passthrough;
108 int optimal_frame_size;
109 int bulk_media_in_progress;
110 int report_queue_drained;
111 int frame_queue_length;
112 int queue_full;
113 int queue_paused;
114 int media_direction;
115 char connection_id[0];
116 };
117
118 /*
119 * These are the indexes in the channel's file descriptor array
120 * not the file descriptors themselves.
121 */
122 #define WS_TIMER_FDNO (AST_EXTENDED_FDS + 1)
123 #define WS_WEBSOCKET_FDNO (AST_EXTENDED_FDS + 2)
124
125 #define MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE "MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE"
126 #define MEDIA_WEBSOCKET_CONNECTION_ID "MEDIA_WEBSOCKET_CONNECTION_ID"
127 #define INCOMING_CONNECTION_ID "INCOMING"
128
129 #define ANSWER_CHANNEL "ANSWER"
130 #define HANGUP_CHANNEL "HANGUP"
131 #define START_MEDIA_BUFFERING "START_MEDIA_BUFFERING"
132 #define STOP_MEDIA_BUFFERING "STOP_MEDIA_BUFFERING"
133 #define MARK_MEDIA "MARK_MEDIA"
134 #define FLUSH_MEDIA "FLUSH_MEDIA"
135 #define GET_DRIVER_STATUS "GET_STATUS"
136 #define REPORT_QUEUE_DRAINED "REPORT_QUEUE_DRAINED"
137 #define PAUSE_MEDIA "PAUSE_MEDIA"
138 #define CONTINUE_MEDIA "CONTINUE_MEDIA"
139 #define SET_MEDIA_DIRECTION "SET_MEDIA_DIRECTION"
140
141 #define QUEUE_LENGTH_MAX 1000
142 #define QUEUE_LENGTH_XOFF_LEVEL 900
143 #define QUEUE_LENGTH_XON_LEVEL 800
144 #define MAX_TEXT_MESSAGE_LEN MIN(128, (AST_WEBSOCKET_MAX_RX_PAYLOAD_SIZE - 1))
145
146 /* Forward declarations */
147 static int read_from_ws_and_queue(struct websocket_pvt *instance);
148 static void _websocket_request_hangup(struct websocket_pvt *instance, int ast_cause,
149 enum ast_websocket_status_code tech_cause, int line, const char *function);
150 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);
151 static int webchan_call(struct ast_channel *ast, const char *dest, int timeout);
152 static struct ast_frame *webchan_read(struct ast_channel *ast);
153 static int webchan_write(struct ast_channel *ast, struct ast_frame *f);
154 static int webchan_hangup(struct ast_channel *ast);
155 static int webchan_send_dtmf_text(struct ast_channel *ast, char digit, unsigned int duration);
156 static int set_channel_timer(struct websocket_pvt *instance);
157
158 #define websocket_request_hangup(_instance, _cause, _tech) \
159 _websocket_request_hangup(_instance, _cause, _tech, __LINE__, __FUNCTION__)
160
161 static struct ast_channel_tech websocket_tech = {
162 .type = "WebSocket",
163 .description = "Media over WebSocket Channel Driver",
164 .requester = webchan_request,
165 .call = webchan_call,
166 .read = webchan_read,
167 .write = webchan_write,
168 .hangup = webchan_hangup,
169 .send_digit_end = webchan_send_dtmf_text,
170 };
171
172 static enum webchan_control_msg_format control_msg_format_from_str(const char *value)
173 {
174 if (ast_strlen_zero(value)) {
175 return WEBCHAN_CONTROL_MSG_FORMAT_INVALID;
176 } else if (strcasecmp(value, msg_format_map[WEBCHAN_CONTROL_MSG_FORMAT_PLAIN]) == 0) {
177 return WEBCHAN_CONTROL_MSG_FORMAT_PLAIN;
178 } else if (strcasecmp(value, msg_format_map[WEBCHAN_CONTROL_MSG_FORMAT_JSON]) == 0) {
179 return WEBCHAN_CONTROL_MSG_FORMAT_JSON;
180 } else {
181 return WEBCHAN_CONTROL_MSG_FORMAT_INVALID;
182 }
183 }
184
185 static const char *control_msg_format_to_str(enum webchan_control_msg_format value)
186 {
187 if (!ARRAY_IN_BOUNDS(value, msg_format_map)) {
188 return NULL;
189 }
190 return msg_format_map[value];
191 }
192
193 /*!
194 * \internal
195 * \brief Catch-all to print events that don't have any data.
196 * \warning Do not call directly.
197 */
198 static char *_create_event_nodata(struct websocket_pvt *instance, char *event)
199 {
200 char *payload = NULL;
201 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
202 struct ast_json * msg = ast_json_pack("{ s:s s:s }",
203 "event", event,
204 "channel_id", ast_channel_uniqueid(instance->channel));
205 if (!msg) {
206 return NULL;
207 }
208 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
209 ast_json_unref(msg);
210 } else {
211 payload = ast_strdup(event);
212 }
213
214 return payload;
215 }
216
217 #define _create_event_MEDIA_XON(_instance) _create_event_nodata(_instance, "MEDIA_XON");
218 #define _create_event_MEDIA_XOFF(_instance) _create_event_nodata(_instance, "MEDIA_XOFF");
219 #define _create_event_QUEUE_DRAINED(_instance) _create_event_nodata(_instance, "QUEUE_DRAINED");
220
221 /*!
222 * \internal
223 * \brief Print the MEDIA_START event.
224 * \warning Do not call directly.
225 */
226 static char *_create_event_MEDIA_START(struct websocket_pvt *instance)
227 {
228 char *payload = NULL;
229
230 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
231 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s, s:s, s:s, s:i, s:i, s:o }",
232 "event", "MEDIA_START",
233 "connection_id", instance->connection_id,
234 "channel", ast_channel_name(instance->channel),
235 "channel_id", ast_channel_uniqueid(instance->channel),
236 "format", ast_format_get_name(instance->native_format),
237 "optimal_frame_size", instance->optimal_frame_size,
238 "ptime", instance->native_codec->default_ms,
239 "channel_variables", ast_json_channel_vars(ast_channel_varshead(
240 instance->channel))
241 );
242 if (!msg) {
243 return NULL;
244 }
245 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
246 ast_json_unref(msg);
247 } else {
248 ast_asprintf(&payload, "%s %s:%s %s:%s %s:%s %s:%s %s:%d %s:%d",
249 "MEDIA_START",
250 "connection_id", instance->connection_id,
251 "channel", ast_channel_name(instance->channel),
252 "channel_id", ast_channel_uniqueid(instance->channel),
253 "format", ast_format_get_name(instance->native_format),
254 "optimal_frame_size", instance->optimal_frame_size,
255 "ptime", instance->native_codec->default_ms
256 );
257 }
258
259 return payload;
260 }
261
262 /*!
263 * \internal
264 * \brief Print the MEDIA_BUFFERING_COMPLETED event.
265 * \warning Do not call directly.
266 */
267 static char *_create_event_MEDIA_BUFFERING_COMPLETED(struct websocket_pvt *instance,
268 const char *id)
269 {
270 char *payload = NULL;
271 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
272 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s}",
273 "event", "MEDIA_BUFFERING_COMPLETED",
274 "channel_id", ast_channel_uniqueid(instance->channel),
275 "correlation_id", S_OR(id, "")
276 );
277 if (!msg) {
278 return NULL;
279 }
280 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
281 ast_json_unref(msg);
282 } else {
283 ast_asprintf(&payload, "%s%s%s",
284 "MEDIA_BUFFERING_COMPLETED",
285 S_COR(id, " ",""), S_OR(id, ""));
286
287 }
288
289 return payload;
290 }
291
292 /*!
293 * \internal
294 * \brief Print the MEDIA_MARK_PROCESSED event.
295 * \warning Do not call directly.
296 */
297 static char *_create_event_MEDIA_MARK_PROCESSED(struct websocket_pvt *instance,
298 const char *id)
299 {
300 char *payload = NULL;
301 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
302 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s}",
303 "event", "MEDIA_MARK_PROCESSED",
304 "channel_id", ast_channel_uniqueid(instance->channel),
305 "correlation_id", S_OR(id, "")
306 );
307 if (!msg) {
308 return NULL;
309 }
310 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
311 ast_json_unref(msg);
312 } else {
313 ast_asprintf(&payload, "%s%s%s",
314 "MEDIA_MARK_PROCESSED",
315 S_COR(id, " ",""), S_OR(id, ""));
316
317 }
318
319 return payload;
320 }
321
322 /*!
323 * \internal
324 * \brief Print the DTMF_END event.
325 * \warning Do not call directly.
326 */
327 static char *_create_event_DTMF_END(struct websocket_pvt *instance,
328 const char digit)
329 {
330 char *payload = NULL;
331 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
332 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s#}",
333 "event", "DTMF_END",
334 "channel_id", ast_channel_uniqueid(instance->channel),
335 "digit", &digit, 1
336 );
337 if (!msg) {
338 return NULL;
339 }
340 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
341 ast_json_unref(msg);
342 } else {
343 ast_asprintf(&payload, "%s digit:%c channel_id:%s",
344 "DTMF_END", digit, ast_channel_uniqueid(instance->channel));
345 }
346
347 return payload;
348 }
349
350 /*!
351 * \internal
352 * \brief Print the STATUS event.
353 * \warning Do not call directly.
354 */
355 static char *_create_event_STATUS(struct websocket_pvt *instance)
356 {
357 char *payload = NULL;
358
359 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
360 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:i, s:i, s:i, s:b, s:b, s:b }",
361 "event", "STATUS",
362 "channel_id", ast_channel_uniqueid(instance->channel),
363 "queue_length", instance->frame_queue_length,
364 "xon_level", QUEUE_LENGTH_XON_LEVEL,
365 "xoff_level", QUEUE_LENGTH_XOFF_LEVEL,
366 "queue_full", instance->queue_full,
367 "bulk_media", instance->bulk_media_in_progress,
368 "media_paused", instance->queue_paused
369 );
370 if (!msg) {
371 return NULL;
372 }
373 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
374 ast_json_unref(msg);
375 } else {
376 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",
377 "STATUS",
378 ast_channel_uniqueid(instance->channel),
379 instance->frame_queue_length, QUEUE_LENGTH_XON_LEVEL,
380 QUEUE_LENGTH_XOFF_LEVEL,
381 S_COR(instance->queue_full, "true", "false"),
382 S_COR(instance->bulk_media_in_progress, "true", "false"),
383 S_COR(instance->queue_paused, "true", "false")
384 );
385 }
386
387 return payload;
388 }
389
390 /*!
391 * \internal
392 * \brief Print the ERROR event.
393 * \warning Do not call directly.
394 */
395 static __attribute__ ((format (gnu_printf, 2, 3))) char *_create_event_ERROR(
396 struct websocket_pvt *instance, const char *format, ...)
397 {
398 char *payload = NULL;
399 char *error_text = NULL;
400 va_list ap;
401 int res = 0;
402
403 va_start(ap, format);
404 res = ast_vasprintf(&error_text, format, ap);
405 va_end(ap);
406 if (res < 0 || !error_text) {
407 return NULL;
408 }
409
410 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
411 struct ast_json *msg = ast_json_pack("{s:s, s:s, s:s}",
412 "event", "ERROR",
413 "channel_id", ast_channel_uniqueid(instance->channel),
414 "error_text", error_text);
415 ast_free(error_text);
416 if (!msg) {
417 return NULL;
418 }
419 payload = ast_json_dump_string_format(msg, AST_JSON_COMPACT);
420 ast_json_unref(msg);
421 } else {
422 ast_asprintf(&payload, "%s channel_id:%s error_text:%s",
423 "ERROR", ast_channel_uniqueid(instance->channel), error_text);
424 ast_free(error_text);
425 }
426
427 return payload;
428 }
429
430 /*!
431 * \def create_event
432 * \brief Use this macro to create events passing in any event-specific parameters.
433 */
434 #define create_event(_instance, _event, ...) \
435 _create_event_ ## _event(_instance, ##__VA_ARGS__)
436
437 /*!
438 * \def send_event
439 * \brief Use this macro to create and send events passing in any event-specific parameters.
440 */
441 #define send_event(_instance, _event, ...) \
442 ({ \
443 int _res = -1; \
444 char *_payload = _create_event_ ## _event(_instance, ##__VA_ARGS__); \
445 if (_payload && _instance->websocket) { \
446 _res = ast_websocket_write_string(_instance->websocket, _payload); \
447 if (_res != 0) { \
448 ast_log(LOG_ERROR, "%s: Unable to send event %s\n", \
449 ast_channel_name(instance->channel), _payload); \
450 } else { \
451 ast_debug(3, "%s: Sent %s\n", \
452 ast_channel_name(instance->channel), _payload); \
453 }\
454 ast_free(_payload); \
455 } \
456 (_res); \
457 })
458
459 /*
460 * Reminder... This function gets called by webchan_read which is
461 * triggered by the channel timer firing. It always gets called
462 * every 20ms (or whatever the timer is set to) even if there are
463 * no frames in the queue.
464 */
465 static struct ast_frame *dequeue_frame(struct websocket_pvt *instance)
466 {
467 struct ast_frame *queued_frame = NULL;
468 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
469 AST_LIST_UNLOCK);
470
471 /*
472 * If the queue is paused, don't read a frame. Processing
473 * will continue down the function and a silence frame will
474 * be sent in its place.
475 */
476 if (instance->queue_paused) {
477 return NULL;
478 }
479
480 /*
481 * We need to check if we need to send an XON before anything
482 * else because there are multiple escape paths in this function
483 * and we don't want to accidentally keep the queue in a "full"
484 * state.
485 */
486 if (instance->queue_full && instance->frame_queue_length < QUEUE_LENGTH_XON_LEVEL) {
487 instance->queue_full = 0;
488 ast_debug(4, "%s: WebSocket sending MEDIA_XON\n",
489 ast_channel_name(instance->channel));
490 send_event(instance, MEDIA_XON);
491 }
492
493 queued_frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list);
494
495 /*
496 * If there are no frames in the queue, we need to
497 * return NULL so we can send a silence frame. We also need
498 * to send the QUEUE_DRAINED notification if we were requested
499 * to do so.
500 */
501 if (!queued_frame) {
502 if (instance->report_queue_drained) {
503 instance->report_queue_drained = 0;
504 ast_debug(4, "%s: WebSocket sending QUEUE_DRAINED\n",
505 ast_channel_name(instance->channel));
506 send_event(instance, QUEUE_DRAINED);
507 }
508 return NULL;
509 }
510
511 /*
512 * The only way a control frame could be present here is as
513 * a result of us calling queue_option_frame() in response
514 * to an incoming TEXT command from the websocket.
515 * We'll be safe and make sure it's a AST_CONTROL_OPTION
516 * frame anyway.
517 *
518 * It's quite possible that there are multiple control frames
519 * in a row in the queue so we need to process consecutive ones
520 * immediately.
521 *
522 * In any case, processing a control frame MUST not use up
523 * a media timeslot so after all control frames have been
524 * processed, we need to read an audio frame and process it.
525 */
526 while (queued_frame && queued_frame->frametype == AST_FRAME_CONTROL) {
527 if (queued_frame->subclass.integer == AST_CONTROL_OPTION) {
528 /*
529 * We just need to send the data to the websocket.
530 * The data should already be NULL terminated.
531 */
532 ast_websocket_write_string(instance->websocket,
533 queued_frame->data.ptr);
534 ast_debug(4, "%s: Sent %s\n",
535 ast_channel_name(instance->channel), (char *)queued_frame->data.ptr);
536 }
537 /*
538 * We do NOT send these to the core so we need to free
539 * the frame and grab the next one. If it's also a
540 * control frame, we need to process it otherwise
541 * continue down in the function.
542 */
543 ast_frame_free(queued_frame, 0);
544 queued_frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list);
545 /*
546 * Jut FYI... We didn't bump the queue length when we added the control
547 * frames so we don't need to decrement it here.
548 */
549 }
550
551 /*
552 * If, after reading all control frames, there are no frames
553 * left in the queue, we need to return NULL so we can send
554 * a silence frame.
555 */
556 if (!queued_frame) {
557 return NULL;
558 }
559
560 instance->frame_queue_length--;
561
562 return queued_frame;
563 }
564 /*!
565 * \internal
566 *
567 * There are two file descriptors on this channel that can trigger
568 * this function...
569 *
570 * The timer fd (WS_TIMER_FDNO) which gets triggered at a constant
571 * rate determined by the format. In this case, we need to pull a
572 * frame OFF the queue and return it to the core.
573 *
574 * The websocket fd (WS_WEBSOCKET_FDNO) which gets triggered when
575 * there's incoming data to read from the websocket. In this case,
576 * we read the data and put it ON the queue. We'll return a null frame.
577 *
578 */
579 static struct ast_frame *webchan_read(struct ast_channel *ast)
580 {
581 struct websocket_pvt *instance = NULL;
582 struct ast_frame *native_frame = NULL;
583 int fdno = ast_channel_fdno(ast);
584
585 instance = ast_channel_tech_pvt(ast);
586 if (!instance) {
587 return NULL;
588 }
589
590 if (fdno == WS_WEBSOCKET_FDNO) {
591 read_from_ws_and_queue(instance);
592 return &ast_null_frame;
593 }
594 if (fdno != WS_TIMER_FDNO) {
595 return &ast_null_frame;
596 }
597
598 if (ast_timer_get_event(instance->timer) == AST_TIMING_EVENT_EXPIRED) {
599 ast_timer_ack(instance->timer, 1);
600 }
601
602 native_frame = dequeue_frame(instance);
603
604 /*
605 * No frame when the timer fires means we have to return a null frame in its place.
606 */
607 if (!native_frame) {
608 ast_debug(4, "%s: WebSocket read timer fired with no frame available. Returning NULL frame.\n",
609 ast_channel_name(ast));
610 return &ast_null_frame;
611 }
612
613 return native_frame;
614 }
615
616 static int queue_frame_from_buffer(struct websocket_pvt *instance,
617 char *buffer, size_t len)
618 {
619 struct ast_frame fr = { 0, };
620 struct ast_frame *duped_frame = NULL;
621
622 AST_FRAME_SET_BUFFER(&fr, buffer, 0, len);
623 fr.frametype = AST_FRAME_VOICE;
624 fr.subclass.format = instance->native_format;
625 fr.samples = instance->native_codec->samples_count(&fr);
626
627 duped_frame = ast_frisolate(&fr);
628 if (!duped_frame) {
629 ast_log(LOG_WARNING, "%s: Failed to isolate frame\n",
630 ast_channel_name(instance->channel));
631 return -1;
632 }
633
634 {
635 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
636 AST_LIST_UNLOCK);
637 AST_LIST_INSERT_TAIL(&instance->frame_queue, duped_frame, frame_list);
638 instance->frame_queue_length++;
639 if (!instance->queue_full && instance->frame_queue_length >= QUEUE_LENGTH_XOFF_LEVEL) {
640 instance->queue_full = 1;
641 send_event(instance, MEDIA_XOFF);
642 }
643 }
644
645 ast_debug(5, "%s: Queued %d byte frame\n", ast_channel_name(instance->channel),
646 duped_frame->datalen);
647
648 return 0;
649 }
650
651 static int queue_option_frame(struct websocket_pvt *instance,
652 char *buffer)
653 {
654 struct ast_frame fr = { 0, };
655 struct ast_frame *duped_frame = NULL;
656
657 AST_FRAME_SET_BUFFER(&fr, buffer, 0, strlen(buffer) + 1);
658 fr.frametype = AST_FRAME_CONTROL;
659 fr.subclass.integer = AST_CONTROL_OPTION;
660
661 duped_frame = ast_frisolate(&fr);
662 if (!duped_frame) {
663 ast_log(LOG_WARNING, "%s: Failed to isolate frame\n",
664 ast_channel_name(instance->channel));
665 return -1;
666 }
667
668 AST_LIST_LOCK(&instance->frame_queue);
669 AST_LIST_INSERT_TAIL(&instance->frame_queue, duped_frame, frame_list);
670 AST_LIST_UNLOCK(&instance->frame_queue);
671
672 ast_debug(4, "%s: Queued '%s' option frame\n",
673 ast_channel_name(instance->channel), buffer);
674
675 return 0;
676 }
677
678 #define ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command) \
679 ({ \
680 if (instance->passthrough) { \
681 send_event(instance, ERROR, "%s not supported in passthrough mode", command); \
682 ast_debug(4, "%s: WebSocket in passthrough mode. Ignoring %s command.\n", \
683 ast_channel_name(instance->channel), command); \
684 return 0; \
685 } \
686 })
687
688 #define ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, direction) \
689 ({ \
690 if (instance->media_direction == direction) { \
691 send_event(instance, ERROR, "%s not supported while media direction " \
692 "is '%s'", command, websocket_media_direction_map[direction]); \
693 ast_debug(4, "%s: WebSocket media direction is '%s'. Ignoring %s command.\n", \
694 ast_channel_name(instance->channel), websocket_media_direction_map[direction], command); \
695 return 0; \
696 } \
697 })
698
699 /*!
700 * \internal
701 * \brief Handle commands from the websocket
702 *
703 * \param instance
704 * \param buffer Allocated by caller so don't free.
705 * \retval 0 Success
706 * \retval -1 Failure
707 */
708 static int handle_command(struct websocket_pvt *instance, char *buffer)
709 {
710 int res = 0;
711 RAII_VAR(struct ast_json *, json, NULL, ast_json_unref);
712 const char *command = NULL;
713 char *data = NULL;
714
715 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
716 struct ast_json_error json_error;
717
718 json = ast_json_load_buf(buffer, strlen(buffer), &json_error);
719 if (!json) {
720 send_event(instance, ERROR, "Unable to parse JSON command");
721 return -1;
722 }
723 command = ast_json_object_string_get(json, "command");
724 } else {
725 command = buffer;
726 data = strchr(buffer, ' ');
727 if (data) {
728 *data = '\0';
729 data++;
730 }
731 }
732
733 if (ast_strings_equal(command, ANSWER_CHANNEL)) {
734 ast_queue_control(instance->channel, AST_CONTROL_ANSWER);
735
736 } else if (ast_strings_equal(command, HANGUP_CHANNEL)) {
737 websocket_request_hangup(instance, AST_CAUSE_NORMAL, AST_WEBSOCKET_STATUS_NORMAL);
738
739 } else if (ast_strings_equal(command, START_MEDIA_BUFFERING)) {
740 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
741 ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, WEBCHAN_MEDIA_DIRECTION_IN);
742 AST_LIST_LOCK(&instance->frame_queue);
743 instance->bulk_media_in_progress = 1;
744 AST_LIST_UNLOCK(&instance->frame_queue);
745
746 } else if (ast_strings_equal(command, STOP_MEDIA_BUFFERING)) {
747 const char *id;
748 char *option;
749 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
750 AST_LIST_UNLOCK);
751
752 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
753 id = ast_json_object_string_get(json, "correlation_id");
754 } else {
755 id = data;
756 }
757
758 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
759 ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, WEBCHAN_MEDIA_DIRECTION_IN);
760
761 ast_debug(4, "%s: WebSocket %s '%s' with %d bytes in leftover_data.\n",
762 ast_channel_name(instance->channel), STOP_MEDIA_BUFFERING, id,
763 (int)instance->leftover_len);
764
765 instance->bulk_media_in_progress = 0;
766 if (instance->leftover_len > 0) {
767 res = queue_frame_from_buffer(instance, instance->leftover_data, instance->leftover_len);
768 if (res != 0) {
769 return res;
770 }
771 }
772 instance->leftover_len = 0;
773 option = create_event(instance, MEDIA_BUFFERING_COMPLETED, id);
774 if (!option) {
775 return -1;
776 }
777 res = queue_option_frame(instance, option);
778 ast_free(option);
779
780 } else if (ast_strings_equal(command, MARK_MEDIA)) {
781 const char *id;
782 char *option;
783 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
784 AST_LIST_UNLOCK);
785
786 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
787 ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, WEBCHAN_MEDIA_DIRECTION_IN);
788
789 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
790 id = ast_json_object_string_get(json, "correlation_id");
791 } else {
792 id = data;
793 }
794
795 ast_debug(4, "%s: %s %s\n",
796 ast_channel_name(instance->channel), MARK_MEDIA, id);
797
798 option = create_event(instance, MEDIA_MARK_PROCESSED, id);
799 if (!option) {
800 return -1;
801 }
802 res = queue_option_frame(instance, option);
803 ast_free(option);
804
805 } else if (ast_strings_equal(command, FLUSH_MEDIA)) {
806 struct ast_frame *frame = NULL;
807
808 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
809
810 AST_LIST_LOCK(&instance->frame_queue);
811 while ((frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list))) {
812 ast_frfree(frame);
813 }
814 instance->frame_queue_length = 0;
815 instance->bulk_media_in_progress = 0;
816 instance->leftover_len = 0;
817 AST_LIST_UNLOCK(&instance->frame_queue);
818
819 } else if (ast_strings_equal(command, REPORT_QUEUE_DRAINED)) {
820 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
821
822 AST_LIST_LOCK(&instance->frame_queue);
823 instance->report_queue_drained = 1;
824 AST_LIST_UNLOCK(&instance->frame_queue);
825
826 } else if (ast_strings_equal(command, GET_DRIVER_STATUS)) {
827 return send_event(instance, STATUS);
828
829 } else if (ast_strings_equal(command, PAUSE_MEDIA)) {
830 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
831 ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, WEBCHAN_MEDIA_DIRECTION_IN);
832 AST_LIST_LOCK(&instance->frame_queue);
833 instance->queue_paused = 1;
834 AST_LIST_UNLOCK(&instance->frame_queue);
835
836 } else if (ast_strings_equal(command, CONTINUE_MEDIA)) {
837 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
838 ERROR_ON_INVALID_MEDIA_DIRECTION_RTN(instance, command, WEBCHAN_MEDIA_DIRECTION_IN);
839 AST_LIST_LOCK(&instance->frame_queue);
840 instance->queue_paused = 0;
841 AST_LIST_UNLOCK(&instance->frame_queue);
842
843 } else if (ast_strings_equal(command, SET_MEDIA_DIRECTION)) {
844 const char *direction;
845
846 ERROR_ON_PASSTHROUGH_MODE_RTN(instance, command);
847
848 if (instance->control_msg_format != WEBCHAN_CONTROL_MSG_FORMAT_JSON) {
849 send_event(instance, ERROR, "%s only supports JSON format.\n", command);
850 return 0;
851 }
852
853 direction = ast_json_object_string_get(json, "direction");
854 if (!direction) {
855 send_event(instance, ERROR, "%s requires a 'direction' parameter.\n", command);
856 return 0;
857 }
858
859 if (!strcmp("both", direction)) {
860 if (instance->media_direction == WEBCHAN_MEDIA_DIRECTION_BOTH) {
861 return 0;
862 }
863
864 if (!instance->timer) {
865 set_channel_timer(instance);
866 ast_queue_frame(instance->channel, &ast_null_frame);
867 }
868
869 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_BOTH;
870
871 } else if (!strcmp("out", direction)) {
872 if (instance->media_direction == WEBCHAN_MEDIA_DIRECTION_OUT) {
873 return 0;
874 }
875
876 if (!instance->timer) {
877 set_channel_timer(instance);
878 ast_queue_frame(instance->channel, &ast_null_frame);
879 }
880
881 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_OUT;
882
883 } else if (!strcmp("in", direction)) {
884 if (instance->media_direction == WEBCHAN_MEDIA_DIRECTION_IN) {
885 return 0;
886 }
887
888 if (instance->timer) {
889 ast_channel_internal_fd_clear(instance->channel, WS_TIMER_FDNO);
890 ast_timer_close(instance->timer);
891 instance->timer = NULL;
892 ast_queue_frame(instance->channel, &ast_null_frame);
893 }
894
895 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_IN;
896
897 } else {
898 send_event(instance, ERROR, "'%s' is not a valid direction for %s.\n",
899 direction, command);
900 return 0;
901 }
902
903 } else {
904 ast_log(LOG_WARNING, "%s: WebSocket %s command unknown\n",
905 ast_channel_name(instance->channel), command);
906 }
907
908 return res;
909 }
910
911 static int process_text_message(struct websocket_pvt *instance,
912 char *payload, uint64_t payload_len)
913 {
914 char *command;
915
916 if (payload_len == 0) {
917 ast_log(LOG_WARNING, "%s: WebSocket TEXT message has 0 length\n",
918 ast_channel_name(instance->channel));
919 return 0;
920 }
921
922 if (payload_len > MAX_TEXT_MESSAGE_LEN) {
923 ast_log(LOG_WARNING, "%s: WebSocket TEXT message of length %d exceeds maximum length of %d\n",
924 ast_channel_name(instance->channel), (int)payload_len, MAX_TEXT_MESSAGE_LEN);
925 return 0;
926 }
927
928 /*
929 * Unfortunately, payload is not NULL terminated even when it's
930 * a TEXT frame so we need to allocate a new buffer, copy
931 * the data into it, and NULL terminate it.
932 */
933 command = ast_alloca(payload_len + 1);
934 memcpy(command, payload, payload_len); /* Safe */
935 command[payload_len] = '\0';
936 command = ast_strip(command);
937
938 ast_debug(4, "%s: Received: %s\n",
939 ast_channel_name(instance->channel), command);
940
941 return handle_command(instance, command);
942 }
943
944 static int process_binary_message(struct websocket_pvt *instance,
945 char *payload, uint64_t payload_len)
946 {
947 char *next_frame_ptr = NULL;
948 size_t bytes_read = 0;
949 int res = 0;
950 size_t bytes_left = 0;
951
952 {
953 SCOPED_LOCK(frame_queue_lock, &instance->frame_queue, AST_LIST_LOCK,
954 AST_LIST_UNLOCK);
955 if (instance->frame_queue_length >= QUEUE_LENGTH_MAX) {
956 ast_debug(4, "%s: WebSocket queue is full. Ignoring incoming binary message.\n",
957 ast_channel_name(instance->channel));
958 return 0;
959 }
960 }
961
962 next_frame_ptr = payload;
963 instance->bytes_read += payload_len;
964
965 if (instance->passthrough) {
966 res = queue_frame_from_buffer(instance, payload, payload_len);
967 return res;
968 }
969
970 if (instance->bulk_media_in_progress && instance->leftover_len > 0) {
971 /*
972 * We have leftover data from a previous websocket message.
973 * Try to make a complete frame by appending data from
974 * the current message to the leftover data.
975 */
976 char *append_ptr = instance->leftover_data + instance->leftover_len;
977 size_t bytes_needed_for_frame = instance->optimal_frame_size - instance->leftover_len;
978 /*
979 * It's possible that even the current message doesn't have enough
980 * data to make a complete frame.
981 */
982 size_t bytes_avail_to_copy = MIN(bytes_needed_for_frame, payload_len);
983
984 /*
985 * Append whatever we can to the end of the leftover data
986 * even if it's not enough to make a complete frame.
987 */
988 memcpy(append_ptr, payload, bytes_avail_to_copy);
989
990 /*
991 * If leftover data is still short, just return and wait for the
992 * next websocket message.
993 */
994 if (bytes_avail_to_copy < bytes_needed_for_frame) {
995 ast_debug(4, "%s: Leftover data %d bytes but only %d new bytes available of %d needed. Appending and waiting for next message.\n",
996 ast_channel_name(instance->channel), (int)instance->leftover_len, (int)bytes_avail_to_copy, (int)bytes_needed_for_frame);
997 instance->leftover_len += bytes_avail_to_copy;
998 return 0;
999 }
1000
1001 res = queue_frame_from_buffer(instance, instance->leftover_data, instance->optimal_frame_size);
1002 if (res < 0) {
1003 return -1;
1004 }
1005
1006 /*
1007 * We stole data from the current payload so decrement payload_len
1008 * and set the next frame pointer after the data in payload
1009 * we just copied.
1010 */
1011 payload_len -= bytes_avail_to_copy;
1012 next_frame_ptr = payload + bytes_avail_to_copy;
1013
1014 ast_debug(5, "%s: --- BR: %4d FQ: %4d PL: %4d LOL: %3d P: %p NFP: %p OFF: %4d NPL: %4d BAC: %3d\n",
1015 ast_channel_name(instance->channel),
1016 instance->frame_queue_length,
1017 (int)instance->bytes_read,
1018 (int)(payload_len + bytes_avail_to_copy),
1019 (int)instance->leftover_len,
1020 payload,
1021 next_frame_ptr,
1022 (int)(next_frame_ptr - payload),
1023 (int)payload_len,
1024 (int)bytes_avail_to_copy
1025 );
1026
1027
1028 instance->leftover_len = 0;
1029 }
1030
1031 if (!instance->bulk_media_in_progress && instance->leftover_len > 0) {
1032 instance->leftover_len = 0;
1033 }
1034
1035 bytes_left = payload_len;
1036 while (bytes_read < payload_len && bytes_left >= instance->optimal_frame_size) {
1037 res = queue_frame_from_buffer(instance, next_frame_ptr,
1038 instance->optimal_frame_size);
1039 if (res < 0) {
1040 break;
1041 }
1042 bytes_read += instance->optimal_frame_size;
1043 next_frame_ptr += instance->optimal_frame_size;
1044 bytes_left -= instance->optimal_frame_size;
1045 }
1046
1047 if (instance->bulk_media_in_progress && bytes_left > 0) {
1048 /*
1049 * We have a partial frame. Save the leftover data.
1050 */
1051 ast_debug(5, "%s: +++ BR: %4d FQ: %4d PL: %4d LOL: %3d P: %p NFP: %p OFF: %4d BL: %4d\n",
1052 ast_channel_name(instance->channel),
1053 (int)instance->bytes_read,
1054 instance->frame_queue_length,
1055 (int)payload_len,
1056 (int)instance->leftover_len,
1057 payload,
1058 next_frame_ptr,
1059 (int)(next_frame_ptr - payload),
1060 (int)bytes_left
1061 );
1062 memcpy(instance->leftover_data, next_frame_ptr, bytes_left);
1063 instance->leftover_len = bytes_left;
1064 }
1065
1066 return 0;
1067 }
1068
1069 static int read_from_ws_and_queue(struct websocket_pvt *instance)
1070 {
1071 uint64_t payload_len = 0;
1072 char *payload = NULL;
1073 enum ast_websocket_opcode opcode;
1074 int fragmented = 0;
1075 int res = 0;
1076
1077 if (!instance->websocket) {
1078 ast_log(LOG_WARNING, "%s: WebSocket session not found\n",
1079 ast_channel_name(instance->channel));
1080 return -1;
1081 }
1082
1083 res = ast_websocket_read(instance->websocket, &payload, &payload_len,
1084 &opcode, &fragmented);
1085
1086 if (res) {
1087 ast_debug(3, "%s: WebSocket read error\n",
1088 ast_channel_name(instance->channel));
1089 websocket_request_hangup(instance, AST_CAUSE_NETWORK_OUT_OF_ORDER, AST_WEBSOCKET_STATUS_GOING_AWAY);
1090 return -1;
1091 }
1092 ast_debug(5, "%s: WebSocket read %d bytes\n", ast_channel_name(instance->channel),
1093 (int)payload_len);
1094
1095 if (opcode == AST_WEBSOCKET_OPCODE_TEXT) {
1096 return process_text_message(instance, payload, payload_len);
1097 }
1098
1099 /*
1100 * PINGs and PONGs will have been handled by res_http_websocket.
1101 * We also need to ignore CONTINUATION frames as they will be accumulated
1102 * by res_http_websocket until the threshold set in websocket_handoff_to_channel()
1103 * is reached, then it will send us a TEXT or BINARY frame.
1104 */
1105 if (opcode == AST_WEBSOCKET_OPCODE_PING || opcode == AST_WEBSOCKET_OPCODE_PONG
1106 || opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
1107 return 0;
1108 }
1109
1110 if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
1111 ast_debug(3, "%s: WebSocket closed by remote\n",
1112 ast_channel_name(instance->channel));
1113 websocket_request_hangup(instance, AST_CAUSE_NORMAL, AST_WEBSOCKET_STATUS_GOING_AWAY);
1114 return -1;
1115 }
1116
1117 if (opcode == AST_WEBSOCKET_OPCODE_BINARY) {
1118 /* If the application's media direction is 'in', drop any media we receive from it */
1119 if (instance->media_direction == WEBCHAN_MEDIA_DIRECTION_IN) {
1120 ast_debug(5, "%s: WebSocket dropped frame (application media direction is 'in')\n",
1121 ast_channel_name(instance->channel));
1122 return 0;
1123 }
1124 } else {
1125 ast_log(LOG_WARNING, "%s: WebSocket frame type %d not supported\n",
1126 ast_channel_name(instance->channel), (int)opcode);
1127 websocket_request_hangup(instance, AST_CAUSE_FAILURE, AST_WEBSOCKET_STATUS_UNSUPPORTED_DATA);
1128 return 0;
1129 }
1130
1131 return process_binary_message(instance, payload, payload_len);
1132 }
1133
1134 static int websocket_handoff_to_channel(struct websocket_pvt *instance)
1135 {
1136 int res = 0;
1137 int nodelay = 1;
1138 struct ast_sockaddr *remote_addr = ast_websocket_remote_address(instance->websocket);
1139
1140 instance->remote_addr = ast_strdup(ast_sockaddr_stringify(remote_addr));
1141 ast_debug(3, "%s: WebSocket connection with %s established\n",
1142 ast_channel_name(instance->channel), instance->remote_addr);
1143
1144 if (setsockopt(ast_websocket_fd(instance->websocket),
1145 IPPROTO_TCP, TCP_NODELAY, (char *) &nodelay, sizeof(nodelay)) < 0) {
1146 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on websocket connection: %s\n", strerror(errno));
1147 }
1148
1149 /*
1150 * Tell res_http_websocket to accumulate incoming WebSocket CONTINUATION frames
1151 * into chunks of 1024 bytes and send us a TEXT or BINARY frame when the threshold
1152 * is reached.
1153 */
1154 ast_websocket_reconstruct_enable(instance->websocket, 1024);
1155
1156 ast_channel_set_fd(instance->channel, WS_WEBSOCKET_FDNO, ast_websocket_fd(instance->websocket));
1157
1158 res = send_event(instance, MEDIA_START);
1159 if (res != 0 ) {
1160 if (instance->type == AST_WS_TYPE_SERVER) {
1161 websocket_request_hangup(instance, AST_CAUSE_NETWORK_OUT_OF_ORDER, AST_WEBSOCKET_STATUS_GOING_AWAY);
1162 } else {
1163 /*
1164 * We were called by webchan_call so just need to set causes.
1165 * The core will hangup the channel.
1166 */
1167 ast_channel_tech_hangupcause_set(instance->channel, AST_WEBSOCKET_STATUS_GOING_AWAY);
1168 ast_channel_hangupcause_set(instance->channel, AST_CAUSE_NETWORK_OUT_OF_ORDER);
1169 }
1170 return -1;
1171 }
1172
1173 if (!instance->no_auto_answer) {
1174 ast_debug(3, "%s: ANSWER by auto_answer\n", ast_channel_name(instance->channel));
1175 ast_queue_control(instance->channel, AST_CONTROL_ANSWER);
1176 }
1177
1178 return 0;
1179 }
1180
1181 static void _websocket_request_hangup(struct websocket_pvt *instance, int ast_cause,
1182 enum ast_websocket_status_code tech_cause, int line, const char *function)
1183 {
1184 if (!instance || !instance->channel) {
1185 return;
1186 }
1187 ast_debug(3, "%s:%s: Hangup requested from %s line %d. cause: %s(%d) tech_cause: %s(%d)",
1188 ast_channel_name(instance->channel), instance->remote_addr,
1189 function, line,
1190 ast_cause2str(ast_cause), ast_cause, ast_websocket_status_to_str(tech_cause), tech_cause);
1191
1192 if (tech_cause) {
1193 ast_channel_tech_hangupcause_set(instance->channel, tech_cause);
1194 }
1195 ast_queue_hangup_with_cause(instance->channel, ast_cause);
1196 }
1197
1198 /*! \brief Function called when we should write a frame to the channel */
1199 static int webchan_write(struct ast_channel *ast, struct ast_frame *f)
1200 {
1201 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1202
1203 if (!instance || !instance->websocket) {
1204 ast_log(LOG_WARNING, "%s: WebSocket instance or client not found\n",
1205 ast_channel_name(ast));
1206 return -1;
1207 }
1208
1209 /* The app doesn't want media right now */
1210 if (instance->media_direction == WEBCHAN_MEDIA_DIRECTION_OUT) {
1211 return 0;
1212 }
1213
1214 if (f->frametype == AST_FRAME_CNG) {
1215 return 0;
1216 }
1217
1218 if (f->frametype != AST_FRAME_VOICE) {
1219 ast_log(LOG_WARNING, "%s: This WebSocket channel only supports AST_FRAME_VOICE frames\n",
1220 ast_channel_name(ast));
1221 return 0;
1222 }
1223
1224 if (ast_format_cmp(f->subclass.format, instance->native_format) == AST_FORMAT_CMP_NOT_EQUAL) {
1225 ast_log(LOG_WARNING, "%s: This WebSocket channel only supports the '%s' format, not '%s'\n",
1226 ast_channel_name(ast), ast_format_get_name(instance->native_format),
1227 ast_format_get_name(f->subclass.format));
1228 return -1;
1229 }
1230
1231 return ast_websocket_write(instance->websocket, AST_WEBSOCKET_OPCODE_BINARY,
1232 (char *)f->data.ptr, (uint64_t)f->datalen);
1233 }
1234
1235 /*!
1236 * \internal
1237 *
1238 * Called by the core to actually call the remote.
1239 * The core will hang up the channel if a non-zero is returned.
1240 * We just need to set hangup causes if appropriate.
1241 */
1242 static int webchan_call(struct ast_channel *ast, const char *dest,
1243 int timeout)
1244 {
1245 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1246 enum ast_websocket_result result;
1247
1248 if (!instance) {
1249 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n",
1250 ast_channel_name(ast));
1251 ast_channel_hangupcause_set(ast, AST_CAUSE_FAILURE);
1252 return -1;
1253 }
1254
1255 if (instance->type == AST_WS_TYPE_SERVER) {
1256 ast_debug(3, "%s: Websocket call incoming\n", ast_channel_name(instance->channel));
1257 return 0;
1258 }
1259 ast_debug(3, "%s: Websocket call outgoing\n", ast_channel_name(instance->channel));
1260
1261 if (!instance->client) {
1262 ast_log(LOG_WARNING, "%s: WebSocket client not found\n",
1263 ast_channel_name(ast));
1264 ast_channel_hangupcause_set(ast, AST_CAUSE_FAILURE);
1265 return -1;
1266 }
1267
1268 ast_debug(3, "%s: WebSocket call requested to %s. cid: %s\n",
1269 ast_channel_name(ast), dest, instance->connection_id);
1270
1271 if (!ast_strlen_zero(instance->uri_params)) {
1272 ast_websocket_client_add_uri_params(instance->client, instance->uri_params);
1273 }
1274
1275 instance->websocket = ast_websocket_client_connect(instance->client,
1276 instance, ast_channel_name(ast), &result);
1277 if (!instance->websocket || result != WS_OK) {
1278 ast_log(LOG_WARNING, "%s: WebSocket connection failed to %s: %s\n",
1279 ast_channel_name(ast), dest, ast_websocket_result_to_str(result));
1280 ast_channel_hangupcause_set(ast, AST_CAUSE_NO_ROUTE_DESTINATION);
1281 return -1;
1282 }
1283
1284 return websocket_handoff_to_channel(instance);
1285 }
1286
1287 static void websocket_destructor(void *data)
1288 {
1289 struct websocket_pvt *instance = data;
1290 struct ast_frame *frame = NULL;
1291 ast_debug(3, "%s: WebSocket instance freed\n", instance->connection_id);
1292
1293 AST_LIST_LOCK(&instance->frame_queue);
1294 while ((frame = AST_LIST_REMOVE_HEAD(&instance->frame_queue, frame_list))) {
1295 ast_frfree(frame);
1296 }
1297 AST_LIST_UNLOCK(&instance->frame_queue);
1298
1299 if (instance->timer) {
1300 ast_timer_close(instance->timer);
1301 instance->timer = NULL;
1302 }
1303
1304 if (instance->channel) {
1305 ast_channel_unref(instance->channel);
1306 instance->channel = NULL;
1307 }
1308 if (instance->websocket) {
1309 ast_websocket_unref(instance->websocket);
1310 instance->websocket = NULL;
1311 }
1312
1313 ao2_cleanup(instance->client);
1314 instance->client = NULL;
1315
1316 ao2_cleanup(instance->native_codec);
1317 instance->native_codec = NULL;
1318
1319 ao2_cleanup(instance->native_format);
1320 instance->native_format = NULL;
1321
1322 if (instance->leftover_data) {
1323 ast_free(instance->leftover_data);
1324 instance->leftover_data = NULL;
1325 }
1326
1327 ast_free(instance->uri_params);
1328 ast_free(instance->remote_addr);
1329 }
1330
1331 struct instance_proxy {
1332 AO2_WEAKPROXY();
1333 /*! \brief The name of the module owning this sorcery instance */
1334 char connection_id[0];
1335 };
1336
1337 static void instance_proxy_cb(void *weakproxy, void *data)
1338 {
1339 struct instance_proxy *proxy = weakproxy;
1340 ast_debug(3, "%s: WebSocket instance removed from instances\n", proxy->connection_id);
1341 ao2_unlink(instances, weakproxy);
1342 }
1343
1344 static struct websocket_pvt* websocket_new(const char *chan_name,
1345 const char *connection_id, struct ast_format *fmt)
1346 {
1347 RAII_VAR(struct instance_proxy *, proxy, NULL, ao2_cleanup);
1348 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1349 char uuid[AST_UUID_STR_LEN];
1350 enum ast_websocket_type ws_type;
1351
1352 SCOPED_AO2WRLOCK(locker, instances);
1353
1354 if (ast_strings_equal(connection_id, INCOMING_CONNECTION_ID)) {
1355 connection_id = ast_uuid_generate_str(uuid, sizeof(uuid));
1356 ws_type = AST_WS_TYPE_SERVER;
1357 } else {
1358 ws_type = AST_WS_TYPE_CLIENT;
1359 }
1360
1361 proxy = ao2_weakproxy_alloc(sizeof(*proxy) + strlen(connection_id) + 1, NULL);
1362 if (!proxy) {
1363 return NULL;
1364 }
1365 strcpy(proxy->connection_id, connection_id); /* Safe */
1366
1367 instance = ao2_alloc(sizeof(*instance) + strlen(connection_id) + 1,
1368 websocket_destructor);
1369 if (!instance) {
1370 return NULL;
1371 }
1372 strcpy(instance->connection_id, connection_id); /* Safe */
1373
1374 instance->type = ws_type;
1375 if (ws_type == AST_WS_TYPE_CLIENT) {
1376 instance->client = ast_websocket_client_retrieve_by_id(instance->connection_id);
1377 if (!instance->client) {
1378 ast_log(LOG_ERROR, "%s: WebSocket client connection '%s' not found\n",
1379 chan_name, instance->connection_id);
1380 return NULL;
1381 }
1382 }
1383
1384 AST_LIST_HEAD_INIT(&instance->frame_queue);
1385
1386 /*
1387 * We need the codec to calculate the number of samples in a frame
1388 * so we'll get it once and store it in the instance.
1389 *
1390 * References for native_format and native_codec are now held by the
1391 * instance and will be released when the instance is destroyed.
1392 */
1393 instance->native_format = fmt;
1394 instance->native_codec = ast_format_get_codec(instance->native_format);
1395 /*
1396 * References for native_format and native_codec are now held by the
1397 * instance and will be released when the instance is destroyed.
1398 */
1399
1400 /*
1401 * It's not possible for us to re-time or re-frame media if the data
1402 * stream can't be broken up on arbitrary byte boundaries. This is usually
1403 * indicated by the codec's minimum_bytes being small (10 bytes or less).
1404 * We need to force passthrough mode in this case.
1405 */
1406 if (instance->native_codec->minimum_bytes <= 10) {
1407 instance->passthrough = 1;
1408 instance->optimal_frame_size = 0;
1409 } else {
1410 instance->optimal_frame_size =
1411 (instance->native_codec->default_ms * instance->native_codec->minimum_bytes)
1412 / instance->native_codec->minimum_ms;
1413 instance->leftover_data = ast_calloc(1, instance->optimal_frame_size);
1414 if (!instance->leftover_data) {
1415 return NULL;
1416 }
1417 }
1418
1419 ast_debug(3,
1420 "%s: WebSocket channel native format '%s' Sample rate: %d ptime: %dms minms: %u minbytes: %u passthrough: %d optimal_frame_size: %d\n",
1421 chan_name, ast_format_get_name(instance->native_format),
1422 ast_format_get_sample_rate(instance->native_format),
1423 ast_format_get_default_ms(instance->native_format),
1424 ast_format_get_minimum_ms(instance->native_format),
1425 ast_format_get_minimum_bytes(instance->native_format),
1426 instance->passthrough,
1427 instance->optimal_frame_size);
1428
1429 /* We have exclusive access to proxy and sorcery, no need for locking here. */
1430 if (ao2_weakproxy_set_object(proxy, instance, OBJ_NOLOCK)) {
1431 return NULL;
1432 }
1433
1434 if (ao2_weakproxy_subscribe(proxy, instance_proxy_cb, NULL, OBJ_NOLOCK)) {
1435 return NULL;
1436 }
1437
1438 if (!ao2_link_flags(instances, proxy, OBJ_NOLOCK)) {
1439 ast_log(LOG_ERROR, "%s: Unable to link WebSocket instance to instances\n",
1440 proxy->connection_id);
1441 return NULL;
1442 }
1443 ast_debug(3, "%s: WebSocket instance created and linked\n", proxy->connection_id);
1444
1445 return ao2_bump(instance);
1446 }
1447
1448 static int set_channel_timer(struct websocket_pvt *instance)
1449 {
1450 int rate = 0;
1451 instance->timer = ast_timer_open();
1452 if (!instance->timer) {
1453 return -1;
1454 }
1455 /* Rate is the number of ticks per second, not the interval. */
1456 rate = 1000 / ast_format_get_default_ms(instance->native_format);
1457 ast_debug(3, "%s: WebSocket timer rate %d\n",
1458 ast_channel_name(instance->channel), rate);
1459 ast_timer_set_rate(instance->timer, rate);
1460 /*
1461 * Calling ast_channel_set_fd will cause the channel thread to call
1462 * webchan_read at 'rate' times per second.
1463 */
1464 ast_channel_set_fd(instance->channel, WS_TIMER_FDNO, ast_timer_fd(instance->timer));
1465
1466 return 0;
1467 }
1468
1469 static int set_channel_variables(struct websocket_pvt *instance)
1470 {
1471 char *pkt_size = NULL;
1472 int res = ast_asprintf(&pkt_size, "%d", instance->optimal_frame_size);
1473 if (res <= 0) {
1474 return -1;
1475 }
1476
1477 pbx_builtin_setvar_helper(instance->channel, MEDIA_WEBSOCKET_OPTIMAL_FRAME_SIZE,
1478 pkt_size);
1479 ast_free(pkt_size);
1480 pbx_builtin_setvar_helper(instance->channel, MEDIA_WEBSOCKET_CONNECTION_ID,
1481 instance->connection_id);
1482
1483 return 0;
1484 }
1485
1486 static int validate_uri_parameters(const char *uri_params)
1487 {
1488 char *params = ast_strdupa(uri_params);
1489 char *nvp = NULL;
1490 char *nv = NULL;
1491
1492 /*
1493 * uri_params should be a comma-separated list of key=value pairs.
1494 * For example:
1495 * name1=value1,name2=value2
1496 * We're verifying that each name and value either doesn't need
1497 * to be encoded or that it already is.
1498 */
1499
1500 while((nvp = ast_strsep(&params, ',', 0))) {
1501 /* nvp will be name1=value1 */
1502 while((nv = ast_strsep(&nvp, '=', 0))) {
1503 /* nv will be either name1 or value1 */
1504 if (!ast_uri_verify_encoded(nv)) {
1505 return 0;
1506 }
1507 }
1508 }
1509
1510 return 1;
1511 }
1512
1513 enum {
1514 OPT_WS_CODEC = (1 << 0),
1515 OPT_WS_NO_AUTO_ANSWER = (1 << 1),
1516 OPT_WS_URI_PARAM = (1 << 2),
1517 OPT_WS_PASSTHROUGH = (1 << 3),
1518 OPT_WS_MSG_FORMAT = (1 << 4),
1519 OPT_WS_MEDIA_DIRECTION = (1 << 5),
1520 };
1521
1522 enum {
1523 OPT_ARG_WS_CODEC,
1524 OPT_ARG_WS_NO_AUTO_ANSWER,
1525 OPT_ARG_WS_URI_PARAM,
1526 OPT_ARG_WS_PASSTHROUGH,
1527 OPT_ARG_WS_MSG_FORMAT,
1528 OPT_ARG_WS_MEDIA_DIRECTION,
1529 OPT_ARG_ARRAY_SIZE
1530 };
1531
1532 AST_APP_OPTIONS(websocket_options, BEGIN_OPTIONS
1533 AST_APP_OPTION_ARG('c', OPT_WS_CODEC, OPT_ARG_WS_CODEC),
1534 AST_APP_OPTION('n', OPT_WS_NO_AUTO_ANSWER),
1535 AST_APP_OPTION_ARG('v', OPT_WS_URI_PARAM, OPT_ARG_WS_URI_PARAM),
1536 AST_APP_OPTION('p', OPT_WS_PASSTHROUGH),
1537 AST_APP_OPTION_ARG('f', OPT_WS_MSG_FORMAT, OPT_ARG_WS_MSG_FORMAT),
1538 AST_APP_OPTION_ARG('d', OPT_WS_MEDIA_DIRECTION, OPT_ARG_WS_MEDIA_DIRECTION),
1539 END_OPTIONS );
1540
1541 static struct ast_channel *webchan_request(const char *type,
1542 struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids,
1543 const struct ast_channel *requestor, const char *data, int *cause)
1544 {
1545 char *parse;
1546 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1547 struct ast_channel *chan = NULL;
1548 struct ast_format *fmt = NULL;
1549 struct ast_format_cap *caps = NULL;
1550 AST_DECLARE_APP_ARGS(args,
1551 AST_APP_ARG(connection_id);
1552 AST_APP_ARG(options);
1553 );
1554 struct ast_flags opts = { 0, };
1555 char *opt_args[OPT_ARG_ARRAY_SIZE];
1556 const char *requestor_name = requestor ? ast_channel_name(requestor) :
1557 (assignedids && !ast_strlen_zero(assignedids->uniqueid) ? assignedids->uniqueid : "<unknown>");
1558 RAII_VAR(struct webchan_conf_global *, global_cfg, NULL, ao2_cleanup);
1559
1560 global_cfg = ast_sorcery_retrieve_by_id(sorcery, "global", "global");
1561
1562 ast_debug(3, "%s: WebSocket channel requested\n",
1563 requestor_name);
1564
1565 if (ast_strlen_zero(data)) {
1566 ast_log(LOG_ERROR, "%s: A connection id is required for the 'WebSocket' channel\n",
1567 requestor_name);
1568 goto failure;
1569 }
1570 parse = ast_strdupa(data);
1571 AST_NONSTANDARD_APP_ARGS(args, parse, '/');
1572
1573 if (ast_strlen_zero(args.connection_id)) {
1574 ast_log(LOG_ERROR, "%s: connection_id is required for the 'WebSocket' channel\n",
1575 requestor_name);
1576 goto failure;
1577 }
1578
1579 if (!ast_strlen_zero(args.options)
1580 && ast_app_parse_options(websocket_options, &opts, opt_args,
1581 ast_strdupa(args.options))) {
1582 ast_log(LOG_ERROR, "%s: 'WebSocket' channel options '%s' parse error\n",
1583 requestor_name, args.options);
1584 goto failure;
1585 }
1586
1587 if (ast_test_flag(&opts, OPT_WS_CODEC)
1588 && !ast_strlen_zero(opt_args[OPT_ARG_WS_CODEC])) {
1589 fmt = ast_format_cache_get(opt_args[OPT_ARG_WS_CODEC]);
1590 } else {
1591 /*
1592 * If codec wasn't specified in the dial string,
1593 * use the first format in the capabilities.
1594 */
1595 fmt = ast_format_cap_get_format(cap, 0);
1596 }
1597
1598 if (!fmt) {
1599 ast_log(LOG_WARNING, "%s: No codec found for sending media to connection '%s'\n",
1600 requestor_name, args.connection_id);
1601 goto failure;
1602 }
1603
1604 ast_debug(3, "%s: Using format %s from %s\n",
1605 requestor_name, ast_format_get_name(fmt),
1606 ast_test_flag(&opts, OPT_WS_CODEC) ? "dialstring" : "requester");
1607
1608 instance = websocket_new(requestor_name, args.connection_id, fmt);
1609 if (!instance) {
1610 ast_log(LOG_ERROR, "%s: Failed to allocate WebSocket channel pvt\n",
1611 requestor_name);
1612 goto failure;
1613 }
1614
1615 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_BOTH;
1616 if (ast_test_flag(&opts, OPT_WS_MEDIA_DIRECTION)) {
1617 if (!strcmp("both", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1618 /* The default. Don't need to do anything here other than
1619 * ensure it is an allowed value. */
1620 } else if (!strcmp("out", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1621 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_OUT;
1622 } else if (!strcmp("in", opt_args[OPT_ARG_WS_MEDIA_DIRECTION])) {
1623 instance->media_direction = WEBCHAN_MEDIA_DIRECTION_IN;
1624 } else {
1625 ast_log(LOG_ERROR, "Unrecognized option for media direction: '%s'.\n",
1626 opt_args[OPT_ARG_WS_MEDIA_DIRECTION]);
1627 goto failure;
1628 }
1629 }
1630
1631 instance->no_auto_answer = ast_test_flag(&opts, OPT_WS_NO_AUTO_ANSWER);
1632 if (!instance->passthrough) {
1633 instance->passthrough = ast_test_flag(&opts, OPT_WS_PASSTHROUGH);
1634 }
1635
1636 if (ast_test_flag(&opts, OPT_WS_URI_PARAM)
1637 && !ast_strlen_zero(opt_args[OPT_ARG_WS_URI_PARAM])) {
1638 char *comma;
1639
1640 if (ast_strings_equal(args.connection_id, INCOMING_CONNECTION_ID)) {
1641 ast_log(LOG_ERROR,
1642 "%s: URI parameters are not allowed for 'WebSocket/INCOMING' channels\n",
1643 requestor_name);
1644 goto failure;
1645 }
1646
1647 ast_debug(3, "%s: Using URI parameters '%s'\n",
1648 requestor_name, opt_args[OPT_ARG_WS_URI_PARAM]);
1649
1650 if (!validate_uri_parameters(opt_args[OPT_ARG_WS_URI_PARAM])) {
1651 ast_log(LOG_ERROR, "%s: Invalid URI parameters '%s' in WebSocket/%s dial string\n",
1652 requestor_name, opt_args[OPT_ARG_WS_URI_PARAM],
1653 args.connection_id);
1654 goto failure;
1655 }
1656
1657 instance->uri_params = ast_strdup(opt_args[OPT_ARG_WS_URI_PARAM]);
1658 comma = instance->uri_params;
1659 /*
1660 * The normal separator for query string components is an
1661 * ampersand ('&') but the Dial app interprets them as additional
1662 * channels to dial in parallel so we instruct users to separate
1663 * the parameters with commas (',') instead. We now have to
1664 * convert those commas back to ampersands.
1665 */
1666 while ((comma = strchr(comma,','))) {
1667 *comma = '&';
1668 }
1669 ast_debug(3, "%s: Using final URI '%s'\n", requestor_name, instance->uri_params);
1670 }
1671
1672 if (ast_test_flag(&opts, OPT_WS_MSG_FORMAT)) {
1673 instance->control_msg_format = control_msg_format_from_str(opt_args[OPT_ARG_WS_MSG_FORMAT]);
1674
1675 if (instance->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_INVALID) {
1676 ast_log(LOG_WARNING, "%s: 'f/control message format' dialstring parameter value missing or invalid. "
1677 "Defaulting to 'plain-text'\n",
1678 ast_channel_name(requestor));
1679 instance->control_msg_format = WEBCHAN_CONTROL_MSG_FORMAT_PLAIN;
1680 }
1681 } else if (global_cfg) {
1682 instance->control_msg_format = global_cfg->control_msg_format;
1683 }
1684
1685 chan = ast_channel_alloc(1, AST_STATE_DOWN, "", "", "", "", "", assignedids,
1686 requestor, 0, "WebSocket/%s/%p", args.connection_id, instance);
1687 if (!chan) {
1688 ast_log(LOG_ERROR, "%s: Unable to alloc channel\n", ast_channel_name(requestor));
1689 goto failure;
1690 }
1691
1692 /* Prevent device state caching as this channel involves ephemeral destinations or sources */
1693 ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_DEVSTATE_CACHE);
1694 ast_debug(3, "%s: WebSocket channel %s allocated for connection %s\n",
1695 ast_channel_name(chan), requestor_name,
1696 instance->connection_id);
1697
1698 instance->channel = ao2_bump(chan);
1699 ast_channel_tech_set(instance->channel, &websocket_tech);
1700
1701 /* If the application's media direction is 'both' or 'out', we need the channel timer. */
1702 if (instance->media_direction != WEBCHAN_MEDIA_DIRECTION_IN
1703 && set_channel_timer(instance) != 0) {
1704 goto failure;
1705 }
1706
1707 if (set_channel_variables(instance) != 0) {
1708 goto failure;
1709 }
1710
1711 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1712 if (!caps) {
1713 ast_log(LOG_ERROR, "%s: Unable to alloc caps\n", requestor_name);
1714 goto failure;
1715 }
1716
1717 ast_format_cap_append(caps, instance->native_format, 0);
1718 ast_channel_nativeformats_set(instance->channel, caps);
1719 ast_channel_set_writeformat(instance->channel, instance->native_format);
1720 ast_channel_set_rawwriteformat(instance->channel, instance->native_format);
1721 ast_channel_set_readformat(instance->channel, instance->native_format);
1722 ast_channel_set_rawreadformat(instance->channel, instance->native_format);
1723 ast_channel_tech_pvt_set(chan, ao2_bump(instance));
1724 ast_channel_unlock(chan);
1725 ao2_cleanup(caps);
1726
1727 ast_debug(3, "%s: WebSocket channel created to %s\n",
1728 ast_channel_name(chan), args.connection_id);
1729
1730 return chan;
1731
1732 failure:
1733 if (chan) {
1734 ast_channel_unlock(chan);
1735 }
1736 *cause = AST_CAUSE_FAILURE;
1737 return NULL;
1738 }
1739
1740 /*!
1741 * \internal
1742 *
1743 * Called by the core to hang up the channel.
1744 */
1745 static int webchan_hangup(struct ast_channel *ast)
1746 {
1747 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1748
1749 if (!instance) {
1750 return -1;
1751 }
1752 ast_debug(3, "%s: WebSocket call hangup. cid: %s\n",
1753 ast_channel_name(ast), instance->connection_id);
1754
1755 if (instance->websocket) {
1756 ast_websocket_close(instance->websocket, ast_channel_tech_hangupcause(ast) ?: 1000);
1757 ast_websocket_unref(instance->websocket);
1758 instance->websocket = NULL;
1759 }
1760 ast_channel_tech_pvt_set(ast, NULL);
1761
1762 /* Clean up the reference from adding the instance to the channel */
1763 ao2_cleanup(instance);
1764
1765 return 0;
1766 }
1767
1768 static int webchan_send_dtmf_text(struct ast_channel *ast, char digit, unsigned int duration)
1769 {
1770 struct websocket_pvt *instance = ast_channel_tech_pvt(ast);
1771
1772 if (!instance) {
1773 return -1;
1774 }
1775
1776 return send_event(instance, DTMF_END, digit);
1777 }
1778
1779 /*!
1780 * \internal
1781 *
1782 * Called by res_http_websocket after a client has connected and
1783 * successfully upgraded from HTTP to WebSocket.
1784 *
1785 * Depends on incoming_ws_http_callback parsing the connection_id from
1786 * the HTTP request and storing it in get_params.
1787 */
1788 static void incoming_ws_established_cb(struct ast_websocket *ast_ws_session,
1789 struct ast_variable *get_params, struct ast_variable *upgrade_headers)
1790 {
1791 RAII_VAR(struct ast_websocket *, s, ast_ws_session, ast_websocket_unref);
1792 struct ast_variable *v;
1793 const char *connection_id = NULL;
1794 struct websocket_pvt *instance = NULL;
1795
1796 ast_debug(3, "WebSocket established\n");
1797
1798 for (v = upgrade_headers; v; v = v->next) {
1799 ast_debug(4, "Header-> %s: %s\n", v->name, v->value);
1800 }
1801 for (v = get_params; v; v = v->next) {
1802 ast_debug(4, " Param-> %s: %s\n", v->name, v->value);
1803 }
1804
1805 connection_id = ast_variable_find_in_list(get_params, "CONNECTION_ID");
1806 if (!connection_id) {
1807 /*
1808 * This can't really happen because websocket_http_callback won't
1809 * let it get this far if it can't add the connection_id to the
1810 * get_params.
1811 * Just in case though...
1812 */
1813 ast_log(LOG_WARNING, "WebSocket connection id not found\n");
1814 websocket_request_hangup(instance, AST_CAUSE_FAILURE, AST_WEBSOCKET_STATUS_INTERNAL_ERROR);
1815 ast_websocket_close(ast_ws_session, AST_WEBSOCKET_STATUS_INTERNAL_ERROR);
1816 return;
1817 }
1818
1819 instance = ao2_weakproxy_find(instances, connection_id, OBJ_SEARCH_KEY | OBJ_NOLOCK, "");
1820 if (!instance) {
1821 /*
1822 * This also can't really happen because websocket_http_callback won't
1823 * let it get this far if it can't find the instance.
1824 * Just in case though...
1825 */
1826 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n", connection_id);
1827 websocket_request_hangup(instance, AST_CAUSE_FAILURE, AST_WEBSOCKET_STATUS_INTERNAL_ERROR);
1828 ast_websocket_close(ast_ws_session, AST_WEBSOCKET_STATUS_INTERNAL_ERROR);
1829 return;
1830 }
1831 instance->websocket = ao2_bump(ast_ws_session);
1832
1833 websocket_handoff_to_channel(instance);
1834 ao2_cleanup(instance);
1835 /*
1836 * The instance is the channel's responsibility now.
1837 * We just return here.
1838 */
1839 }
1840
1841 /*!
1842 * \internal
1843 *
1844 * Called by the core http server after a client connects but before
1845 * the upgrade from HTTP to Websocket. We need to save the URI in
1846 * the CONNECTION_ID in a get_param because it contains the connection UUID
1847 * we gave to the client when they used externalMedia to create the channel.
1848 * incoming_ws_established_cb() will use this to retrieve the chan_websocket
1849 * instance.
1850 */
1851 static int incoming_ws_http_callback(struct ast_tcptls_session_instance *ser,
1852 const struct ast_http_uri *urih, const char *uri,
1853 enum ast_http_method method, struct ast_variable *get_params,
1854 struct ast_variable *headers)
1855 {
1856 struct ast_http_uri fake_urih = {
1857 .data = ast_ws_server,
1858 };
1859 int res = 0;
1860 /*
1861 * Normally the http server will destroy the get_params
1862 * when the session ends but if there weren't any initially
1863 * and we create some and add them to the list, the http server
1864 * won't know about it so we have to destroy it ourselves.
1865 */
1866 int destroy_get_params = (get_params == NULL);
1867 struct ast_variable *v = NULL;
1868 RAII_VAR(struct websocket_pvt *, instance, NULL, ao2_cleanup);
1869
1870 ast_debug(2, "URI: %s Starting\n", uri);
1871
1872 /*
1873 * The client will have issued the GET request with a URI of
1874 * /media/<connection_id>
1875 *
1876 * Since this callback is registered for the /media URI prefix the
1877 * http server will strip that off the front of the URI passing in
1878 * only the path components after that in the 'uri' parameter.
1879 * This should leave only the connection id without a leading '/'.
1880 */
1881 instance = ao2_weakproxy_find(instances, uri, OBJ_SEARCH_KEY | OBJ_NOLOCK, "");
1882 if (!instance) {
1883 ast_log(LOG_WARNING, "%s: WebSocket instance not found\n", uri);
1884 ast_http_error(ser, 404, "Not found", "WebSocket instance not found");
1885 return -1;
1886 }
1887
1888 /*
1889 * We don't allow additional connections using the same connection id.
1890 */
1891 if (instance->websocket) {
1892 ast_log(LOG_WARNING, "%s: Websocket already connected for channel '%s'\n",
1893 uri, instance->channel ? ast_channel_name(instance->channel) : "unknown");
1894 ast_http_error(ser, 409, "Conflict", "Another websocket connection exists for this connection id");
1895 return -1;
1896 }
1897
1898 v = ast_variable_new("CONNECTION_ID", uri, "");
1899 if (!v) {
1900 ast_http_error(ser, 500, "Server error", "");
1901 return -1;
1902 }
1903 ast_variable_list_append(&get_params, v);
1904
1905 for (v = get_params; v; v = v->next) {
1906 ast_debug(4, " Param-> %s: %s\n", v->name, v->value);
1907 }
1908
1909 /*
1910 * This will ultimately call internal_ws_established_cb() so
1911 * this function will block until the websocket is closed and
1912 * internal_ws_established_cb() returns;
1913 */
1914 res = ast_websocket_uri_cb(ser, &fake_urih, uri, method,
1915 get_params, headers);
1916 if (destroy_get_params) {
1917 ast_variables_destroy(get_params);
1918 }
1919
1920 ast_debug(2, "URI: %s DONE\n", uri);
1921
1922 return res;
1923 }
1924
1925 static struct ast_http_uri http_uri = {
1926 .callback = incoming_ws_http_callback,
1927 .description = "Media over Websocket",
1928 .uri = "media",
1929 .has_subtree = 1,
1930 .data = NULL,
1931 .key = __FILE__,
1932 .no_decode_uri = 1,
1933 };
1934
1935 AO2_STRING_FIELD_HASH_FN(instance_proxy, connection_id)
1936 AO2_STRING_FIELD_CMP_FN(instance_proxy, connection_id)
1937 AO2_STRING_FIELD_SORT_FN(instance_proxy, connection_id)
1938
1939 static int global_control_message_format_from_str(const struct aco_option *opt,
1940 struct ast_variable *var, void *obj)
1941 {
1942 struct webchan_conf_global *cfg = obj;
1943
1944 cfg->control_msg_format = control_msg_format_from_str(var->value);
1945
1946 if (cfg->control_msg_format == WEBCHAN_CONTROL_MSG_FORMAT_INVALID) {
1947 ast_log(LOG_ERROR, "chan_websocket.conf: Invalid value '%s' for "
1948 "control_mesage_format. Must be 'plain-text' or 'json'\n",
1949 var->value);
1950 return -1;
1951 }
1952
1953 return 0;
1954 }
1955
1956 static int global_control_message_format_to_str(const void *obj, const intptr_t *args, char **buf)
1957 {
1958 const struct webchan_conf_global *cfg = obj;
1959
1960 *buf = ast_strdup(control_msg_format_to_str(cfg->control_msg_format));
1961
1962 return 0;
1963 }
1964
1965 static void *global_alloc(const char *name)
1966 {
1967 struct webchan_conf_global *cfg = ast_sorcery_generic_alloc(
1968 sizeof(*cfg), NULL);
1969
1970 if (!cfg) {
1971 return NULL;
1972 }
1973
1974 return cfg;
1975 }
1976
1977 static int global_apply(const struct ast_sorcery *sorcery, void *obj)
1978 {
1979 struct webchan_conf_global *cfg = obj;
1980
1981 ast_debug(1, "control_msg_format: %s\n",
1982 control_msg_format_to_str(cfg->control_msg_format));
1983
1984 return 0;
1985 }
1986
1987 static int load_config(void)
1988 {
1989 ast_debug(2, "Initializing Websocket Client Configuration\n");
1990 sorcery = ast_sorcery_open();
1991 if (!sorcery) {
1992 ast_log(LOG_ERROR, "Failed to open sorcery\n");
1993 return -1;
1994 }
1995
1996 ast_sorcery_apply_default(sorcery, "global", "config",
1997 "chan_websocket.conf,criteria=type=global,single_object=yes,explicit_name=global");
1998
1999 if (ast_sorcery_object_register(sorcery, "global", global_alloc, NULL, global_apply)) {
2000 ast_log(LOG_ERROR, "Failed to register chan_websocket global object with sorcery\n");
2001 ast_sorcery_unref(sorcery);
2002 sorcery = NULL;
2003 return -1;
2004 }
2005
2006 ast_sorcery_object_field_register_nodoc(sorcery, "global", "type", "", OPT_NOOP_T, 0, 0);
2007 ast_sorcery_register_cust(global, control_message_format, "plain-text");
2008
2009 ast_sorcery_load(sorcery);
2010
2011 return 0;
2012 }
2013
2014 /*! \brief Function called when our module is unloaded */
2015 static int unload_module(void)
2016 {
2017 ast_http_uri_unlink(&http_uri);
2018 ao2_cleanup(ast_ws_server);
2019 ast_ws_server = NULL;
2020
2021 ast_channel_unregister(&websocket_tech);
2022 ao2_cleanup(websocket_tech.capabilities);
2023 websocket_tech.capabilities = NULL;
2024
2025 ao2_cleanup(instances);
2026 instances = NULL;
2027
2028 ast_sorcery_unref(sorcery);
2029 sorcery = NULL;
2030
2031 return 0;
2032 }
2033
2034 static int reload_module(void)
2035 {
2036 ast_debug(2, "Reloading chan_websocket configuration\n");
2037 ast_sorcery_reload(sorcery);
2038
2039 return 0;
2040 }
2041
2042 /*! \brief Function called when our module is loaded */
2043 static int load_module(void)
2044 {
2045 int res = 0;
2046 struct ast_websocket_protocol *protocol;
2047
2048 res = load_config();
2049 if (res != 0) {
2050 return AST_MODULE_LOAD_DECLINE;
2051 }
2052
2053 if (!(websocket_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2054 return AST_MODULE_LOAD_DECLINE;
2055 }
2056
2057 ast_format_cap_append_by_type(websocket_tech.capabilities, AST_MEDIA_TYPE_UNKNOWN);
2058 if (ast_channel_register(&websocket_tech)) {
2059 ast_log(LOG_ERROR, "Unable to register channel class 'WebSocket'\n");
2060 unload_module();
2061 return AST_MODULE_LOAD_DECLINE;
2062 }
2063
2064 instances = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
2065 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE, 17, instance_proxy_hash_fn,
2066 instance_proxy_sort_fn, instance_proxy_cmp_fn);
2067 if (!instances) {
2068 ast_log(LOG_WARNING,
2069 "Failed to allocate the chan_websocket instance registry\n");
2070 unload_module();
2071 return AST_MODULE_LOAD_DECLINE;
2072 }
2073
2074 ast_ws_server = ast_websocket_server_create();
2075 if (!ast_ws_server) {
2076 unload_module();
2077 return AST_MODULE_LOAD_DECLINE;
2078 }
2079
2080 protocol = ast_websocket_sub_protocol_alloc("media");
2081 if (!protocol) {
2082 unload_module();
2083 return AST_MODULE_LOAD_DECLINE;
2084 }
2085 protocol->session_established = incoming_ws_established_cb;
2086 res = ast_websocket_server_add_protocol2(ast_ws_server, protocol);
2087
2088 ast_http_uri_link(&http_uri);
2089
2090 return res == 0 ? AST_MODULE_LOAD_SUCCESS : AST_MODULE_LOAD_DECLINE;
2091 }
2092
2093 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Websocket Media Channel",
2094 .support_level = AST_MODULE_SUPPORT_CORE,
2095 .load = load_module,
2096 .unload = unload_module,
2097 .reload = reload_module,
2098 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2099 .requires = "res_http_websocket,res_websocket_client",
2100 );