Asterisk - The Open Source Telephony Project GIT-master-35be64c
Loading...
Searching...
No Matches
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.
 
#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT_STR   "100"
 Default websocket write timeout, in ms (as a string)
 
#define AST_WEBSOCKET_MAX_RX_PAYLOAD_SIZE   65535
 Size of the pre-determined buffer for WebSocket frames.
 
#define AST_WEBSOCKET_PROTOCOL_VERSION   1
 Protocol version. This prevents dynamically loadable modules from registering if this struct is changed.
 

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

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 , AST_WEBSOCKET_OPCODE_UNKNOWN = 0xf
}
 WebSocket operation codes. More...
 
enum  ast_websocket_result {
  WS_OK = 0 , 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 , WS_UNAUTHORIZED , WS_TLS_ERROR
}
 Result code for a websocket client. More...
 
enum  ast_websocket_status_code {
  AST_WEBSOCKET_STATUS_NORMAL = 1000 , AST_WEBSOCKET_STATUS_GOING_AWAY = 1001 , AST_WEBSOCKET_STATUS_PROTOCOL_ERROR = 1002 , AST_WEBSOCKET_STATUS_UNSUPPORTED_DATA = 1003 ,
  AST_WEBSOCKET_STATUS_RESERVED_1004 = 1004 , AST_WEBSOCKET_STATUS_RESERVED_1005 = 1005 , AST_WEBSOCKET_STATUS_RESERVED_1006 = 1006 , AST_WEBSOCKET_STATUS_INVALID_FRAME = 1007 ,
  AST_WEBSOCKET_STATUS_POLICY_VIOLATION = 1008 , AST_WEBSOCKET_STATUS_TOO_BIG = 1009 , AST_WEBSOCKET_STATUS_MANDATORY_EXT = 1010 , AST_WEBSOCKET_STATUS_INTERNAL_ERROR = 1011 ,
  AST_WEBSOCKET_STATUS_RESERVED_1012 = 1012 , AST_WEBSOCKET_STATUS_RESERVED_1013 = 1013 , AST_WEBSOCKET_STATUS_BAD_GATEWAY = 1014 , AST_WEBSOCKET_STATUS_RESERVED_1015 = 1015
}
 Websocket Status Codes from RFC-6455. More...
 
enum  ast_websocket_type {
  AST_WS_TYPE_CLIENT_PERSISTENT = (1 << 0) , AST_WS_TYPE_CLIENT_PER_CALL_CONFIG = (1 << 1) , AST_WS_TYPE_CLIENT_PER_CALL = (1 << 2) , AST_WS_TYPE_CLIENT = (1 << 3) ,
  AST_WS_TYPE_INBOUND = (1 << 4) , AST_WS_TYPE_SERVER = (1 << 5) , AST_WS_TYPE_ANY = (0xFFFFFFFF)
}
 WebSocket connection/configuration types. More...
 

Functions

int AST_OPTIONAL_API_NAME() ast_websocket_add_protocol (const char *name, ast_websocket_callback callback)
 Add a sub-protocol handler to the default /ws server.
 
int AST_OPTIONAL_API_NAME() ast_websocket_add_protocol2 (struct ast_websocket_protocol *protocol)
 Add a sub-protocol handler to the default /ws server.
 
const char *AST_OPTIONAL_API_NAME() ast_websocket_client_accept_protocol (struct ast_websocket *ws)
 Retrieve the server accepted sub-protocol on the client.
 
struct ast_websocket *AST_OPTIONAL_API_NAME() 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.
 
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.
 
int AST_OPTIONAL_API_NAME() ast_websocket_close (struct ast_websocket *session, uint16_t reason)
 Close a WebSocket session by sending a message with the CLOSE opcode and an optional code.
 
int AST_OPTIONAL_API_NAME() ast_websocket_fd (struct ast_websocket *session)
 Get the file descriptor for a WebSocket session.
 
int AST_OPTIONAL_API_NAME() ast_websocket_is_secure (struct ast_websocket *session)
 Get whether the WebSocket session is using a secure transport or not.
 
struct ast_sockaddr *AST_OPTIONAL_API_NAME() ast_websocket_local_address (struct ast_websocket *session)
 Get the local address for a WebSocket connection session.
 
int AST_OPTIONAL_API_NAME() ast_websocket_read (struct ast_websocket *session, char **payload, uint64_t *payload_len, enum ast_websocket_opcode *opcode, int *fragmented)
 Read a WebSocket frame and handle it.
 
int AST_OPTIONAL_API_NAME() ast_websocket_read_string (struct ast_websocket *ws, char **buf)
 Read a WebSocket frame containing string data.
 
void AST_OPTIONAL_API_NAME() ast_websocket_reconstruct_disable (struct ast_websocket *session)
 Disable multi-frame reconstruction.
 
void AST_OPTIONAL_API_NAME() ast_websocket_reconstruct_enable (struct ast_websocket *session, size_t bytes)
 Enable multi-frame reconstruction up to a certain number of bytes.
 
void AST_OPTIONAL_API_NAME() ast_websocket_ref (struct ast_websocket *session)
 Increase the reference count for a WebSocket session.
 
struct ast_sockaddr *AST_OPTIONAL_API_NAME() ast_websocket_remote_address (struct ast_websocket *session)
 Get the remote address for a WebSocket connected session.
 
int AST_OPTIONAL_API_NAME() ast_websocket_remove_protocol (const char *name, ast_websocket_callback callback)
 Remove a sub-protocol handler from the default /ws server.
 
const char *AST_OPTIONAL_API_NAME() ast_websocket_result_to_str (enum ast_websocket_result result)
 Convert a websocket result code to a string.
 
int AST_OPTIONAL_API_NAME() 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.
 
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.
 
struct ast_websocket_server *AST_OPTIONAL_API_NAME() ast_websocket_server_create (void)
 Creates a ast_websocket_server.
 
int AST_OPTIONAL_API_NAME() 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.
 
const char *AST_OPTIONAL_API_NAME() ast_websocket_session_id (struct ast_websocket *session)
 Get the session ID for a WebSocket session.
 
int AST_OPTIONAL_API_NAME() ast_websocket_set_nonblock (struct ast_websocket *session)
 Set the socket of a WebSocket session to be non-blocking.
 
int AST_OPTIONAL_API_NAME() ast_websocket_set_timeout (struct ast_websocket *session, int timeout)
 Set the timeout on a non-blocking WebSocket session.
 
const char *AST_OPTIONAL_API_NAME() ast_websocket_status_to_str (enum ast_websocket_status_code code)
 Convert a websocket status code to a string.
 
struct ast_websocket_protocol *AST_OPTIONAL_API_NAME() ast_websocket_sub_protocol_alloc (const char *name)
 Allocate a websocket sub-protocol instance.
 
const char * ast_websocket_type_to_str (enum ast_websocket_type type)
 
void AST_OPTIONAL_API_NAME() ast_websocket_unref (struct ast_websocket *session)
 Decrease the reference count for a WebSocket session.
 
int AST_OPTIONAL_API_NAME() ast_websocket_uri_cb (struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_vars, struct ast_variable *headers)
 Callback suitable for use with a ast_http_uri.
 
int AST_OPTIONAL_API_NAME() ast_websocket_wait_for_input (struct ast_websocket *session, int timeout)
 Wait for the WebSocket session to be ready to be read.
 
int AST_OPTIONAL_API_NAME() ast_websocket_write (struct ast_websocket *session, enum ast_websocket_opcode opcode, char *payload, uint64_t payload_size)
 Construct and transmit a WebSocket frame.
 
int AST_OPTIONAL_API_NAME() ast_websocket_write_string (struct ast_websocket *ws, const char *buf)
 Construct and transmit a WebSocket frame containing string data.
 

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_MAX_RX_PAYLOAD_SIZE

#define AST_WEBSOCKET_MAX_RX_PAYLOAD_SIZE   65535

Size of the pre-determined buffer for WebSocket frames.

Definition at line 106 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 169 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 150 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 137 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

AST_WEBSOCKET_OPCODE_UNKNOWN 

Error

Definition at line 71 of file http_websocket.h.

71 {
72 AST_WEBSOCKET_OPCODE_TEXT = 0x1, /*!< Text frame */
73 AST_WEBSOCKET_OPCODE_BINARY = 0x2, /*!< Binary frame */
74 AST_WEBSOCKET_OPCODE_PING = 0x9, /*!< Request that the other side respond with a pong */
75 AST_WEBSOCKET_OPCODE_PONG = 0xA, /*!< Response to a ping */
76 AST_WEBSOCKET_OPCODE_CLOSE = 0x8, /*!< Connection is being closed */
77 AST_WEBSOCKET_OPCODE_CONTINUATION = 0x0, /*!< Continuation of a previous frame */
78 AST_WEBSOCKET_OPCODE_UNKNOWN = 0xf, /*!< Error */
79};
@ AST_WEBSOCKET_OPCODE_PING
@ AST_WEBSOCKET_OPCODE_PONG
@ AST_WEBSOCKET_OPCODE_CONTINUATION
@ AST_WEBSOCKET_OPCODE_BINARY
@ AST_WEBSOCKET_OPCODE_UNKNOWN
@ 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 
WS_UNAUTHORIZED 
WS_TLS_ERROR 

Definition at line 448 of file http_websocket.h.

448 {
449 WS_OK = 0,
465};
@ WS_BAD_REQUEST
@ WS_TLS_ERROR
@ WS_URL_NOT_FOUND
@ WS_CLIENT_START_ERROR
@ WS_KEY_ERROR
@ WS_NOT_SUPPORTED
@ WS_ALLOCATE_ERROR
@ WS_HEADER_MISMATCH
@ WS_WRITE_ERROR
@ WS_UNAUTHORIZED
@ WS_URI_RESOLVE_ERROR
@ WS_OK
@ WS_INVALID_RESPONSE
@ WS_BAD_STATUS
@ WS_URI_PARSE_ERROR
@ WS_HEADER_MISSING

◆ ast_websocket_status_code

Websocket Status Codes from RFC-6455.

Enumerator
AST_WEBSOCKET_STATUS_NORMAL 
AST_WEBSOCKET_STATUS_GOING_AWAY 
AST_WEBSOCKET_STATUS_PROTOCOL_ERROR 
AST_WEBSOCKET_STATUS_UNSUPPORTED_DATA 
AST_WEBSOCKET_STATUS_RESERVED_1004 
AST_WEBSOCKET_STATUS_RESERVED_1005 
AST_WEBSOCKET_STATUS_RESERVED_1006 
AST_WEBSOCKET_STATUS_INVALID_FRAME 
AST_WEBSOCKET_STATUS_POLICY_VIOLATION 
AST_WEBSOCKET_STATUS_TOO_BIG 
AST_WEBSOCKET_STATUS_MANDATORY_EXT 
AST_WEBSOCKET_STATUS_INTERNAL_ERROR 
AST_WEBSOCKET_STATUS_RESERVED_1012 
AST_WEBSOCKET_STATUS_RESERVED_1013 
AST_WEBSOCKET_STATUS_BAD_GATEWAY 
AST_WEBSOCKET_STATUS_RESERVED_1015 

Definition at line 82 of file http_websocket.h.

82 {
99};
@ AST_WEBSOCKET_STATUS_RESERVED_1015
@ AST_WEBSOCKET_STATUS_BAD_GATEWAY
@ AST_WEBSOCKET_STATUS_UNSUPPORTED_DATA
@ AST_WEBSOCKET_STATUS_PROTOCOL_ERROR
@ AST_WEBSOCKET_STATUS_NORMAL
@ AST_WEBSOCKET_STATUS_MANDATORY_EXT
@ AST_WEBSOCKET_STATUS_TOO_BIG
@ AST_WEBSOCKET_STATUS_RESERVED_1006
@ AST_WEBSOCKET_STATUS_RESERVED_1004
@ AST_WEBSOCKET_STATUS_RESERVED_1013
@ AST_WEBSOCKET_STATUS_RESERVED_1005
@ AST_WEBSOCKET_STATUS_POLICY_VIOLATION
@ AST_WEBSOCKET_STATUS_GOING_AWAY
@ AST_WEBSOCKET_STATUS_INTERNAL_ERROR
@ AST_WEBSOCKET_STATUS_RESERVED_1012
@ AST_WEBSOCKET_STATUS_INVALID_FRAME

◆ ast_websocket_type

WebSocket connection/configuration types.

These may look like they overlap or are redundant, but they're shared by other modules like ari and chan_websocket and it didn't make sense to force them to define their own types.

Enumerator
AST_WS_TYPE_CLIENT_PERSISTENT 
AST_WS_TYPE_CLIENT_PER_CALL_CONFIG 
AST_WS_TYPE_CLIENT_PER_CALL 
AST_WS_TYPE_CLIENT 
AST_WS_TYPE_INBOUND 
AST_WS_TYPE_SERVER 
AST_WS_TYPE_ANY 

Definition at line 57 of file http_websocket.h.

57 {
61 AST_WS_TYPE_CLIENT = (1 << 3),
62 AST_WS_TYPE_INBOUND = (1 << 4),
63 AST_WS_TYPE_SERVER = (1 << 5),
64 AST_WS_TYPE_ANY = (0xFFFFFFFF),
65};
@ AST_WS_TYPE_ANY
@ AST_WS_TYPE_CLIENT
@ AST_WS_TYPE_INBOUND
@ AST_WS_TYPE_CLIENT_PER_CALL_CONFIG
@ AST_WS_TYPE_SERVER
@ AST_WS_TYPE_CLIENT_PERSISTENT
@ AST_WS_TYPE_CLIENT_PER_CALL

Function Documentation

◆ ast_websocket_add_protocol()

int AST_OPTIONAL_API_NAME() 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 1252 of file res_http_websocket.c.

1253{
1255}
static struct ast_channel * callback(struct ast_channelstorage_instance *driver, ao2_callback_data_fn *cb_fn, void *arg, void *data, int ao2_flags, int rdlock)
static const char name[]
Definition format_mp3.c:68
static int websocket_add_protocol_internal(const char *name, ast_websocket_callback callback)

References callback(), name, and websocket_add_protocol_internal().

Referenced by AST_TEST_DEFINE(), and load_module().

◆ ast_websocket_add_protocol2()

int AST_OPTIONAL_API_NAME() 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 1257 of file res_http_websocket.c.

1258{
1259 struct ast_websocket_server *ws_server = websocketuri.data;
1260
1261 if (!ws_server) {
1262 return -1;
1263 }
1264
1265 if (ast_websocket_server_add_protocol2(ws_server, protocol)) {
1266 return -1;
1267 }
1268
1269 return 0;
1270}
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_OPTIONAL_API_NAME() 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 1573 of file res_http_websocket.c.

1575{
1576 return ws->client->accept_protocol;
1577}
struct websocket_client * client

References websocket_client::accept_protocol, and ast_websocket::client.

Referenced by AST_TEST_DEFINE().

◆ ast_websocket_client_create()

struct ast_websocket *AST_OPTIONAL_API_NAME() 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
Warning
The returned websocket must be closed with ast_websocket_close and its reference count decremented with ast_websocket_unref when it's no longer needed.

Definition at line 1924 of file res_http_websocket.c.

1927{
1929 .uri = uri,
1930 .protocols = protocols,
1931 .timeout = -1,
1932 .tls_cfg = tls_cfg,
1933 .write_timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT,
1934 };
1935
1937}
static PGresult * result
Definition cel_pgsql.c:84
#define AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT
Default websocket write timeout, in ms.
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_DEFAULT_WEBSOCKET_WRITE_TIMEOUT, 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_TEST_DEFINE(), AST_TEST_DEFINE(), and AST_TEST_DEFINE().

◆ ast_websocket_client_create_with_options()

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.

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
Warning
The returned websocket must be closed with ast_websocket_close and its reference count decremented with ast_websocket_unref when it's no longer needed.

Definition at line 2043 of file res_http_websocket.c.

2045{
2046 struct ast_websocket *ws = NULL;
2047 SCOPE_ENTER(2, "%s: Creating client\n", options->uri);
2048
2050 if (!ws) {
2051 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_ERROR, "%s: Failed to create: %s\n", options->uri, ast_websocket_result_to_str(*result));
2052 }
2053
2054 ast_trace(-1, "%s: Connecting\n", ws->client->options->uri);
2055
2056 if ((*result = websocket_client_connect(ws, options)) != WS_OK) {
2057 ao2_ref(ws, -1);
2058 SCOPE_EXIT_RTN_VALUE(NULL, "%s: Failed to connect: %s\n", options->uri, ast_websocket_result_to_str(*result));
2059 }
2060 ast_trace(-1, "%s: Connected\n", ws->client->options->uri);
2061
2062 if (ws->client->options->tcp_keepalives) {
2063 int sockfd = ast_iostream_get_fd(ws->stream);
2064 int enabled = 1;
2065
2066 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &enabled, sizeof(enabled));
2067 setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &options->tcp_keepalive_time, sizeof(options->tcp_keepalive_time));
2068 setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &options->tcp_keepalive_interval, sizeof(&options->tcp_keepalive_interval));
2069 setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, &options->tcp_keepalive_probes, sizeof(&options->tcp_keepalive_probes));
2070 ast_trace(-1, "%s: Enabled TCP keepalives\n", ws->client->options->uri);
2071 }
2072
2073 if (ws->client->options->pingpongs) {
2076 if (ws->client->ping_sched_timer < 0) {
2077 ast_log(LOG_WARNING, "%s: Unable to schedule PING/PONG keepalives\n", ws->client->options->uri);
2078 ao2_ref(ws, -1);
2079 } else {
2080 ast_trace(-1, "%s: Enabled PING/PONG keepalives\n", ws->client->options->uri);
2081 }
2082 }
2083 SCOPE_EXIT_RTN_VALUE(ws, "%s: Client created and connected %p %p\n", options->uri, ws, ws->client);
2084}
#define ast_log
Definition astobj2.c:42
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
Definition astobj2.h:459
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
Definition astobj2.h:480
static int enabled
Definition dnsmgr.c:91
#define SCOPE_EXIT_RTN_VALUE(__return_value,...)
#define SCOPE_EXIT_LOG_RTN_VALUE(__value, __log_level,...)
#define SCOPE_ENTER(level,...)
#define ast_trace(level,...)
#define LOG_ERROR
#define LOG_WARNING
int ast_iostream_get_fd(struct ast_iostream *stream)
Get an iostream's file descriptor.
Definition iostream.c:85
static int ping_scheduler_callback(const void *obj)
static struct ast_websocket * websocket_client_create(struct ast_websocket_client_options *options, enum ast_websocket_result *result)
static struct ast_sched_context * ping_scheduler
static enum ast_websocket_result websocket_client_connect(struct ast_websocket *ws, struct ast_websocket_client_options *options)
const char *AST_OPTIONAL_API_NAME() ast_websocket_result_to_str(enum ast_websocket_result result)
Convert a websocket result code to a string.
#define NULL
Definition resample.c:96
int ast_sched_add(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
Adds a scheduled event.
Definition sched.c:567
Structure definition for session.
struct ast_iostream * stream
struct ast_websocket_client_options * options

References ao2_bump, ao2_ref, ast_iostream_get_fd(), ast_log, ast_sched_add(), ast_trace, ast_websocket_result_to_str(), ast_websocket::client, enabled, LOG_ERROR, LOG_WARNING, NULL, websocket_client::options, options, websocket_client::ping_sched_timer, ping_scheduler, ping_scheduler_callback(), ast_websocket_client_options::pingpong_interval, ast_websocket_client_options::pingpongs, result, SCOPE_ENTER, SCOPE_EXIT_LOG_RTN_VALUE, SCOPE_EXIT_RTN_VALUE, ast_websocket::stream, ast_websocket_client_options::tcp_keepalives, ast_websocket_client_options::uri, websocket_client_connect(), websocket_client_create(), and WS_OK.

Referenced by ast_websocket_client_connect(), ast_websocket_client_create(), and websocket_connect().

◆ ast_websocket_close()

int AST_OPTIONAL_API_NAME() ast_websocket_close ( struct ast_websocket *  session,
uint16_t  reason 
)

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

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 559 of file res_http_websocket.c.

560{
561 if (session->closed_by == WS_NOT_CLOSED) {
562 session->closed_by = WS_CLOSED_BY_US;
563 }
564
565 return websocket_close(session, reason, 0);
566}
static struct ast_mansession session
static int websocket_close(struct ast_websocket *session, uint16_t reason, int force)
@ WS_NOT_CLOSED
@ WS_CLOSED_BY_US

References session, websocket_close(), WS_CLOSED_BY_US, and WS_NOT_CLOSED.

Referenced by ast_websocket_read(), incoming_ws_established_cb(), outbound_session_apply_config(), outbound_session_handler_thread(), outbound_session_pc_close_thread(), outbound_sessions_load(), session_destroy_fn(), session_shutdown_cb(), webchan_hangup(), websocket_disconnect(), websocket_established_cb(), and ws_shutdown().

◆ ast_websocket_fd()

int AST_OPTIONAL_API_NAME() 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 668 of file res_http_websocket.c.

669{
670 return session->closing ? -1 : ast_iostream_get_fd(session->stream);
671}

References ast_iostream_get_fd(), and session.

Referenced by session_read(), speech_test_server_cb(), websocket_echo_callback(), websocket_handoff_to_channel(), websocket_read(), and ws_shutdown().

◆ ast_websocket_is_secure()

int AST_OPTIONAL_API_NAME() 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 688 of file res_http_websocket.c.

689{
690 return session->secure;
691}

References session.

Referenced by transport_create().

◆ ast_websocket_local_address()

struct ast_sockaddr *AST_OPTIONAL_API_NAME() 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 683 of file res_http_websocket.c.

684{
685 return &session->local_address;
686}

References session.

Referenced by transport_create().

◆ ast_websocket_read()

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.

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 809 of file res_http_websocket.c.

810{
811 int fin = 0;
812 int mask_present = 0;
813 char *mask = NULL, *new_payload = NULL;
814 size_t options_len = 0, frame_size = 0;
815 SCOPE_ENTER(4, "%s: Reading\n", WS_SESSION_REMOTE(session));
816
817 *payload = NULL;
818 *payload_len = 0;
819 *fragmented = 0;
820
821 if (ws_safe_read(session, &session->buf[0], MIN_WS_HDR_SZ, opcode)) {
822 SCOPE_EXIT_RTN_VALUE(-1, "%s: Initial ws_safe_read failed\n", WS_SESSION_REMOTE(session));
823 }
825
826 /* 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) */
827 *opcode = session->buf[0] & 0xf;
828 *payload_len = session->buf[1] & 0x7f;
831 fin = (session->buf[0] >> 7) & 1;
832 mask_present = (session->buf[1] >> 7) & 1;
833
834 /* Based on the mask flag and payload length, determine how much more we need to read before start parsing the rest of the header */
835 options_len += mask_present ? 4 : 0;
836 options_len += (*payload_len == 126) ? 2 : (*payload_len == 127) ? 8 : 0;
837 if (options_len) {
838 /* read the rest of the header options */
839 if (ws_safe_read(session, &session->buf[frame_size], options_len, opcode)) {
840 SCOPE_EXIT_RTN_VALUE(-1, "%s: ws_safe_read of options failed\n", WS_SESSION_REMOTE(session));
841 }
842 frame_size += options_len;
843 }
844
845 if (*payload_len == 126) {
846 /* Grab the 2-byte payload length */
847 *payload_len = ntohs(get_unaligned_uint16(&session->buf[2]));
848 mask = &session->buf[4];
849 } else if (*payload_len == 127) {
850 /* Grab the 8-byte payload length */
851 *payload_len = ntohll(get_unaligned_uint64(&session->buf[2]));
852 mask = &session->buf[10];
853 } else {
854 /* Just set the mask after the small 2-byte header */
855 mask = &session->buf[2];
856 }
857
858 /* Now read the rest of the payload */
859 *payload = &session->buf[frame_size]; /* payload will start here, at the end of the options, if any */
860 frame_size = frame_size + (*payload_len); /* final frame size is header + optional headers + payload data */
862 /* The frame won't fit :-( */
864 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Cannot fit huge websocket frame of %zu bytes\n",
866 }
867
868 if (*payload_len) {
869 if (ws_safe_read(session, *payload, *payload_len, opcode)) {
870 SCOPE_EXIT_RTN_VALUE(-1, "%s: ws_safe_read of payload failed\n", WS_SESSION_REMOTE(session));
871 }
872 }
873
874 /* If a mask is present unmask the payload */
875 if (mask_present) {
876 unsigned int pos;
877 for (pos = 0; pos < *payload_len; pos++) {
878 (*payload)[pos] ^= mask[pos % 4];
879 }
880 }
881
882 /* Per the RFC for PING we need to send back an opcode with the application data as received */
883 if (*opcode == AST_WEBSOCKET_OPCODE_PING) {
884 if (ast_websocket_write(session, AST_WEBSOCKET_OPCODE_PONG, *payload, *payload_len)) {
886 }
887 *payload_len = 0;
888 SCOPE_EXIT_RTN_VALUE(0, "%s: PING received. Sent PONG\n", WS_SESSION_REMOTE(session));
889 }
890
891 if (*opcode == AST_WEBSOCKET_OPCODE_PONG || *opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
892 if (websocket_handled_pong_or_close(session, *payload, *payload_len, *opcode)) {
893 SCOPE_EXIT_RTN_VALUE(0, "%s: Handled PONG or CLOSE\n", WS_SESSION_REMOTE(session));
894 }
895 }
896
897 /* Below this point we are handling TEXT, BINARY or CONTINUATION opcodes */
898 if (*payload_len) {
899 if (!(new_payload = ast_realloc(session->payload, (session->payload_len + *payload_len)))) {
900 *payload_len = 0;
902 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Failed allocation: %p, %zu, %"PRIu64"\n",
903 WS_SESSION_REMOTE(session), session->payload, session->payload_len, *payload_len);
904 }
905
906 session->payload = new_payload;
907 memcpy((session->payload + session->payload_len), (*payload), (*payload_len));
908 session->payload_len += *payload_len;
909 } else if (!session->payload_len && session->payload) {
910 ast_free(session->payload);
911 session->payload = NULL;
912 }
913
914 if (!fin && session->reconstruct && (session->payload_len < session->reconstruct)) {
915 /* If this is not a final message we need to defer returning it until later */
916 if (*opcode != AST_WEBSOCKET_OPCODE_CONTINUATION) {
917 session->opcode = *opcode;
918 }
920 *payload_len = 0;
921 *payload = NULL;
922 } else {
923 if (*opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
924 if (!fin) {
925 /* If this was not actually the final message tell the user it is fragmented so they can deal with it accordingly */
926 *fragmented = 1;
927 } else {
928 /* Final frame in multi-frame so push up the actual opcode */
929 *opcode = session->opcode;
930 }
931 }
932 *payload_len = session->payload_len;
933 *payload = session->payload;
934 session->payload_len = 0;
935 }
936 } else {
937 ast_log(LOG_WARNING, "WebSocket unknown opcode %u\n", *opcode);
938 /* 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
939 * fit that, I think. */
941 }
942
943 SCOPE_EXIT_RTN_VALUE(0, "%s: Read complete. Opcode: %s Length: %"PRIu64"\n",
944 WS_SESSION_REMOTE(session), websocket_opcode2str(*opcode), *payload_len);
945}
uint64_t ntohll(uint64_t net64)
Definition strcompat.c:365
#define ast_free(a)
Definition astmm.h:180
#define ast_realloc(p, len)
A wrapper for realloc()
Definition astmm.h:226
static int frame_size[4]
Definition format_g726.c:52
#define AST_WEBSOCKET_MAX_RX_PAYLOAD_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)
static int websocket_handled_pong_or_close(struct ast_websocket *session, char *payload, uint64_t payload_len, enum ast_websocket_opcode opcode)
#define WS_SESSION_REMOTE(_session)
int AST_OPTIONAL_API_NAME() ast_websocket_close(struct ast_websocket *session, uint16_t reason)
Close function for websocket session.
static const char * websocket_opcode2str(enum ast_websocket_opcode opcode)
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_MAX_RX_PAYLOAD_SIZE, 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, MIN_WS_HDR_SZ, ntohll(), NULL, ast_websocket::opcode, ast_websocket::payload, ast_websocket::payload_len, SCOPE_ENTER, SCOPE_EXIT_LOG_RTN_VALUE, SCOPE_EXIT_RTN_VALUE, session, websocket_handled_pong_or_close(), websocket_opcode2str(), ws_safe_read(), and WS_SESSION_REMOTE.

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

◆ ast_websocket_read_string()

int AST_OPTIONAL_API_NAME() 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 2086 of file res_http_websocket.c.

2088{
2089 char *payload;
2090 uint64_t payload_len;
2091 enum ast_websocket_opcode opcode;
2092 int fragmented = 1;
2093
2094 while (fragmented) {
2095 if (ast_websocket_read(ws, &payload, &payload_len,
2096 &opcode, &fragmented)) {
2097 ast_log(LOG_ERROR, "Client WebSocket string read - "
2098 "error reading string data\n");
2099 return -1;
2100 }
2101
2102 if (opcode == AST_WEBSOCKET_OPCODE_PING) {
2103 /* Try read again, we have sent pong already */
2104 fragmented = 1;
2105 continue;
2106 }
2107
2108 if (opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
2109 continue;
2110 }
2111
2112 if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2113 return -1;
2114 }
2115
2116 if (opcode != AST_WEBSOCKET_OPCODE_TEXT) {
2117 ast_log(LOG_ERROR, "Client WebSocket string read - "
2118 "non string data received\n");
2119 return -1;
2120 }
2121 }
2122
2123 if (!(*buf = ast_strndup(payload, payload_len))) {
2124 return -1;
2125 }
2126
2127 return payload_len + 1;
2128}
#define ast_strndup(str, len)
A wrapper for strndup()
Definition astmm.h:256
char buf[BUFSIZE]
Definition eagi_proxy.c:66
ast_websocket_opcode
WebSocket operation codes.
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_OPTIONAL_API_NAME() 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 644 of file res_http_websocket.c.

645{
646 session->reconstruct = 0;
647}

References session.

◆ ast_websocket_reconstruct_enable()

void AST_OPTIONAL_API_NAME() ast_websocket_reconstruct_enable ( struct ast_websocket *  session,
size_t  bytes 
)

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

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 639 of file res_http_websocket.c.

640{
641 session->reconstruct = MIN(bytes, MAXIMUM_RECONSTRUCTION_CEILING);
642}
#define MAXIMUM_RECONSTRUCTION_CEILING
Maximum reconstruction size for multi-frame payload reconstruction.
#define MIN(a, b)
Definition utils.h:252

References MAXIMUM_RECONSTRUCTION_CEILING, MIN, and session.

Referenced by websocket_handoff_to_channel().

◆ ast_websocket_ref()

void AST_OPTIONAL_API_NAME() ast_websocket_ref ( struct ast_websocket *  session)

Increase the reference count for a WebSocket session.

Parameters
sessionPointer to the WebSocket session

Definition at line 649 of file res_http_websocket.c.

650{
652 int refcount = session ? ao2_ref(session, 0) : 0;
653 SCOPE_ENTER(2, "%s: Reffing. Refcount: %d\n", id, refcount);
654 ao2_ref(session, +1);
655 SCOPE_EXIT("%s: Reffed. Refcount: %d\n", id, session ? refcount - 1 : 0);
656}
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition astmm.h:298
#define SCOPE_EXIT(...)

References ao2_ref, ast_strdupa, SCOPE_ENTER, SCOPE_EXIT, session, and WS_SESSION_REMOTE.

Referenced by session_update(), and transport_create().

◆ ast_websocket_remote_address()

struct ast_sockaddr *AST_OPTIONAL_API_NAME() ast_websocket_remote_address ( struct ast_websocket *  session)

Get the remote address for a WebSocket connected session.

Returns
Remote address

Definition at line 678 of file res_http_websocket.c.

679{
680 return &session->remote_address;
681}

References session.

Referenced by ari_websocket_send_event(), session_update(), session_write(), transport_create(), transport_read(), websocket_established_cb(), and websocket_handoff_to_channel().

◆ ast_websocket_remove_protocol()

int AST_OPTIONAL_API_NAME() 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 1281 of file res_http_websocket.c.

1282{
1284}
static int websocket_remove_protocol_internal(const char *name, ast_websocket_callback callback)

References callback(), name, and websocket_remove_protocol_internal().

Referenced by AST_TEST_DEFINE(), and unload_module().

◆ ast_websocket_result_to_str()

const char *AST_OPTIONAL_API_NAME() ast_websocket_result_to_str ( enum ast_websocket_result  result)

Convert a websocket result code to a string.

Parameters
resultThe result code to convert
Returns
A string representation of the result code

Definition at line 2166 of file res_http_websocket.c.

2168{
2170 return "unknown";
2171 }
2173}
const char * websocket_result_string_map[]
#define ARRAY_IN_BOUNDS(v, a)
Checks to see if value is within the bounds of the given array.
Definition utils.h:727

References ARRAY_IN_BOUNDS, result, and websocket_result_string_map.

Referenced by ast_websocket_client_connect(), ast_websocket_client_create_with_options(), webchan_call(), websocket_client_handshake(), websocket_client_handshake_get_response(), and websocket_proxy_handshake().

◆ ast_websocket_server_add_protocol()

int AST_OPTIONAL_API_NAME() 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 297 of file res_http_websocket.c.

298{
299 struct ast_websocket_protocol *protocol;
300
301 if (!server->protocols) {
302 return -1;
303 }
304
306 if (!protocol) {
307 return -1;
308 }
309 protocol->session_established = callback;
310
311 if (ast_websocket_server_add_protocol2(server, protocol)) {
312 ao2_ref(protocol, -1);
313 return -1;
314 }
315
316 return 0;
317}
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(), callback(), name, ast_websocket_server::protocols, and ast_websocket_protocol::session_established.

Referenced by websocket_add_protocol_internal().

◆ ast_websocket_server_add_protocol2()

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.

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 319 of file res_http_websocket.c.

320{
321 struct ast_websocket_protocol *existing;
322
323 if (!server->protocols) {
324 return -1;
325 }
326
327 if (protocol->version != AST_WEBSOCKET_PROTOCOL_VERSION) {
328 ast_log(LOG_WARNING, "WebSocket could not register sub-protocol '%s': "
329 "expected version '%u', got version '%u'\n",
330 protocol->name, AST_WEBSOCKET_PROTOCOL_VERSION, protocol->version);
331 return -1;
332 }
333
334 ao2_lock(server->protocols);
335
336 /* Ensure a second protocol handler is not registered for the same protocol */
337 existing = ao2_find(server->protocols, protocol->name, OBJ_KEY | OBJ_NOLOCK);
338 if (existing) {
339 ao2_ref(existing, -1);
340 ao2_unlock(server->protocols);
341 return -1;
342 }
343
344 ao2_link_flags(server->protocols, protocol, OBJ_NOLOCK);
345 ao2_unlock(server->protocols);
346
347 ast_debug(1, "WebSocket registered sub-protocol '%s'\n", protocol->name);
348 ao2_ref(protocol, -1);
349
350 return 0;
351}
#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
#define ao2_unlock(a)
Definition astobj2.h:729
#define ao2_lock(a)
Definition astobj2.h:717
@ 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...
#define ast_debug(level,...)
Log a DEBUG message.
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_debug, ast_log, AST_WEBSOCKET_PROTOCOL_VERSION, LOG_WARNING, OBJ_KEY, OBJ_NOLOCK, and ast_websocket_server::protocols.

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

◆ ast_websocket_server_create()

struct ast_websocket_server *AST_OPTIONAL_API_NAME() 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 252 of file res_http_websocket.c.

253{
255}
static struct ast_websocket_server * websocket_server_create_impl(void)

References websocket_server_create_impl().

Referenced by ari_websocket_load_module(), and load_module().

◆ ast_websocket_server_remove_protocol()

int AST_OPTIONAL_API_NAME() 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 353 of file res_http_websocket.c.

354{
355 struct ast_websocket_protocol *protocol;
356
357 if (!(protocol = ao2_find(server->protocols, name, OBJ_KEY))) {
358 return -1;
359 }
360
361 if (protocol->session_established != callback) {
362 ao2_ref(protocol, -1);
363 return -1;
364 }
365
366 ao2_unlink(server->protocols, protocol);
367 ao2_ref(protocol, -1);
368
369 ast_debug(1, "WebSocket unregistered sub-protocol '%s'\n", name);
370
371 return 0;
372}
#define ao2_unlink(container, obj)
Remove an object from a container.
Definition astobj2.h:1578

References ao2_find, ao2_ref, ao2_unlink, ast_debug, callback(), 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_OPTIONAL_API_NAME() ast_websocket_session_id ( struct ast_websocket *  session)

Get the session ID for a WebSocket session.

Returns
session id

Definition at line 707 of file res_http_websocket.c.

708{
709 return session->session_id;
710}

References session.

Referenced by websocket_established_cb().

◆ ast_websocket_set_nonblock()

int AST_OPTIONAL_API_NAME() 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 693 of file res_http_websocket.c.

694{
697 return 0;
698}
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:154
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 session_update(), websocket_cb(), and websocket_handoff_to_channel().

◆ ast_websocket_set_timeout()

int AST_OPTIONAL_API_NAME() 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
Warning
To be effective, the socket must be in non-blocking mode because the timeout can only be checked after a read or write operation returns. If the socket is in blocking mode (the default), those calls may block for longer than the specified timeout, possibly much longer.
Return values
0on success
-1on failure

Definition at line 700 of file res_http_websocket.c.

701{
702 session->timeout = timeout;
703
704 return 0;
705}

References session, and ast_websocket::timeout.

Referenced by incoming_ws_established_cb(), outbound_session_handler_thread(), webchan_call(), websocket_cb(), and websocket_established_cb().

◆ ast_websocket_status_to_str()

const char *AST_OPTIONAL_API_NAME() ast_websocket_status_to_str ( enum ast_websocket_status_code  code)

Convert a websocket status code to a string.

Parameters
codeThe code to convert
Returns
A string representation of the code

Definition at line 2199 of file res_http_websocket.c.

2201{
2202 int i;
2203
2204 for (i = 0; i < ARRAY_LEN(websocket_status_map); i++) {
2205 if (websocket_status_map[i].code == code)
2206 return websocket_status_map[i].desc;
2207 }
2208
2209 return "Unknown";
2210}
static const struct status_map websocket_status_map[]
const char * desc
#define ARRAY_LEN(a)
Definition utils.h:706

References ARRAY_LEN, status_map::code, status_map::desc, and websocket_status_map.

Referenced by _websocket_request_hangup(), websocket_close(), and websocket_handled_pong_or_close().

◆ ast_websocket_sub_protocol_alloc()

struct ast_websocket_protocol *AST_OPTIONAL_API_NAME() 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 278 of file res_http_websocket.c.

279{
280 struct ast_websocket_protocol *protocol;
281
282 protocol = ao2_alloc(sizeof(*protocol), protocol_destroy_fn);
283 if (!protocol) {
284 return NULL;
285 }
286
287 protocol->name = ast_strdup(name);
288 if (!protocol->name) {
289 ao2_ref(protocol, -1);
290 return NULL;
291 }
293
294 return protocol;
295}
#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 ari_websocket_load_module(), ast_websocket_server_add_protocol(), and load_module().

◆ ast_websocket_type_to_str()

const char * ast_websocket_type_to_str ( enum ast_websocket_type  type)

Definition at line 169 of file res_http_websocket.c.

170{
171 switch (type) {
173 return "persistent";
175 return "per_call";
177 return "per_call_config";
179 return "client";
181 return "inbound";
183 return "server";
184 case AST_WS_TYPE_ANY:
185 return "any";
186 default:
187 return "unknown";
188 }
189}
static const char type[]

References AST_WS_TYPE_ANY, AST_WS_TYPE_CLIENT, AST_WS_TYPE_CLIENT_PER_CALL, AST_WS_TYPE_CLIENT_PER_CALL_CONFIG, AST_WS_TYPE_CLIENT_PERSISTENT, AST_WS_TYPE_INBOUND, AST_WS_TYPE_SERVER, and type.

Referenced by session_cleanup().

◆ ast_websocket_unref()

void AST_OPTIONAL_API_NAME() ast_websocket_unref ( struct ast_websocket *  session)

Decrease the reference count for a WebSocket session.

Parameters
sessionPointer to the WebSocket session

Definition at line 658 of file res_http_websocket.c.

659{
661 int refcount = session ? ao2_ref(session, 0) : 0;
662 SCOPE_ENTER(2, "%s: Unreffing. Refcount: %d\n", id, refcount);
663
665 SCOPE_EXIT("%s: Unreffed. Refcount: %d\n", id, session ? refcount - 1 : 0);
666}
#define ao2_cleanup(obj)
Definition astobj2.h:1934

References ao2_cleanup, ao2_ref, ast_strdupa, SCOPE_ENTER, SCOPE_EXIT, session, and WS_SESSION_REMOTE.

Referenced by incoming_ws_established_cb(), outbound_session_handler_thread(), session_dtor(), speech_test_server_cb(), transport_dtor(), webchan_hangup(), websocket_cb(), websocket_destroy(), websocket_destructor(), websocket_echo_callback(), and websocket_established_cb().

◆ ast_websocket_uri_cb()

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

Callback suitable for use with a ast_http_uri.

Set the data field of the ast_http_uri to ast_websocket_server.

Since
12

Definition at line 988 of file res_http_websocket.c.

989{
990 struct ast_variable *v;
991 const char *upgrade = NULL, *key = NULL, *key1 = NULL, *key2 = NULL, *protos = NULL;
992 char *requested_protocols = NULL, *protocol = NULL;
993 int version = 0, flags = 1;
994 struct ast_websocket_protocol *protocol_handler = NULL;
995 struct ast_websocket *session;
996 struct ast_websocket_server *server;
997
999
1000 /* Upgrade requests are only permitted on GET methods */
1001 if (method != AST_HTTP_GET) {
1002 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
1003 return 0;
1004 }
1005
1006 server = urih->data;
1007
1008 /* Get the minimum headers required to satisfy our needs */
1009 for (v = headers; v; v = v->next) {
1010 if (!strcasecmp(v->name, "Upgrade")) {
1011 upgrade = v->value;
1012 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key")) {
1013 key = v->value;
1014 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key1")) {
1015 key1 = v->value;
1016 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key2")) {
1017 key2 = v->value;
1018 } else if (!strcasecmp(v->name, "Sec-WebSocket-Protocol")) {
1019 protos = v->value;
1020 } else if (!strcasecmp(v->name, "Sec-WebSocket-Version")) {
1021 if (sscanf(v->value, "%30d", &version) != 1) {
1022 version = 0;
1023 }
1024 }
1025 }
1026
1027 /* If this is not a websocket upgrade abort */
1028 if (!upgrade || strcasecmp(upgrade, "websocket")) {
1029 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - did not request WebSocket\n",
1031 ast_http_error(ser, 426, "Upgrade Required", NULL);
1032 return 0;
1033 } else if (ast_strlen_zero(protos)) {
1034 /* If there's only a single protocol registered, and the
1035 * client doesn't specify what protocol it's using, go ahead
1036 * and accept the connection */
1037 protocol_handler = one_protocol(server);
1038 if (!protocol_handler) {
1039 /* Multiple registered subprotocols; client must specify */
1040 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols requested\n",
1043 return 0;
1044 }
1045 } else if (key1 && key2) {
1046 /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 and
1047 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 -- not currently supported*/
1048 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '00/76' chosen\n",
1051 return 0;
1052 }
1053
1054 if (!protocol_handler && protos) {
1055 requested_protocols = ast_strdupa(protos);
1056 /* Iterate through the requested protocols trying to find one that we have a handler for */
1057 while (!protocol_handler && (protocol = strsep(&requested_protocols, ","))) {
1058 protocol_handler = ao2_find(server->protocols, ast_strip(protocol), OBJ_KEY);
1059 }
1060 }
1061
1062 /* If no protocol handler exists bump this back to the requester */
1063 if (!protocol_handler) {
1064 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols out of '%s' supported\n",
1065 ast_sockaddr_stringify(&ser->remote_address), protos);
1067 return 0;
1068 }
1069
1070 /* Determine how to respond depending on the version */
1071 if (version == 7 || version == 8 || version == 13) {
1072 char base64[64];
1073
1074 if (!key || strlen(key) + strlen(WEBSOCKET_GUID) + 1 > 8192) { /* no stack overflows please */
1076 ao2_ref(protocol_handler, -1);
1077 return 0;
1078 }
1079
1080 if (ast_http_body_discard(ser)) {
1082 ao2_ref(protocol_handler, -1);
1083 return 0;
1084 }
1085
1086 if (!(session = ao2_alloc(sizeof(*session) + AST_UUID_STR_LEN + 1, session_destroy_fn))) {
1087 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted\n",
1090 ao2_ref(protocol_handler, -1);
1091 return 0;
1092 }
1094
1095 /* Generate the session id */
1096 if (!ast_uuid_generate_str(session->session_id, sizeof(session->session_id))) {
1097 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to generate a session id\n",
1099 ast_http_error(ser, 500, "Internal Server Error", "Allocation failed");
1100 ao2_ref(session, -1);
1101 ao2_ref(protocol_handler, -1);
1102 return 0;
1103 }
1104
1105 if (protocol_handler->session_attempted
1106 && protocol_handler->session_attempted(ser, get_vars, headers, session->session_id)) {
1107 ast_debug(3, "WebSocket connection from '%s' rejected by protocol handler '%s'\n",
1108 ast_sockaddr_stringify(&ser->remote_address), protocol_handler->name);
1110 ao2_ref(session, -1);
1111 ao2_ref(protocol_handler, -1);
1112 return 0;
1113 }
1114
1115 /* RFC 6455, Section 4.1:
1116 *
1117 * 6. If the response includes a |Sec-WebSocket-Protocol| header
1118 * field and this header field indicates the use of a
1119 * subprotocol that was not present in the client's handshake
1120 * (the server has indicated a subprotocol not requested by
1121 * the client), the client MUST _Fail the WebSocket
1122 * Connection_.
1123 */
1124 if (protocol) {
1126 "HTTP/1.1 101 Switching Protocols\r\n"
1127 "Upgrade: %s\r\n"
1128 "Connection: Upgrade\r\n"
1129 "Sec-WebSocket-Accept: %s\r\n"
1130 "Sec-WebSocket-Protocol: %s\r\n\r\n",
1131 upgrade,
1132 websocket_combine_key(key, base64, sizeof(base64)),
1133 protocol);
1134 } else {
1136 "HTTP/1.1 101 Switching Protocols\r\n"
1137 "Upgrade: %s\r\n"
1138 "Connection: Upgrade\r\n"
1139 "Sec-WebSocket-Accept: %s\r\n\r\n",
1140 upgrade,
1141 websocket_combine_key(key, base64, sizeof(base64)));
1142 }
1143 } else {
1144
1145 /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 or completely unknown */
1146 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '%d' chosen\n",
1149 ao2_ref(protocol_handler, -1);
1150 return 0;
1151 }
1152
1153 /* Enable keepalive on all sessions so the underlying user does not have to */
1154 if (setsockopt(ast_iostream_get_fd(ser->stream), SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
1155 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to enable keepalive\n",
1158 ao2_ref(session, -1);
1159 ao2_ref(protocol_handler, -1);
1160 return 0;
1161 }
1162
1163 /* Get our local address for the connected socket */
1164 if (ast_getsockname(ast_iostream_get_fd(ser->stream), &session->local_address)) {
1165 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to get local address\n",
1168 ao2_ref(session, -1);
1169 ao2_ref(protocol_handler, -1);
1170 return 0;
1171 }
1172
1173 ast_debug(3, "WebSocket connection from '%s' for protocol '%s' accepted using version '%d'\n", ast_sockaddr_stringify(&ser->remote_address), protocol ? : "", version);
1174
1175 /* Populate the session with all the needed details */
1176 session->stream = ser->stream;
1177 ast_sockaddr_copy(&session->remote_address, &ser->remote_address);
1178 session->opcode = -1;
1180 session->secure = ast_iostream_get_ssl(ser->stream) ? 1 : 0;
1181
1182 /* Give up ownership of the socket and pass it to the protocol handler */
1184 protocol_handler->session_established(session, get_vars, headers);
1185 ao2_ref(protocol_handler, -1);
1186
1187 /*
1188 * By dropping the stream from the session the connection
1189 * won't get closed when the HTTP server cleans up because we
1190 * passed the connection to the protocol handler.
1191 */
1192 ser->stream = NULL;
1193
1194 return 0;
1195}
char * strsep(char **str, const char *delims)
static char version[AST_MAX_EXTENSION]
@ 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:1193
void ast_http_error(struct ast_tcptls_session_instance *ser, int status, const char *title, const char *text)
Send HTTP error message and close socket.
Definition http.c:722
ssize_t ast_iostream_printf(struct ast_iostream *stream, const char *format,...)
Write a formatted string to an iostream.
Definition iostream.c:507
SSL * ast_iostream_get_ssl(struct ast_iostream *stream)
Get a pointer to an iostream's OpenSSL SSL structure.
Definition iostream.c:114
#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 char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
Definition netsock2.h:256
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:1277
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:162
struct ast_sockaddr remote_address
Definition tcptls.h:153
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, 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(), ast_variable::value, version, websocket_bad_request(), websocket_combine_key(), and WEBSOCKET_GUID.

Referenced by ari_handle_websocket(), and incoming_ws_http_callback().

◆ ast_websocket_wait_for_input()

int AST_OPTIONAL_API_NAME() 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 673 of file res_http_websocket.c.

674{
675 return session->closing ? -1 : ast_iostream_wait_for_input(session->stream, timeout);
676}
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_OPTIONAL_API_NAME() ast_websocket_write ( struct ast_websocket *  session,
enum ast_websocket_opcode  opcode,
char *  payload,
uint64_t  payload_size 
)

Construct and transmit a WebSocket frame.

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 569 of file res_http_websocket.c.

571{
572 size_t header_size = 2; /* The minimum size of a websocket frame is 2 bytes */
573 char *frame;
574 uint64_t length;
575 uint64_t frame_size;
576 SCOPE_ENTER(4, "%s: Opcode: %s Length: %"PRIu64"\n",
577 WS_SESSION_REMOTE(session), websocket_opcode2str(opcode), payload_size);
578
579 if (payload_size < 126) {
580 length = payload_size;
581 } else if (payload_size < (1 << 16)) {
582 length = 126;
583 /* We need an additional 2 bytes to store the extended length */
584 header_size += 2;
585 } else {
586 length = 127;
587 /* We need an additional 8 bytes to store the really really extended length */
588 header_size += 8;
589 }
590
591 if (session->client) {
592 /* Additional 4 bytes for the client masking key */
593 header_size += 4;
594 }
595
596 frame_size = header_size + payload_size;
597
598 frame = ast_alloca(frame_size + 1);
599 memset(frame, 0, frame_size + 1);
600
601 frame[0] = opcode | 0x80;
602 frame[1] = length;
603
604 /* Use the additional available bytes to store the length */
605 if (length == 126) {
606 put_unaligned_uint16(&frame[2], htons(payload_size));
607 } else if (length == 127) {
608 put_unaligned_uint64(&frame[2], htonll(payload_size));
609 }
610
611 memcpy(&frame[header_size], payload, payload_size);
612
613 websocket_mask_payload(session, frame, &frame[header_size], payload_size);
614
616 if (session->closing) {
618 SCOPE_EXIT_RTN_VALUE(-1, "%s: Websocket already closing\n", WS_SESSION_REMOTE(session));
619 }
620
622 if (ast_iostream_write(session->stream, frame, frame_size) != frame_size) {
624 /* 1011 - server terminating connection due to not being able to fulfill the request */
625 ast_trace(-1, "%s: Closing WS with 1011 because we can't fulfill a write request\n",
627 websocket_close(session, 1011, 1);
628 SCOPE_EXIT_RTN_VALUE(-1, "%s: Closed WS with 1011 because we couldn't fulfill a write request\n",
630 }
631
634
635 SCOPE_EXIT_RTN_VALUE(0, "%s: Wrote opcode: %s length: %"PRIu64"\n",
636 WS_SESSION_REMOTE(session), websocket_opcode2str(opcode), payload_size);
637}
uint64_t htonll(uint64_t host64)
Definition strcompat.c:391
#define ast_alloca(size)
call __builtin_alloca to ensure we get gcc builtin semantics
Definition astmm.h:288
ssize_t ast_iostream_write(struct ast_iostream *stream, const void *buffer, size_t count)
Write data to an iostream.
Definition iostream.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:145
void ast_iostream_set_timeout_disable(struct ast_iostream *stream)
Disable the iostream timeout timer.
Definition iostream.c:119
static void websocket_mask_payload(struct ast_websocket *session, char *frame, char *payload, uint64_t payload_size)
Perform payload masking for client sessions.
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition time.h:159
static void put_unaligned_uint16(void *p, unsigned short datum)
Definition unaligned.h:65
static void put_unaligned_uint64(void *p, uint64_t datum)
Definition unaligned.h:51

References ao2_lock, ao2_unlock, ast_alloca, ast_iostream_set_timeout_disable(), ast_iostream_set_timeout_sequence(), ast_iostream_write(), ast_trace, ast_tvnow(), frame_size, htonll(), ast_websocket::opcode, ast_websocket::payload, put_unaligned_uint16(), put_unaligned_uint64(), SCOPE_ENTER, SCOPE_EXIT_RTN_VALUE, session, websocket_close(), websocket_mask_payload(), websocket_opcode2str(), and WS_SESSION_REMOTE.

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

◆ ast_websocket_write_string()

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

Construct and transmit a WebSocket frame containing string data.

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

Definition at line 2130 of file res_http_websocket.c.

2132{
2133 uint64_t len = strlen(buf);
2134
2135 ast_debug(3, "Writing websocket string of length %" PRIu64 "\n", len);
2136
2137 /* We do not pass strlen(buf) to ast_websocket_write() directly because the
2138 * size_t returned by strlen() may not require the same storage size
2139 * as the uint64_t that ast_websocket_write() uses. This normally
2140 * would not cause a problem, but since ast_websocket_write() uses
2141 * the optional API, this function call goes through a series of macros
2142 * that may cause a 32-bit to 64-bit conversion to go awry.
2143 */
2145 (char *)buf, len);
2146}
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_TEST_DEFINE(), dequeue_frame(), session_write(), and speech_test_server_handle_request().