Asterisk - The Open Source Telephony Project GIT-master-85241bd
Data Structures | Macros | Typedefs | Enumerations | Functions
http_websocket.h File Reference

Support for WebSocket connections within the Asterisk HTTP server and client WebSocket connections to a server. More...

#include "asterisk/http.h"
#include "asterisk/optional_api.h"
#include <errno.h>
Include dependency graph for http_websocket.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  ast_websocket_client_options
 Options used for a websocket client. More...
 
struct  ast_websocket_protocol
 A websocket protocol implementation. More...
 

Macros

#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT   100
 Default websocket write timeout, in ms. More...
 
#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT_STR   "100"
 Default websocket write timeout, in ms (as a string) More...
 
#define AST_WEBSOCKET_PROTOCOL_VERSION   1
 Protocol version. This prevents dynamically loadable modules from registering if this struct is changed. More...
 

Typedefs

typedef void(* ast_websocket_callback) (struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
 Callback for when a new connection for a sub-protocol is established. More...
 
typedef int(* ast_websocket_pre_callback) (struct ast_tcptls_session_instance *ser, struct ast_variable *parameters, struct ast_variable *headers, const char *session_id)
 Callback from the HTTP request attempting to establish a websocket connection. More...
 

Enumerations

enum  ast_websocket_opcode {
  AST_WEBSOCKET_OPCODE_TEXT = 0x1 , AST_WEBSOCKET_OPCODE_BINARY = 0x2 , AST_WEBSOCKET_OPCODE_PING = 0x9 , AST_WEBSOCKET_OPCODE_PONG = 0xA ,
  AST_WEBSOCKET_OPCODE_CLOSE = 0x8 , AST_WEBSOCKET_OPCODE_CONTINUATION = 0x0
}
 WebSocket operation codes. More...
 
enum  ast_websocket_result {
  WS_OK , WS_ALLOCATE_ERROR , WS_KEY_ERROR , WS_URI_PARSE_ERROR ,
  WS_URI_RESOLVE_ERROR , WS_BAD_STATUS , WS_INVALID_RESPONSE , WS_BAD_REQUEST ,
  WS_URL_NOT_FOUND , WS_HEADER_MISMATCH , WS_HEADER_MISSING , WS_NOT_SUPPORTED ,
  WS_WRITE_ERROR , WS_CLIENT_START_ERROR
}
 Result code for a websocket client. More...
 

Functions

int ast_websocket_add_protocol (const char *name, ast_websocket_callback callback)
 Add a sub-protocol handler to the default /ws server. More...
 
int ast_websocket_add_protocol2 (struct ast_websocket_protocol *protocol)
 Add a sub-protocol handler to the default /ws server. More...
 
const char * ast_websocket_client_accept_protocol (struct ast_websocket *ws)
 Retrieve the server accepted sub-protocol on the client. More...
 
struct ast_websocketast_websocket_client_create (const char *uri, const char *protocols, struct ast_tls_config *tls_cfg, enum ast_websocket_result *result)
 Create, and connect, a websocket client. More...
 
struct ast_websocketast_websocket_client_create_with_options (struct ast_websocket_client_options *options, enum ast_websocket_result *result)
 Create, and connect, a websocket client using given options. More...
 
int 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. More...
 
int ast_websocket_fd (struct ast_websocket *session)
 Get the file descriptor for a WebSocket session. More...
 
int ast_websocket_is_secure (struct ast_websocket *session)
 Get whether the WebSocket session is using a secure transport or not. More...
 
struct ast_sockaddrast_websocket_local_address (struct ast_websocket *session)
 Get the local address for a WebSocket connection session. More...
 
int 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. More...
 
int ast_websocket_read_string (struct ast_websocket *ws, char **buf)
 Read a WebSocket frame containing string data. More...
 
void ast_websocket_reconstruct_disable (struct ast_websocket *session)
 Disable multi-frame reconstruction. More...
 
void ast_websocket_reconstruct_enable (struct ast_websocket *session, size_t bytes)
 Enable multi-frame reconstruction up to a certain number of bytes. More...
 
void ast_websocket_ref (struct ast_websocket *session)
 Increase the reference count for a WebSocket session. More...
 
struct ast_sockaddrast_websocket_remote_address (struct ast_websocket *session)
 Get the remote address for a WebSocket connected session. More...
 
int ast_websocket_remove_protocol (const char *name, ast_websocket_callback callback)
 Remove a sub-protocol handler from the default /ws server. More...
 
int ast_websocket_server_add_protocol (struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
 Add a sub-protocol handler to the given server. More...
 
int ast_websocket_server_add_protocol2 (struct ast_websocket_server *server, struct ast_websocket_protocol *protocol)
 Add a sub-protocol handler to the given server. More...
 
struct ast_websocket_serverast_websocket_server_create (void)
 Creates a ast_websocket_server. More...
 
int ast_websocket_server_remove_protocol (struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
 Remove a sub-protocol handler from the given server. More...
 
const char * ast_websocket_session_id (struct ast_websocket *session)
 Get the session ID for a WebSocket session. More...
 
int ast_websocket_set_nonblock (struct ast_websocket *session)
 Set the socket of a WebSocket session to be non-blocking. More...
 
int ast_websocket_set_timeout (struct ast_websocket *session, int timeout)
 Set the timeout on a non-blocking WebSocket session. More...
 
struct ast_websocket_protocolast_websocket_sub_protocol_alloc (const char *name)
 Allocate a websocket sub-protocol instance. More...
 
void ast_websocket_unref (struct ast_websocket *session)
 Decrease the reference count for a WebSocket session. More...
 
int ast_websocket_uri_cb (struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers)
 Callback suitable for use with a ast_http_uri. More...
 
int ast_websocket_wait_for_input (struct ast_websocket *session, int timeout)
 Wait for the WebSocket session to be ready to be read. More...
 
int ast_websocket_write (struct ast_websocket *session, enum ast_websocket_opcode opcode, char *payload, uint64_t payload_size)
 Construct and transmit a WebSocket frame. More...
 
int ast_websocket_write_string (struct ast_websocket *ws, const char *buf)
 Construct and transmit a WebSocket frame containing string data. More...
 

Detailed Description

Support for WebSocket connections within the Asterisk HTTP server and client WebSocket connections to a server.

Supported WebSocket versions in server implementation: Version 7 defined in specification http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07 Version 8 defined in specification http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 Version 13 defined in specification http://tools.ietf.org/html/rfc6455 Supported WebSocket versions in client implementation: Version 13 defined in specification http://tools.ietf.org/html/rfc6455

Author
Joshua Colp jcolp.nosp@m.@dig.nosp@m.ium.c.nosp@m.om

Definition in file http_websocket.h.

Macro Definition Documentation

◆ AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT

#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT   100

Default websocket write timeout, in ms.

Definition at line 28 of file http_websocket.h.

◆ AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT_STR

#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT_STR   "100"

Default websocket write timeout, in ms (as a string)

Definition at line 31 of file http_websocket.h.

◆ AST_WEBSOCKET_PROTOCOL_VERSION

#define AST_WEBSOCKET_PROTOCOL_VERSION   1

Protocol version. This prevents dynamically loadable modules from registering if this struct is changed.

Definition at line 120 of file http_websocket.h.

Typedef Documentation

◆ ast_websocket_callback

typedef void(* ast_websocket_callback) (struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)

Callback for when a new connection for a sub-protocol is established.

Parameters
sessionA WebSocket session structure
parametersParameters extracted from the request URI
headersHeaders included in the request
Note
Once called the ownership of the session is transferred to the sub-protocol handler. It is responsible for closing and cleaning up.

Definition at line 101 of file http_websocket.h.

◆ ast_websocket_pre_callback

typedef int(* ast_websocket_pre_callback) (struct ast_tcptls_session_instance *ser, struct ast_variable *parameters, struct ast_variable *headers, const char *session_id)

Callback from the HTTP request attempting to establish a websocket connection.

This callback occurs when an HTTP request is made to establish a websocket connection. Implementers of ast_websocket_protocol can use this to deny a request, or to set up application specific data before invocation of ast_websocket_callback.

Parameters
serThe TCP/TLS session
parametersParameters extracted from the request URI
headersHeaders included in the request
session_idThe id of the current session.
Return values
0The session should be accepted
-1The session should be rejected. Note that the caller must send an error response using ast_http_error.
Since
13.5.0

Definition at line 88 of file http_websocket.h.

Enumeration Type Documentation

◆ ast_websocket_opcode

WebSocket operation codes.

Enumerator
AST_WEBSOCKET_OPCODE_TEXT 

Text frame

AST_WEBSOCKET_OPCODE_BINARY 

Binary frame

AST_WEBSOCKET_OPCODE_PING 

Request that the other side respond with a pong

AST_WEBSOCKET_OPCODE_PONG 

Response to a ping

AST_WEBSOCKET_OPCODE_CLOSE 

Connection is being closed

AST_WEBSOCKET_OPCODE_CONTINUATION 

Continuation of a previous frame

Definition at line 51 of file http_websocket.h.

51 {
52 AST_WEBSOCKET_OPCODE_TEXT = 0x1, /*!< Text frame */
53 AST_WEBSOCKET_OPCODE_BINARY = 0x2, /*!< Binary frame */
54 AST_WEBSOCKET_OPCODE_PING = 0x9, /*!< Request that the other side respond with a pong */
55 AST_WEBSOCKET_OPCODE_PONG = 0xA, /*!< Response to a ping */
56 AST_WEBSOCKET_OPCODE_CLOSE = 0x8, /*!< Connection is being closed */
57 AST_WEBSOCKET_OPCODE_CONTINUATION = 0x0, /*!< Continuation of a previous frame */
58};
@ AST_WEBSOCKET_OPCODE_PING
@ AST_WEBSOCKET_OPCODE_PONG
@ AST_WEBSOCKET_OPCODE_CONTINUATION
@ AST_WEBSOCKET_OPCODE_BINARY
@ AST_WEBSOCKET_OPCODE_CLOSE
@ AST_WEBSOCKET_OPCODE_TEXT

◆ ast_websocket_result

Result code for a websocket client.

Enumerator
WS_OK 
WS_ALLOCATE_ERROR 
WS_KEY_ERROR 
WS_URI_PARSE_ERROR 
WS_URI_RESOLVE_ERROR 
WS_BAD_STATUS 
WS_INVALID_RESPONSE 
WS_BAD_REQUEST 
WS_URL_NOT_FOUND 
WS_HEADER_MISMATCH 
WS_HEADER_MISSING 
WS_NOT_SUPPORTED 
WS_WRITE_ERROR 
WS_CLIENT_START_ERROR 

Definition at line 399 of file http_websocket.h.

399 {
400 WS_OK,
414};
@ WS_BAD_REQUEST
@ WS_URL_NOT_FOUND
@ WS_CLIENT_START_ERROR
@ WS_KEY_ERROR
@ WS_NOT_SUPPORTED
@ WS_ALLOCATE_ERROR
@ WS_HEADER_MISMATCH
@ WS_WRITE_ERROR
@ WS_URI_RESOLVE_ERROR
@ WS_OK
@ WS_INVALID_RESPONSE
@ WS_BAD_STATUS
@ WS_URI_PARSE_ERROR
@ WS_HEADER_MISSING

Function Documentation

◆ ast_websocket_add_protocol()

int ast_websocket_add_protocol ( const char *  name,
ast_websocket_callback  callback 
)

Add a sub-protocol handler to the default /ws server.

Parameters
nameName of the sub-protocol to register
callbackCallback called when a new connection requesting the sub-protocol is established
Return values
0success
-1if sub-protocol handler could not be registered

Definition at line 1052 of file res_http_websocket.c.

1053{
1054 return websocket_add_protocol_internal(name, callback);
1055}
static const char name[]
Definition: format_mp3.c:68
static int websocket_add_protocol_internal(const char *name, ast_websocket_callback callback)

References name, and websocket_add_protocol_internal().

Referenced by AST_TEST_DEFINE(), and load_module().

◆ ast_websocket_add_protocol2()

int ast_websocket_add_protocol2 ( struct ast_websocket_protocol protocol)

Add a sub-protocol handler to the default /ws server.

Parameters
protocolThe sub-protocol to register. Note that this must be allocated using /ref ast_websocket_sub_protocol_alloc.
Note
This method is reference stealing. It will steal the reference to protocol on success.
Return values
0success
-1if sub-protocol handler could not be registered
Since
13.5.0

Definition at line 1057 of file res_http_websocket.c.

1058{
1059 struct ast_websocket_server *ws_server = websocketuri.data;
1060
1061 if (!ws_server) {
1062 return -1;
1063 }
1064
1065 if (ast_websocket_server_add_protocol2(ws_server, protocol)) {
1066 return -1;
1067 }
1068
1069 return 0;
1070}
static struct ast_http_uri websocketuri
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.
void * data
Definition: http.h:116
Structure for a WebSocket server.

References ast_websocket_server_add_protocol2(), ast_http_uri::data, and websocketuri.

◆ ast_websocket_client_accept_protocol()

const char * ast_websocket_client_accept_protocol ( struct ast_websocket ws)

Retrieve the server accepted sub-protocol on the client.

Parameters
wsthe websocket client
Returns
the accepted client sub-protocol.
Since
13

Definition at line 1275 of file res_http_websocket.c.

1277{
1278 return ws->client->accept_protocol;
1279}
struct websocket_client * client

Referenced by AST_TEST_DEFINE().

◆ ast_websocket_client_create()

struct ast_websocket * ast_websocket_client_create ( const char *  uri,
const char *  protocols,
struct ast_tls_config tls_cfg,
enum ast_websocket_result result 
)

Create, and connect, a websocket client.

If the client websocket successfully connects, then the accepted protocol can be checked via a call to ast_websocket_client_accept_protocol.

Note
While connecting this will block until a response is received from the remote host.
Expected uri form:
ws[s]://<address>[:port][/<path>] 
The address (can be a host name) and port are parsed out and used to connect to the remote server. If multiple IPs are returned during address resolution then the first one is chosen.
Parameters
uriuri to connect to
protocolsa comma separated string of supported protocols
tls_cfgsecure websocket credentials
resultresult code set on client failure
Returns
a client websocket.
Return values
NULLif object could not be created or connected
Since
13

Definition at line 1440 of file res_http_websocket.c.

1443{
1445 .uri = uri,
1446 .protocols = protocols,
1447 .timeout = -1,
1448 .tls_cfg = tls_cfg,
1449 };
1450
1452}
static PGresult * result
Definition: cel_pgsql.c:84
struct ast_websocket *AST_OPTIONAL_API_NAME() ast_websocket_client_create_with_options(struct ast_websocket_client_options *options, enum ast_websocket_result *result)
Create, and connect, a websocket client using given options.
Options used for a websocket client.
struct ast_tls_config * tls_cfg
static struct test_options options

References ast_websocket_client_create_with_options(), options, ast_websocket_client_options::protocols, result, ast_websocket_client_options::tls_cfg, and ast_websocket_client_options::uri.

Referenced by AST_TEST_DEFINE().

◆ ast_websocket_client_create_with_options()

struct ast_websocket * ast_websocket_client_create_with_options ( struct ast_websocket_client_options options,
enum ast_websocket_result result 
)

Create, and connect, a websocket client using given options.

If the client websocket successfully connects, then the accepted protocol can be checked via a call to ast_websocket_client_accept_protocol.

Note
While connecting this will block until a response is received from the remote host, or the connection timeout is reached
Parameters
optionsWebsocket client options
resultresult code set on client failure
Returns
a client websocket.
Return values
NULLif object could not be created or connected

Definition at line 1454 of file res_http_websocket.c.

1456{
1458
1459 if (!ws) {
1460 return NULL;
1461 }
1462
1463 if ((*result = websocket_client_connect(ws, options->timeout)) != WS_OK) {
1464 ao2_ref(ws, -1);
1465 return NULL;
1466 }
1467
1468 return ws;
1469}
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition: astobj2.h:459
static enum ast_websocket_result websocket_client_connect(struct ast_websocket *ws, int timeout)
static struct ast_websocket * websocket_client_create(struct ast_websocket_client_options *options, enum ast_websocket_result *result)
#define NULL
Definition: resample.c:96
Structure definition for session.

References ao2_ref, NULL, options, result, websocket_client_connect(), websocket_client_create(), and WS_OK.

Referenced by ast_websocket_client_create(), and websocket_connect().

◆ ast_websocket_close()

int 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.

Parameters
sessionPointer to the WebSocket session
reasonReason code for closing the session as defined in the RFC
Return values
0if successfully written
-1if error occurred

Close a WebSocket session by sending a message with the CLOSE opcode and an optional code.

Definition at line 308 of file res_http_websocket.c.

309{
311 /* The header is either 2 or 6 bytes and the
312 * reason code takes up another 2 bytes */
313 char frame[8] = { 0, };
314 int header_size, fsize, res;
315
316 if (session->close_sent) {
317 return 0;
318 }
319
320 /* clients need space for an additional 4 byte masking key */
321 header_size = session->client ? 6 : 2;
322 fsize = header_size + 2;
323
324 frame[0] = opcode | 0x80;
325 frame[1] = 2; /* The reason code is always 2 bytes */
326
327 /* If no reason has been specified assume 1000 which is normal closure */
328 put_unaligned_uint16(&frame[header_size], htons(reason ? reason : 1000));
329
330 websocket_mask_payload(session, frame, &frame[header_size], 2);
331
332 session->closing = 1;
333 session->close_sent = 1;
334
337 res = ast_iostream_write(session->stream, frame, fsize);
339
340 /* If an error occurred when trying to close this connection explicitly terminate it now.
341 * Doing so will cause the thread polling on it to wake up and terminate.
342 */
343 if (res != fsize) {
345 session->stream = NULL;
346 ast_verb(2, "WebSocket connection %s '%s' forcefully closed due to fatal write error\n",
347 session->client ? "to" : "from", ast_sockaddr_stringify(&session->remote_address));
348 }
349
351 return res == sizeof(frame);
352}
static struct ast_mansession session
#define ao2_unlock(a)
Definition: astobj2.h:729
#define ao2_lock(a)
Definition: astobj2.h:717
ast_websocket_opcode
WebSocket operation codes.
#define ast_verb(level,...)
void ast_iostream_set_timeout_inactivity(struct ast_iostream *stream, int timeout)
Set the iostream inactivity timeout timer.
Definition: iostream.c:122
ssize_t ast_iostream_write(struct ast_iostream *stream, const void *buffer, size_t count)
Write data to an iostream.
Definition: iostream.c:385
int ast_iostream_close(struct ast_iostream *stream)
Close an iostream.
Definition: iostream.c:539
void ast_iostream_set_timeout_disable(struct ast_iostream *stream)
Disable the iostream timeout timer.
Definition: iostream.c:114
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition: netsock2.h:256
static void websocket_mask_payload(struct ast_websocket *session, char *frame, char *payload, uint64_t payload_size)
Perform payload masking for client sessions.
static void put_unaligned_uint16(void *p, unsigned short datum)
Definition: unaligned.h:65

References ao2_lock, ao2_unlock, ast_iostream_close(), ast_iostream_set_timeout_disable(), ast_iostream_set_timeout_inactivity(), ast_iostream_write(), ast_sockaddr_stringify(), ast_verb, AST_WEBSOCKET_OPCODE_CLOSE, NULL, ast_websocket::opcode, put_unaligned_uint16(), session, and websocket_mask_payload().

Referenced by ast_websocket_read(), ast_websocket_write(), session_destroy_fn(), and ws_shutdown().

◆ ast_websocket_fd()

int ast_websocket_fd ( struct ast_websocket session)

Get the file descriptor for a WebSocket session.

Returns
file descriptor
Note
You must not directly read from or write to this file descriptor. It should only be used for polling.

Definition at line 461 of file res_http_websocket.c.

462{
463 return session->closing ? -1 : ast_iostream_get_fd(session->stream);
464}
int ast_iostream_get_fd(struct ast_iostream *stream)
Get an iostream's file descriptor.
Definition: iostream.c:85

References ast_iostream_get_fd(), and session.

Referenced by ast_ari_websocket_session_read(), speech_test_server_cb(), websocket_echo_callback(), websocket_read(), and ws_shutdown().

◆ ast_websocket_is_secure()

int ast_websocket_is_secure ( struct ast_websocket session)

Get whether the WebSocket session is using a secure transport or not.

Return values
0if unsecure
1if secure

Definition at line 481 of file res_http_websocket.c.

482{
483 return session->secure;
484}

References session.

Referenced by transport_create().

◆ ast_websocket_local_address()

struct ast_sockaddr * ast_websocket_local_address ( struct ast_websocket session)

Get the local address for a WebSocket connection session.

Returns
Local address
Since
13.19.0

Definition at line 476 of file res_http_websocket.c.

477{
478 return &session->local_address;
479}

References session.

Referenced by transport_create().

◆ ast_websocket_read()

int 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.

Parameters
sessionPointer to the WebSocket session
payloadPointer to a char* which will be populated with a pointer to the payload if present
payload_lenPointer to a uint64_t which will be populated with the length of the payload if present
opcodePointer to an enum which will be populated with the opcode of the frame
fragmentedPointer to an int which is set to 1 if payload is fragmented and 0 if not
Return values
-1on error
0on success
Note
Once an AST_WEBSOCKET_OPCODE_CLOSE opcode is received the socket will be closed

Definition at line 602 of file res_http_websocket.c.

603{
604 int fin = 0;
605 int mask_present = 0;
606 char *mask = NULL, *new_payload = NULL;
607 size_t options_len = 0, frame_size = 0;
608
609 *payload = NULL;
610 *payload_len = 0;
611 *fragmented = 0;
612
613 if (ws_safe_read(session, &session->buf[0], MIN_WS_HDR_SZ, opcode)) {
614 return -1;
615 }
617
618 /* ok, now we have the first 2 bytes, so we know some flags, opcode and payload length (or whether payload length extension will be required) */
619 *opcode = session->buf[0] & 0xf;
620 *payload_len = session->buf[1] & 0x7f;
623 fin = (session->buf[0] >> 7) & 1;
624 mask_present = (session->buf[1] >> 7) & 1;
625
626 /* Based on the mask flag and payload length, determine how much more we need to read before start parsing the rest of the header */
627 options_len += mask_present ? 4 : 0;
628 options_len += (*payload_len == 126) ? 2 : (*payload_len == 127) ? 8 : 0;
629 if (options_len) {
630 /* read the rest of the header options */
631 if (ws_safe_read(session, &session->buf[frame_size], options_len, opcode)) {
632 return -1;
633 }
634 frame_size += options_len;
635 }
636
637 if (*payload_len == 126) {
638 /* Grab the 2-byte payload length */
639 *payload_len = ntohs(get_unaligned_uint16(&session->buf[2]));
640 mask = &session->buf[4];
641 } else if (*payload_len == 127) {
642 /* Grab the 8-byte payload length */
643 *payload_len = ntohll(get_unaligned_uint64(&session->buf[2]));
644 mask = &session->buf[10];
645 } else {
646 /* Just set the mask after the small 2-byte header */
647 mask = &session->buf[2];
648 }
649
650 /* Now read the rest of the payload */
651 *payload = &session->buf[frame_size]; /* payload will start here, at the end of the options, if any */
652 frame_size = frame_size + (*payload_len); /* final frame size is header + optional headers + payload data */
654 ast_log(LOG_WARNING, "Cannot fit huge websocket frame of %zu bytes\n", frame_size);
655 /* The frame won't fit :-( */
657 return -1;
658 }
659
660 if (*payload_len) {
661 if (ws_safe_read(session, *payload, *payload_len, opcode)) {
662 return -1;
663 }
664 }
665
666 /* If a mask is present unmask the payload */
667 if (mask_present) {
668 unsigned int pos;
669 for (pos = 0; pos < *payload_len; pos++) {
670 (*payload)[pos] ^= mask[pos % 4];
671 }
672 }
673
674 /* Per the RFC for PING we need to send back an opcode with the application data as received */
675 if (*opcode == AST_WEBSOCKET_OPCODE_PING) {
676 if (ast_websocket_write(session, AST_WEBSOCKET_OPCODE_PONG, *payload, *payload_len)) {
678 }
679 *payload_len = 0;
680 return 0;
681 }
682
683 /* Stop PONG processing here */
684 if (*opcode == AST_WEBSOCKET_OPCODE_PONG) {
685 *payload_len = 0;
686 return 0;
687 }
688
689 /* Save the CLOSE status code which will be sent in our own CLOSE in the destructor */
690 if (*opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
691 session->closing = 1;
692 if (*payload_len >= 2) {
693 session->close_status_code = ntohs(get_unaligned_uint16(*payload));
694 }
695 *payload_len = 0;
696 return 0;
697 }
698
699 /* Below this point we are handling TEXT, BINARY or CONTINUATION opcodes */
700 if (*payload_len) {
701 if (!(new_payload = ast_realloc(session->payload, (session->payload_len + *payload_len)))) {
702 ast_log(LOG_WARNING, "Failed allocation: %p, %zu, %"PRIu64"\n",
703 session->payload, session->payload_len, *payload_len);
704 *payload_len = 0;
706 return -1;
707 }
708
709 session->payload = new_payload;
710 memcpy((session->payload + session->payload_len), (*payload), (*payload_len));
711 session->payload_len += *payload_len;
712 } else if (!session->payload_len && session->payload) {
713 ast_free(session->payload);
714 session->payload = NULL;
715 }
716
717 if (!fin && session->reconstruct && (session->payload_len < session->reconstruct)) {
718 /* If this is not a final message we need to defer returning it until later */
719 if (*opcode != AST_WEBSOCKET_OPCODE_CONTINUATION) {
720 session->opcode = *opcode;
721 }
723 *payload_len = 0;
724 *payload = NULL;
725 } else {
726 if (*opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
727 if (!fin) {
728 /* If this was not actually the final message tell the user it is fragmented so they can deal with it accordingly */
729 *fragmented = 1;
730 } else {
731 /* Final frame in multi-frame so push up the actual opcode */
732 *opcode = session->opcode;
733 }
734 }
735 *payload_len = session->payload_len;
736 *payload = session->payload;
737 session->payload_len = 0;
738 }
739 } else {
740 ast_log(LOG_WARNING, "WebSocket unknown opcode %u\n", *opcode);
741 /* We received an opcode that we don't understand, the RFC states that 1003 is for a type of data that can't be accepted... opcodes
742 * fit that, I think. */
744 }
745
746 return 0;
747}
#define ast_free(a)
Definition: astmm.h:180
#define ast_realloc(p, len)
A wrapper for realloc()
Definition: astmm.h:226
#define ast_log
Definition: astobj2.c:42
static int frame_size[4]
Definition: format_g726.c:52
uint64_t ntohll(uint64_t net64)
Definition: strcompat.c:364
#define LOG_WARNING
#define MAXIMUM_FRAME_SIZE
Size of the pre-determined buffer for WebSocket frames.
int AST_OPTIONAL_API_NAME() ast_websocket_write(struct ast_websocket *session, enum ast_websocket_opcode opcode, char *payload, uint64_t payload_size)
Write function for websocket traffic.
#define MIN_WS_HDR_SZ
static int ws_safe_read(struct ast_websocket *session, char *buf, size_t len, enum ast_websocket_opcode *opcode)
int AST_OPTIONAL_API_NAME() ast_websocket_close(struct ast_websocket *session, uint16_t reason)
Close function for websocket session.
static unsigned short get_unaligned_uint16(const void *p)
Definition: unaligned.h:44
static uint64_t get_unaligned_uint64(const void *p)
Definition: unaligned.h:32

References ast_free, ast_log, ast_realloc, ast_websocket_close(), 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_write(), frame_size, get_unaligned_uint16(), get_unaligned_uint64(), LOG_WARNING, MAXIMUM_FRAME_SIZE, MIN_WS_HDR_SZ, ntohll(), NULL, ast_websocket::opcode, ast_websocket::payload, ast_websocket::payload_len, session, and ws_safe_read().

Referenced by ast_ari_websocket_session_read(), ast_websocket_read_string(), speech_test_server_cb(), websocket_cb(), websocket_echo_callback(), and websocket_read().

◆ ast_websocket_read_string()

int ast_websocket_read_string ( struct ast_websocket ws,
char **  buf 
)

Read a WebSocket frame containing string data.

Note
The caller is responsible for freeing the output "buf".
Parameters
wspointer to the websocket
bufstring buffer to populate with data read from socket
Return values
-1on error
Returns
number of bytes read on success
Note
Once an AST_WEBSOCKET_OPCODE_CLOSE opcode is received the socket will be closed

Definition at line 1471 of file res_http_websocket.c.

1473{
1474 char *payload;
1475 uint64_t payload_len;
1476 enum ast_websocket_opcode opcode;
1477 int fragmented = 1;
1478
1479 while (fragmented) {
1480 if (ast_websocket_read(ws, &payload, &payload_len,
1481 &opcode, &fragmented)) {
1482 ast_log(LOG_ERROR, "Client WebSocket string read - "
1483 "error reading string data\n");
1484 return -1;
1485 }
1486
1487 if (opcode == AST_WEBSOCKET_OPCODE_PING) {
1488 /* Try read again, we have sent pong already */
1489 fragmented = 1;
1490 continue;
1491 }
1492
1493 if (opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
1494 continue;
1495 }
1496
1497 if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
1498 return -1;
1499 }
1500
1501 if (opcode != AST_WEBSOCKET_OPCODE_TEXT) {
1502 ast_log(LOG_ERROR, "Client WebSocket string read - "
1503 "non string data received\n");
1504 return -1;
1505 }
1506 }
1507
1508 if (!(*buf = ast_strndup(payload, payload_len))) {
1509 return -1;
1510 }
1511
1512 return payload_len + 1;
1513}
#define ast_strndup(str, len)
A wrapper for strndup()
Definition: astmm.h:256
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
#define LOG_ERROR
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.

References ast_log, ast_strndup, AST_WEBSOCKET_OPCODE_CLOSE, AST_WEBSOCKET_OPCODE_CONTINUATION, AST_WEBSOCKET_OPCODE_PING, AST_WEBSOCKET_OPCODE_TEXT, ast_websocket_read(), buf, LOG_ERROR, ast_websocket::opcode, ast_websocket::payload, and ast_websocket::payload_len.

Referenced by AST_TEST_DEFINE().

◆ ast_websocket_reconstruct_disable()

void ast_websocket_reconstruct_disable ( struct ast_websocket session)

Disable multi-frame reconstruction.

Parameters
sessionPointer to the WebSocket session
Note
If reconstruction is disabled each message that is part of a multi-frame message will be sent up to the user when ast_websocket_read is called.

Definition at line 446 of file res_http_websocket.c.

447{
448 session->reconstruct = 0;
449}

References session.

◆ ast_websocket_reconstruct_enable()

void ast_websocket_reconstruct_enable ( struct ast_websocket session,
size_t  bytes 
)

Enable multi-frame reconstruction up to a certain number of bytes.

Parameters
sessionPointer to the WebSocket session
bytesIf a reconstructed payload exceeds the specified number of bytes the payload will be returned and upon reception of the next multi-frame a new reconstructed payload will begin.

Definition at line 441 of file res_http_websocket.c.

442{
443 session->reconstruct = MIN(bytes, MAXIMUM_RECONSTRUCTION_CEILING);
444}
#define MAXIMUM_RECONSTRUCTION_CEILING
Maximum reconstruction size for multi-frame payload reconstruction.
#define MIN(a, b)
Definition: utils.h:231

References MAXIMUM_RECONSTRUCTION_CEILING, MIN, and session.

◆ ast_websocket_ref()

void ast_websocket_ref ( struct ast_websocket session)

Increase the reference count for a WebSocket session.

Parameters
sessionPointer to the WebSocket session

Definition at line 451 of file res_http_websocket.c.

452{
453 ao2_ref(session, +1);
454}

References ao2_ref, and session.

Referenced by transport_create().

◆ ast_websocket_remote_address()

struct ast_sockaddr * ast_websocket_remote_address ( struct ast_websocket session)

Get the remote address for a WebSocket connected session.

Returns
Remote address

Definition at line 471 of file res_http_websocket.c.

472{
473 return &session->remote_address;
474}

References session.

Referenced by ast_ari_websocket_session_get_remote_addr(), transport_create(), and transport_read().

◆ ast_websocket_remove_protocol()

int ast_websocket_remove_protocol ( const char *  name,
ast_websocket_callback  callback 
)

Remove a sub-protocol handler from the default /ws server.

Parameters
nameName of the sub-protocol to unregister
callbackSession Established callback that was previously registered with the sub-protocol
Return values
0success
-1if sub-protocol was not found or if callback did not match

Definition at line 1081 of file res_http_websocket.c.

1082{
1083 return websocket_remove_protocol_internal(name, callback);
1084}
static int websocket_remove_protocol_internal(const char *name, ast_websocket_callback callback)

References name, and websocket_remove_protocol_internal().

Referenced by AST_TEST_DEFINE(), and unload_module().

◆ ast_websocket_server_add_protocol()

int ast_websocket_server_add_protocol ( struct ast_websocket_server server,
const char *  name,
ast_websocket_callback  callback 
)

Add a sub-protocol handler to the given server.

Parameters
serverThe server to add the sub-protocol to
nameName of the sub-protocol to register
callbackCallback called when a new connection requesting the sub-protocol is established
Return values
0success
-1if sub-protocol handler could not be registered
Since
12

Definition at line 210 of file res_http_websocket.c.

211{
212 struct ast_websocket_protocol *protocol;
213
214 if (!server->protocols) {
215 return -1;
216 }
217
219 if (!protocol) {
220 return -1;
221 }
222 protocol->session_established = callback;
223
224 if (ast_websocket_server_add_protocol2(server, protocol)) {
225 ao2_ref(protocol, -1);
226 return -1;
227 }
228
229 return 0;
230}
struct ast_websocket_protocol *AST_OPTIONAL_API_NAME() ast_websocket_sub_protocol_alloc(const char *name)
Allocate a websocket sub-protocol instance.
A websocket protocol implementation.
ast_websocket_callback session_established
Callback called when a new session is established. Mandatory.
struct ao2_container * protocols

References ao2_ref, ast_websocket_server_add_protocol2(), ast_websocket_sub_protocol_alloc(), name, ast_websocket_server::protocols, and ast_websocket_protocol::session_established.

Referenced by websocket_add_protocol_internal().

◆ ast_websocket_server_add_protocol2()

int ast_websocket_server_add_protocol2 ( struct ast_websocket_server server,
struct ast_websocket_protocol protocol 
)

Add a sub-protocol handler to the given server.

Parameters
serverThe server to add the sub-protocol to.
protocolThe sub-protocol to register. Note that this must be allocated using /ref ast_websocket_sub_protocol_alloc.
Note
This method is reference stealing. It will steal the reference to protocol on success.
Return values
0success
-1if sub-protocol handler could not be registered
Since
13.5.0

Definition at line 232 of file res_http_websocket.c.

233{
234 struct ast_websocket_protocol *existing;
235
236 if (!server->protocols) {
237 return -1;
238 }
239
240 if (protocol->version != AST_WEBSOCKET_PROTOCOL_VERSION) {
241 ast_log(LOG_WARNING, "WebSocket could not register sub-protocol '%s': "
242 "expected version '%u', got version '%u'\n",
243 protocol->name, AST_WEBSOCKET_PROTOCOL_VERSION, protocol->version);
244 return -1;
245 }
246
247 ao2_lock(server->protocols);
248
249 /* Ensure a second protocol handler is not registered for the same protocol */
250 existing = ao2_find(server->protocols, protocol->name, OBJ_KEY | OBJ_NOLOCK);
251 if (existing) {
252 ao2_ref(existing, -1);
253 ao2_unlock(server->protocols);
254 return -1;
255 }
256
257 ao2_link_flags(server->protocols, protocol, OBJ_NOLOCK);
258 ao2_unlock(server->protocols);
259
260 ast_verb(5, "WebSocket registered sub-protocol '%s'\n", protocol->name);
261 ao2_ref(protocol, -1);
262
263 return 0;
264}
#define OBJ_KEY
Definition: astobj2.h:1151
#define ao2_link_flags(container, obj, flags)
Add an object to a container.
Definition: astobj2.h:1554
#define ao2_find(container, arg, flags)
Definition: astobj2.h:1736
@ OBJ_NOLOCK
Assume that the ao2_container is already locked.
Definition: astobj2.h:1063
#define AST_WEBSOCKET_PROTOCOL_VERSION
Protocol version. This prevents dynamically loadable modules from registering if this struct is chang...
unsigned int version
Protocol version. Should be set to /ref AST_WEBSOCKET_PROTOCOL_VERSION.
char * name
Name of the protocol.

References ao2_find, ao2_link_flags, ao2_lock, ao2_ref, ao2_unlock, ast_log, ast_verb, AST_WEBSOCKET_PROTOCOL_VERSION, LOG_WARNING, OBJ_KEY, OBJ_NOLOCK, and ast_websocket_server::protocols.

Referenced by ast_websocket_add_protocol2(), ast_websocket_server_add_protocol(), and load_module().

◆ ast_websocket_server_create()

struct ast_websocket_server * ast_websocket_server_create ( void  )

Creates a ast_websocket_server.

Returns
New ast_websocket_server instance
Return values
NULLon error
Since
12

Definition at line 167 of file res_http_websocket.c.

168{
170}
static struct ast_websocket_server * websocket_server_create_impl(void)

References websocket_server_create_impl().

Referenced by load_module().

◆ ast_websocket_server_remove_protocol()

int ast_websocket_server_remove_protocol ( struct ast_websocket_server server,
const char *  name,
ast_websocket_callback  callback 
)

Remove a sub-protocol handler from the given server.

Parameters
serverThe server to unregister the sub-protocol from
nameName of the sub-protocol to unregister
callbackCallback that was previously registered with the sub-protocol
Return values
0success
-1if sub-protocol was not found or if callback did not match
Since
12

Definition at line 266 of file res_http_websocket.c.

267{
268 struct ast_websocket_protocol *protocol;
269
270 if (!(protocol = ao2_find(server->protocols, name, OBJ_KEY))) {
271 return -1;
272 }
273
274 if (protocol->session_established != callback) {
275 ao2_ref(protocol, -1);
276 return -1;
277 }
278
279 ao2_unlink(server->protocols, protocol);
280 ao2_ref(protocol, -1);
281
282 ast_verb(5, "WebSocket unregistered sub-protocol '%s'\n", name);
283
284 return 0;
285}
#define ao2_unlink(container, obj)
Remove an object from a container.
Definition: astobj2.h:1578

References ao2_find, ao2_ref, ao2_unlink, ast_verb, name, OBJ_KEY, ast_websocket_server::protocols, and ast_websocket_protocol::session_established.

Referenced by websocket_remove_protocol_internal().

◆ ast_websocket_session_id()

const char * ast_websocket_session_id ( struct ast_websocket session)

Get the session ID for a WebSocket session.

Returns
session id

Definition at line 500 of file res_http_websocket.c.

501{
502 return session->session_id;
503}

References session.

Referenced by ast_ari_websocket_session_id().

◆ ast_websocket_set_nonblock()

int ast_websocket_set_nonblock ( struct ast_websocket session)

Set the socket of a WebSocket session to be non-blocking.

Return values
0on success
-1on failure

Definition at line 486 of file res_http_websocket.c.

487{
490 return 0;
491}
void ast_iostream_set_exclusive_input(struct ast_iostream *stream, int exclusive_input)
Set the iostream if it can exclusively depend upon the set timeouts.
Definition: iostream.c:149
void ast_iostream_nonblock(struct ast_iostream *stream)
Make an iostream non-blocking.
Definition: iostream.c:104

References ast_iostream_nonblock(), ast_iostream_set_exclusive_input(), and session.

Referenced by ast_ari_websocket_session_create(), and websocket_cb().

◆ ast_websocket_set_timeout()

int ast_websocket_set_timeout ( struct ast_websocket session,
int  timeout 
)

Set the timeout on a non-blocking WebSocket session.

Since
11.11.0
12.4.0
Return values
0on success
-1on failure

Definition at line 493 of file res_http_websocket.c.

494{
495 session->timeout = timeout;
496
497 return 0;
498}

References session, and ast_websocket::timeout.

Referenced by ast_ari_websocket_session_create(), and websocket_cb().

◆ ast_websocket_sub_protocol_alloc()

struct ast_websocket_protocol * ast_websocket_sub_protocol_alloc ( const char *  name)

Allocate a websocket sub-protocol instance.

Returns
An instance of ast_websocket_protocol on success
Return values
NULLon error
Since
13.5.0

Definition at line 191 of file res_http_websocket.c.

192{
193 struct ast_websocket_protocol *protocol;
194
195 protocol = ao2_alloc(sizeof(*protocol), protocol_destroy_fn);
196 if (!protocol) {
197 return NULL;
198 }
199
200 protocol->name = ast_strdup(name);
201 if (!protocol->name) {
202 ao2_ref(protocol, -1);
203 return NULL;
204 }
206
207 return protocol;
208}
#define ast_strdup(str)
A wrapper for strdup()
Definition: astmm.h:241
#define ao2_alloc(data_size, destructor_fn)
Definition: astobj2.h:409
static void protocol_destroy_fn(void *obj)
Destructor function for protocols.

References ao2_alloc, ao2_ref, ast_strdup, AST_WEBSOCKET_PROTOCOL_VERSION, name, ast_websocket_protocol::name, NULL, protocol_destroy_fn(), and ast_websocket_protocol::version.

Referenced by ast_websocket_server_add_protocol(), and load_module().

◆ ast_websocket_unref()

void ast_websocket_unref ( struct ast_websocket session)

Decrease the reference count for a WebSocket session.

Parameters
sessionPointer to the WebSocket session

Definition at line 456 of file res_http_websocket.c.

457{
459}
#define ao2_cleanup(obj)
Definition: astobj2.h:1934

References ao2_cleanup, and session.

Referenced by ast_ari_events_event_websocket_ws_established_cb(), speech_test_server_cb(), transport_dtor(), websocket_cb(), websocket_disconnect(), websocket_echo_callback(), and websocket_session_dtor().

◆ ast_websocket_uri_cb()

int ast_websocket_uri_cb ( struct ast_tcptls_session_instance ser,
const struct ast_http_uri urih,
const char *  uri,
enum ast_http_method  method,
struct ast_variable get_vars,
struct ast_variable headers 
)

Callback suitable for use with a ast_http_uri.

Set the data field of the ast_http_uri to ast_websocket_server.

Since
12

Definition at line 790 of file res_http_websocket.c.

791{
792 struct ast_variable *v;
793 const char *upgrade = NULL, *key = NULL, *key1 = NULL, *key2 = NULL, *protos = NULL;
794 char *requested_protocols = NULL, *protocol = NULL;
795 int version = 0, flags = 1;
796 struct ast_websocket_protocol *protocol_handler = NULL;
797 struct ast_websocket *session;
798 struct ast_websocket_server *server;
799
801
802 /* Upgrade requests are only permitted on GET methods */
803 if (method != AST_HTTP_GET) {
804 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
805 return 0;
806 }
807
808 server = urih->data;
809
810 /* Get the minimum headers required to satisfy our needs */
811 for (v = headers; v; v = v->next) {
812 if (!strcasecmp(v->name, "Upgrade")) {
813 upgrade = v->value;
814 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key")) {
815 key = v->value;
816 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key1")) {
817 key1 = v->value;
818 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key2")) {
819 key2 = v->value;
820 } else if (!strcasecmp(v->name, "Sec-WebSocket-Protocol")) {
821 protos = v->value;
822 } else if (!strcasecmp(v->name, "Sec-WebSocket-Version")) {
823 if (sscanf(v->value, "%30d", &version) != 1) {
824 version = 0;
825 }
826 }
827 }
828
829 /* If this is not a websocket upgrade abort */
830 if (!upgrade || strcasecmp(upgrade, "websocket")) {
831 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - did not request WebSocket\n",
833 ast_http_error(ser, 426, "Upgrade Required", NULL);
834 return 0;
835 } else if (ast_strlen_zero(protos)) {
836 /* If there's only a single protocol registered, and the
837 * client doesn't specify what protocol it's using, go ahead
838 * and accept the connection */
839 protocol_handler = one_protocol(server);
840 if (!protocol_handler) {
841 /* Multiple registered subprotocols; client must specify */
842 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols requested\n",
845 return 0;
846 }
847 } else if (key1 && key2) {
848 /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 and
849 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 -- not currently supported*/
850 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '00/76' chosen\n",
853 return 0;
854 }
855
856 if (!protocol_handler && protos) {
857 requested_protocols = ast_strdupa(protos);
858 /* Iterate through the requested protocols trying to find one that we have a handler for */
859 while (!protocol_handler && (protocol = strsep(&requested_protocols, ","))) {
860 protocol_handler = ao2_find(server->protocols, ast_strip(protocol), OBJ_KEY);
861 }
862 }
863
864 /* If no protocol handler exists bump this back to the requester */
865 if (!protocol_handler) {
866 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols out of '%s' supported\n",
869 return 0;
870 }
871
872 /* Determine how to respond depending on the version */
873 if (version == 7 || version == 8 || version == 13) {
874 char base64[64];
875
876 if (!key || strlen(key) + strlen(WEBSOCKET_GUID) + 1 > 8192) { /* no stack overflows please */
878 ao2_ref(protocol_handler, -1);
879 return 0;
880 }
881
882 if (ast_http_body_discard(ser)) {
884 ao2_ref(protocol_handler, -1);
885 return 0;
886 }
887
888 if (!(session = ao2_alloc(sizeof(*session) + AST_UUID_STR_LEN + 1, session_destroy_fn))) {
889 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted\n",
892 ao2_ref(protocol_handler, -1);
893 return 0;
894 }
896
897 /* Generate the session id */
898 if (!ast_uuid_generate_str(session->session_id, sizeof(session->session_id))) {
899 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to generate a session id\n",
901 ast_http_error(ser, 500, "Internal Server Error", "Allocation failed");
902 ao2_ref(protocol_handler, -1);
903 return 0;
904 }
905
906 if (protocol_handler->session_attempted
907 && protocol_handler->session_attempted(ser, get_vars, headers, session->session_id)) {
908 ast_debug(3, "WebSocket connection from '%s' rejected by protocol handler '%s'\n",
909 ast_sockaddr_stringify(&ser->remote_address), protocol_handler->name);
911 ao2_ref(protocol_handler, -1);
912 return 0;
913 }
914
915 /* RFC 6455, Section 4.1:
916 *
917 * 6. If the response includes a |Sec-WebSocket-Protocol| header
918 * field and this header field indicates the use of a
919 * subprotocol that was not present in the client's handshake
920 * (the server has indicated a subprotocol not requested by
921 * the client), the client MUST _Fail the WebSocket
922 * Connection_.
923 */
924 if (protocol) {
926 "HTTP/1.1 101 Switching Protocols\r\n"
927 "Upgrade: %s\r\n"
928 "Connection: Upgrade\r\n"
929 "Sec-WebSocket-Accept: %s\r\n"
930 "Sec-WebSocket-Protocol: %s\r\n\r\n",
931 upgrade,
932 websocket_combine_key(key, base64, sizeof(base64)),
933 protocol);
934 } else {
936 "HTTP/1.1 101 Switching Protocols\r\n"
937 "Upgrade: %s\r\n"
938 "Connection: Upgrade\r\n"
939 "Sec-WebSocket-Accept: %s\r\n\r\n",
940 upgrade,
941 websocket_combine_key(key, base64, sizeof(base64)));
942 }
943 } else {
944
945 /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 or completely unknown */
946 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '%d' chosen\n",
949 ao2_ref(protocol_handler, -1);
950 return 0;
951 }
952
953 /* Enable keepalive on all sessions so the underlying user does not have to */
954 if (setsockopt(ast_iostream_get_fd(ser->stream), SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
955 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to enable keepalive\n",
958 ao2_ref(session, -1);
959 ao2_ref(protocol_handler, -1);
960 return 0;
961 }
962
963 /* Get our local address for the connected socket */
964 if (ast_getsockname(ast_iostream_get_fd(ser->stream), &session->local_address)) {
965 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to get local address\n",
968 ao2_ref(session, -1);
969 ao2_ref(protocol_handler, -1);
970 return 0;
971 }
972
973 ast_verb(2, "WebSocket connection from '%s' for protocol '%s' accepted using version '%d'\n", ast_sockaddr_stringify(&ser->remote_address), protocol ? : "", version);
974
975 /* Populate the session with all the needed details */
976 session->stream = ser->stream;
977 ast_sockaddr_copy(&session->remote_address, &ser->remote_address);
978 session->opcode = -1;
980 session->secure = ast_iostream_get_ssl(ser->stream) ? 1 : 0;
981
982 /* Give up ownership of the socket and pass it to the protocol handler */
984 protocol_handler->session_established(session, get_vars, headers);
985 ao2_ref(protocol_handler, -1);
986
987 /*
988 * By dropping the stream from the session the connection
989 * won't get closed when the HTTP server cleans up because we
990 * passed the connection to the protocol handler.
991 */
992 ser->stream = NULL;
993
994 return 0;
995}
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:298
static char version[AST_MAX_EXTENSION]
Definition: chan_ooh323.c:391
@ AST_HTTP_GET
Definition: http.h:60
int ast_http_body_discard(struct ast_tcptls_session_instance *ser)
Read and discard any unread HTTP request body.
Definition: http.c:1122
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:651
#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT
Default websocket write timeout, in ms.
char * strsep(char **str, const char *delims)
#define ast_debug(level,...)
Log a DEBUG message.
ssize_t ast_iostream_printf(struct ast_iostream *stream, const char *format,...)
Write a formatted string to an iostream.
Definition: iostream.c:502
SSL * ast_iostream_get_ssl(struct ast_iostream *stream)
Get a pointer to an iostream's OpenSSL SSL structure.
Definition: iostream.c:109
#define SCOPED_MODULE_USE(module)
Definition: module.h:679
int ast_getsockname(int sockfd, struct ast_sockaddr *addr)
Wrapper around getsockname(2) that uses struct ast_sockaddr.
Definition: netsock2.c:600
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
Definition: netsock2.h:167
static void websocket_bad_request(struct ast_tcptls_session_instance *ser)
static struct ast_websocket_protocol * one_protocol(struct ast_websocket_server *server)
If the server has exactly one configured protocol, return it.
#define DEFAULT_RECONSTRUCTION_CEILING
Default reconstruction size for multi-frame payload reconstruction. If exceeded the next frame will s...
static char * websocket_combine_key(const char *key, char *res, int res_size)
#define WEBSOCKET_GUID
GUID used to compute the accept key, defined in the specifications.
static void session_destroy_fn(void *obj)
Destructor function for sessions.
const char * method
Definition: res_pjsip.c:1279
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
struct ast_module * self
Definition: module.h:356
struct ast_iostream * stream
Definition: tcptls.h:161
struct ast_sockaddr remote_address
Definition: tcptls.h:152
Structure for variables, used for configurations and for channel variables.
struct ast_variable * next
ast_websocket_pre_callback session_attempted
Callback called when a new session is attempted. Optional.
static char base64[64]
Definition: utils.c:80
#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

References ao2_alloc, ao2_find, ao2_ref, ast_debug, AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT, ast_getsockname(), ast_http_body_discard(), ast_http_error(), AST_HTTP_GET, ast_iostream_get_fd(), ast_iostream_get_ssl(), ast_iostream_printf(), ast_iostream_set_exclusive_input(), ast_log, ast_sockaddr_copy(), ast_sockaddr_stringify(), ast_strdupa, ast_strip(), ast_strlen_zero(), ast_uuid_generate_str(), AST_UUID_STR_LEN, ast_verb, base64, ast_http_uri::data, DEFAULT_RECONSTRUCTION_CEILING, LOG_WARNING, method, ast_variable::name, ast_websocket_protocol::name, ast_variable::next, NULL, OBJ_KEY, one_protocol(), ast_websocket_server::protocols, ast_tcptls_session_instance::remote_address, SCOPED_MODULE_USE, ast_module_info::self, session, ast_websocket_protocol::session_attempted, session_destroy_fn(), ast_websocket_protocol::session_established, ast_tcptls_session_instance::stream, strsep(), 210693f3123d_create_cdr_table::upgrade(), ast_variable::value, version, websocket_bad_request(), websocket_combine_key(), and WEBSOCKET_GUID.

Referenced by ari_handle_websocket().

◆ ast_websocket_wait_for_input()

int ast_websocket_wait_for_input ( struct ast_websocket session,
int  timeout 
)

Wait for the WebSocket session to be ready to be read.

Since
16.8.0
17.2.0
Parameters
sessionPointer to the WebSocket session
timeoutthe number of milliseconds to wait
Return values
-1if error occurred
0if the timeout expired
1if the WebSocket session is ready for reading

Definition at line 466 of file res_http_websocket.c.

467{
468 return session->closing ? -1 : ast_iostream_wait_for_input(session->stream, timeout);
469}
int ast_iostream_wait_for_input(struct ast_iostream *stream, int timeout)
Wait for input on the iostream's file descriptor.
Definition: iostream.c:90

References ast_iostream_wait_for_input(), session, and ast_websocket::timeout.

Referenced by speech_test_server_cb(), websocket_cb(), websocket_echo_callback(), and websocket_read().

◆ ast_websocket_write()

int ast_websocket_write ( struct ast_websocket session,
enum ast_websocket_opcode  opcode,
char *  payload,
uint64_t  payload_size 
)

Construct and transmit a WebSocket frame.

Parameters
sessionPointer to the WebSocket session
opcodeWebSocket operation code to place in the frame
payloadOptional pointer to a payload to add to the frame
payload_sizeLength of the payload (0 if no payload)
Return values
0if successfully written
-1if error occurred

Construct and transmit a WebSocket frame.

Definition at line 374 of file res_http_websocket.c.

375{
376 size_t header_size = 2; /* The minimum size of a websocket frame is 2 bytes */
377 char *frame;
378 uint64_t length;
379 uint64_t frame_size;
380
381 ast_debug(3, "Writing websocket %s frame, length %" PRIu64 "\n",
382 websocket_opcode2str(opcode), payload_size);
383
384 if (payload_size < 126) {
385 length = payload_size;
386 } else if (payload_size < (1 << 16)) {
387 length = 126;
388 /* We need an additional 2 bytes to store the extended length */
389 header_size += 2;
390 } else {
391 length = 127;
392 /* We need an additional 8 bytes to store the really really extended length */
393 header_size += 8;
394 }
395
396 if (session->client) {
397 /* Additional 4 bytes for the client masking key */
398 header_size += 4;
399 }
400
401 frame_size = header_size + payload_size;
402
403 frame = ast_alloca(frame_size + 1);
404 memset(frame, 0, frame_size + 1);
405
406 frame[0] = opcode | 0x80;
407 frame[1] = length;
408
409 /* Use the additional available bytes to store the length */
410 if (length == 126) {
411 put_unaligned_uint16(&frame[2], htons(payload_size));
412 } else if (length == 127) {
413 put_unaligned_uint64(&frame[2], htonll(payload_size));
414 }
415
416 memcpy(&frame[header_size], payload, payload_size);
417
418 websocket_mask_payload(session, frame, &frame[header_size], payload_size);
419
421 if (session->closing) {
423 return -1;
424 }
425
427 if (ast_iostream_write(session->stream, frame, frame_size) != frame_size) {
429 /* 1011 - server terminating connection due to not being able to fulfill the request */
430 ast_debug(1, "Closing WS with 1011 because we can't fulfill a write request\n");
432 return -1;
433 }
434
437
438 return 0;
439}
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition: astmm.h:288
uint64_t htonll(uint64_t host64)
Definition: strcompat.c:390
void ast_iostream_set_timeout_sequence(struct ast_iostream *stream, struct timeval start, int timeout)
Set the iostream I/O sequence timeout timer.
Definition: iostream.c:140
static const char * websocket_opcode2str(enum ast_websocket_opcode opcode)
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159
static void put_unaligned_uint64(void *p, uint64_t datum)
Definition: unaligned.h:51

References ao2_lock, ao2_unlock, ast_alloca, ast_debug, ast_iostream_set_timeout_disable(), ast_iostream_set_timeout_sequence(), ast_iostream_write(), ast_tvnow(), ast_websocket_close(), frame_size, htonll(), ast_websocket::opcode, ast_websocket::payload, put_unaligned_uint16(), put_unaligned_uint64(), session, websocket_mask_payload(), and websocket_opcode2str().

Referenced by ast_ari_events_event_websocket_ws_established_cb(), ast_websocket_read(), ast_websocket_write_string(), speech_test_server_cb(), websocket_echo_callback(), websocket_write(), and ws_send_msg().

◆ ast_websocket_write_string()

int ast_websocket_write_string ( struct ast_websocket ws,
const char *  buf 
)

Construct and transmit a WebSocket frame containing string data.

Parameters
wspointer to the websocket
bufstring data to write to socket
Return values
0if successfully written
-1if error occurred

Definition at line 1515 of file res_http_websocket.c.

1517{
1518 uint64_t len = strlen(buf);
1519
1520 ast_debug(3, "Writing websocket string of length %" PRIu64 "\n", len);
1521
1522 /* We do not pass strlen(buf) to ast_websocket_write() directly because the
1523 * size_t returned by strlen() may not require the same storage size
1524 * as the uint64_t that ast_websocket_write() uses. This normally
1525 * would not cause a problem, but since ast_websocket_write() uses
1526 * the optional API, this function call goes through a series of macros
1527 * that may cause a 32-bit to 64-bit conversion to go awry.
1528 */
1530 (char *)buf, len);
1531}
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)

References ast_debug, AST_WEBSOCKET_OPCODE_TEXT, ast_websocket_write(), buf, and len().

Referenced by ast_ari_websocket_session_write(), AST_TEST_DEFINE(), and speech_test_server_handle_request().