2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2012, Digium, Inc.
6 * Joshua Colp <jcolp@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief WebSocket support for the Asterisk internal HTTP server
23 * \author Joshua Colp <jcolp@digium.com>
27 <support_level>extended</support_level>
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include "asterisk/module.h"
35 #include "asterisk/http.h"
36 #include "asterisk/astobj2.h"
37 #include "asterisk/strings.h"
38 #include "asterisk/file.h"
39 #include "asterisk/unaligned.h"
41 #define AST_API_MODULE
42 #include "asterisk/http_websocket.h"
44 /*! \brief GUID used to compute the accept key, defined in the specifications */
45 #define WEBSOCKET_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
47 /*! \brief Number of buckets for registered protocols */
48 #define MAX_PROTOCOL_BUCKETS 7
50 /*! \brief Size of the pre-determined buffer for WebSocket frames */
51 #define MAXIMUM_FRAME_SIZE 8192
53 /*! \brief Default reconstruction size for multi-frame payload reconstruction. If exceeded the next frame will start a
56 #define DEFAULT_RECONSTRUCTION_CEILING 16384
58 /*! \brief Maximum reconstruction size for multi-frame payload reconstruction. */
59 #define MAXIMUM_RECONSTRUCTION_CEILING 16384
61 /*! \brief Structure definition for session */
62 struct ast_websocket {
63 FILE *f; /*!< Pointer to the file instance used for writing and reading */
64 int fd; /*!< File descriptor for the session, only used for polling */
65 struct ast_sockaddr address; /*!< Address of the remote client */
66 enum ast_websocket_opcode opcode; /*!< Cached opcode for multi-frame messages */
67 size_t payload_len; /*!< Length of the payload */
68 char *payload; /*!< Pointer to the payload */
69 size_t reconstruct; /*!< Number of bytes before a reconstructed payload will be returned and a new one started */
70 unsigned int secure:1; /*!< Bit to indicate that the transport is secure */
71 unsigned int closing:1; /*!< Bit to indicate that the session is in the process of being closed */
74 /*! \brief Structure definition for protocols */
75 struct websocket_protocol {
76 char *name; /*!< Name of the protocol */
77 ast_websocket_callback callback; /*!< Callback called when a new session is established */
80 /*! \brief Hashing function for protocols */
81 static int protocol_hash_fn(const void *obj, const int flags)
83 const struct websocket_protocol *protocol = obj;
84 const char *name = obj;
86 return ast_str_case_hash(flags & OBJ_KEY ? name : protocol->name);
89 /*! \brief Comparison function for protocols */
90 static int protocol_cmp_fn(void *obj, void *arg, int flags)
92 const struct websocket_protocol *protocol1 = obj, *protocol2 = arg;
93 const char *protocol = arg;
95 return !strcasecmp(protocol1->name, flags & OBJ_KEY ? protocol : protocol2->name) ? CMP_MATCH | CMP_STOP : 0;
98 /*! \brief Destructor function for protocols */
99 static void protocol_destroy_fn(void *obj)
101 struct websocket_protocol *protocol = obj;
102 ast_free(protocol->name);
105 /*! \brief Structure for a WebSocket server */
106 struct ast_websocket_server {
107 struct ao2_container *protocols; /*!< Container for registered protocols */
110 static void websocket_server_dtor(void *obj)
112 struct ast_websocket_server *server = obj;
113 ao2_cleanup(server->protocols);
114 server->protocols = NULL;
117 struct ast_websocket_server *ast_websocket_server_create(void)
119 RAII_VAR(struct ast_websocket_server *, server, NULL, ao2_cleanup);
121 server = ao2_alloc(sizeof(*server), websocket_server_dtor);
126 server->protocols = ao2_container_alloc(MAX_PROTOCOL_BUCKETS, protocol_hash_fn, protocol_cmp_fn);
127 if (!server->protocols) {
135 /*! \brief Destructor function for sessions */
136 static void session_destroy_fn(void *obj)
138 struct ast_websocket *session = obj;
142 ast_verb(2, "WebSocket connection from '%s' closed\n", ast_sockaddr_stringify(&session->address));
145 ast_free(session->payload);
148 int AST_OPTIONAL_API_NAME(ast_websocket_server_add_protocol)(struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
150 struct websocket_protocol *protocol;
152 if (!server->protocols) {
156 ao2_lock(server->protocols);
158 /* Ensure a second protocol handler is not registered for the same protocol */
159 if ((protocol = ao2_find(server->protocols, name, OBJ_KEY | OBJ_NOLOCK))) {
160 ao2_ref(protocol, -1);
161 ao2_unlock(server->protocols);
165 if (!(protocol = ao2_alloc(sizeof(*protocol), protocol_destroy_fn))) {
166 ao2_unlock(server->protocols);
170 if (!(protocol->name = ast_strdup(name))) {
171 ao2_ref(protocol, -1);
172 ao2_unlock(server->protocols);
176 protocol->callback = callback;
178 ao2_link_flags(server->protocols, protocol, OBJ_NOLOCK);
179 ao2_unlock(server->protocols);
180 ao2_ref(protocol, -1);
182 ast_verb(2, "WebSocket registered sub-protocol '%s'\n", name);
187 int AST_OPTIONAL_API_NAME(ast_websocket_server_remove_protocol)(struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
189 struct websocket_protocol *protocol;
191 if (!(protocol = ao2_find(server->protocols, name, OBJ_KEY))) {
195 if (protocol->callback != callback) {
196 ao2_ref(protocol, -1);
200 ao2_unlink(server->protocols, protocol);
201 ao2_ref(protocol, -1);
203 ast_verb(2, "WebSocket unregistered sub-protocol '%s'\n", name);
208 /*! \brief Close function for websocket session */
209 int AST_OPTIONAL_API_NAME(ast_websocket_close)(struct ast_websocket *session, uint16_t reason)
211 char frame[4] = { 0, }; /* The header is 2 bytes and the reason code takes up another 2 bytes */
213 frame[0] = AST_WEBSOCKET_OPCODE_CLOSE | 0x80;
214 frame[1] = 2; /* The reason code is always 2 bytes */
216 /* If no reason has been specified assume 1000 which is normal closure */
217 put_unaligned_uint16(&frame[2], htons(reason ? reason : 1000));
219 session->closing = 1;
221 return (fwrite(frame, 1, 4, session->f) == 4) ? 0 : -1;
225 /*! \brief Write function for websocket traffic */
226 int AST_OPTIONAL_API_NAME(ast_websocket_write)(struct ast_websocket *session, enum ast_websocket_opcode opcode, char *payload, uint64_t actual_length)
228 size_t header_size = 2; /* The minimum size of a websocket frame is 2 bytes */
232 if (actual_length < 126) {
233 length = actual_length;
234 } else if (actual_length < (1 << 16)) {
236 /* We need an additional 2 bytes to store the extended length */
240 /* We need an additional 8 bytes to store the really really extended length */
244 frame = ast_alloca(header_size);
245 memset(frame, 0, sizeof(*frame));
247 frame[0] = opcode | 0x80;
250 /* Use the additional available bytes to store the length */
252 put_unaligned_uint16(&frame[2], htons(actual_length));
253 } else if (length == 127) {
254 put_unaligned_uint64(&frame[2], htonl(actual_length));
257 if (fwrite(frame, 1, header_size, session->f) != header_size) {
261 if (fwrite(payload, 1, actual_length, session->f) != actual_length) {
268 void AST_OPTIONAL_API_NAME(ast_websocket_reconstruct_enable)(struct ast_websocket *session, size_t bytes)
270 session->reconstruct = MIN(bytes, MAXIMUM_RECONSTRUCTION_CEILING);
273 void AST_OPTIONAL_API_NAME(ast_websocket_reconstruct_disable)(struct ast_websocket *session)
275 session->reconstruct = 0;
278 void AST_OPTIONAL_API_NAME(ast_websocket_ref)(struct ast_websocket *session)
280 ao2_ref(session, +1);
283 void AST_OPTIONAL_API_NAME(ast_websocket_unref)(struct ast_websocket *session)
285 ao2_ref(session, -1);
288 int AST_OPTIONAL_API_NAME(ast_websocket_fd)(struct ast_websocket *session)
290 return session->closing ? -1 : session->fd;
293 struct ast_sockaddr * AST_OPTIONAL_API_NAME(ast_websocket_remote_address)(struct ast_websocket *session)
295 return &session->address;
298 int AST_OPTIONAL_API_NAME(ast_websocket_is_secure)(struct ast_websocket *session)
300 return session->secure;
303 int AST_OPTIONAL_API_NAME(ast_websocket_set_nonblock)(struct ast_websocket *session)
307 if ((flags = fcntl(session->fd, F_GETFL)) == -1) {
313 if ((flags = fcntl(session->fd, F_SETFL, flags)) == -1) {
320 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)
322 char buf[MAXIMUM_FRAME_SIZE] = "";
323 size_t frame_size, expected = 2;
329 /* We try to read in 14 bytes, which is the largest possible WebSocket header */
330 if ((frame_size = fread(&buf, 1, 14, session->f)) < 1) {
334 /* The minimum size for a WebSocket frame is 2 bytes */
335 if (frame_size < expected) {
339 *opcode = buf[0] & 0xf;
341 if (*opcode == AST_WEBSOCKET_OPCODE_TEXT || *opcode == AST_WEBSOCKET_OPCODE_BINARY || *opcode == AST_WEBSOCKET_OPCODE_CONTINUATION ||
342 *opcode == AST_WEBSOCKET_OPCODE_PING || *opcode == AST_WEBSOCKET_OPCODE_PONG) {
343 int fin = (buf[0] >> 7) & 1;
344 int mask_present = (buf[1] >> 7) & 1;
345 char *mask = NULL, *new_payload;
349 /* The mask should take up 4 bytes */
352 if (frame_size < expected) {
353 /* Per the RFC 1009 means we received a message that was too large for us to process */
354 ast_websocket_close(session, 1009);
359 /* Assume no extended length and no masking at the beginning */
360 *payload_len = buf[1] & 0x7f;
363 /* Determine if extended length is being used */
364 if (*payload_len == 126) {
365 /* Use the next 2 bytes to get a uint16_t */
369 if (frame_size < expected) {
370 ast_websocket_close(session, 1009);
374 *payload_len = ntohs(get_unaligned_uint16(&buf[2]));
375 } else if (*payload_len == 127) {
376 /* Use the next 8 bytes to get a uint64_t */
380 if (frame_size < expected) {
381 ast_websocket_close(session, 1009);
385 *payload_len = ntohl(get_unaligned_uint64(&buf[2]));
388 /* If masking is present the payload currently points to the mask, so move it over 4 bytes to the actual payload */
394 /* Determine how much payload we need to read in as we may have already read some in */
395 remaining = *payload_len - (frame_size - expected);
397 /* If how much payload they want us to read in exceeds what we are capable of close the session, things
398 * will fail no matter what most likely */
399 if (remaining > (MAXIMUM_FRAME_SIZE - frame_size)) {
400 ast_websocket_close(session, 1009);
404 new_payload = *payload + (frame_size - expected);
406 /* Read in the remaining payload */
407 while (remaining > 0) {
410 /* Wait for data to come in */
411 if (ast_wait_for_input(session->fd, -1) <= 0) {
412 *opcode = AST_WEBSOCKET_OPCODE_CLOSE;
414 session->closing = 1;
418 /* If some sort of failure occurs notify the caller */
419 if ((payload_read = fread(new_payload, 1, remaining, session->f)) < 1) {
423 remaining -= payload_read;
424 new_payload += payload_read;
427 /* If a mask is present unmask the payload */
430 for (pos = 0; pos < *payload_len; pos++) {
431 (*payload)[pos] ^= mask[pos % 4];
435 if (!(new_payload = ast_realloc(session->payload, session->payload_len + *payload_len))) {
437 ast_websocket_close(session, 1009);
441 /* Per the RFC for PING we need to send back an opcode with the application data as received */
442 if (*opcode == AST_WEBSOCKET_OPCODE_PING) {
443 ast_websocket_write(session, AST_WEBSOCKET_OPCODE_PONG, *payload, *payload_len);
446 session->payload = new_payload;
447 memcpy(session->payload + session->payload_len, *payload, *payload_len);
448 session->payload_len += *payload_len;
450 if (!fin && session->reconstruct && (session->payload_len < session->reconstruct)) {
451 /* If this is not a final message we need to defer returning it until later */
452 if (*opcode != AST_WEBSOCKET_OPCODE_CONTINUATION) {
453 session->opcode = *opcode;
455 *opcode = AST_WEBSOCKET_OPCODE_CONTINUATION;
459 if (*opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
461 /* If this was not actually the final message tell the user it is fragmented so they can deal with it accordingly */
464 /* Final frame in multi-frame so push up the actual opcode */
465 *opcode = session->opcode;
468 *payload_len = session->payload_len;
469 *payload = session->payload;
470 session->payload_len = 0;
472 } else if (*opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
475 *payload_len = buf[1] & 0x7f;
477 /* Make the payload available so the user can look at the reason code if they so desire */
478 if ((*payload_len) && (new_payload = ast_realloc(session->payload, *payload_len))) {
479 session->payload = new_payload;
480 memcpy(session->payload, &buf[2], *payload_len);
481 *payload = session->payload;
484 if (!session->closing) {
485 ast_websocket_close(session, 0);
490 ast_verb(2, "WebSocket connection from '%s' closed\n", ast_sockaddr_stringify(&session->address));
492 /* 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
493 * fit that, I think. */
494 ast_websocket_close(session, 1003);
500 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)
502 struct ast_variable *v;
503 char *upgrade = NULL, *key = NULL, *key1 = NULL, *key2 = NULL, *protos = NULL, *requested_protocols = NULL, *protocol = NULL;
504 int version = 0, flags = 1;
505 struct websocket_protocol *protocol_handler = NULL;
506 struct ast_websocket *session;
507 struct ast_websocket_server *server;
509 /* Upgrade requests are only permitted on GET methods */
510 if (method != AST_HTTP_GET) {
511 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
517 /* Get the minimum headers required to satisfy our needs */
518 for (v = headers; v; v = v->next) {
519 if (!strcasecmp(v->name, "Upgrade")) {
520 upgrade = ast_strip(ast_strdupa(v->value));
521 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key")) {
522 key = ast_strip(ast_strdupa(v->value));
523 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key1")) {
524 key1 = ast_strip(ast_strdupa(v->value));
525 } else if (!strcasecmp(v->name, "Sec-WebSocket-Key2")) {
526 key2 = ast_strip(ast_strdupa(v->value));
527 } else if (!strcasecmp(v->name, "Sec-WebSocket-Protocol")) {
528 requested_protocols = ast_strip(ast_strdupa(v->value));
529 protos = ast_strdupa(requested_protocols);
530 } else if (!strcasecmp(v->name, "Sec-WebSocket-Version")) {
531 if (sscanf(v->value, "%30d", &version) != 1) {
537 /* If this is not a websocket upgrade abort */
538 if (!upgrade || strcasecmp(upgrade, "websocket")) {
539 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - did not request WebSocket\n",
540 ast_sockaddr_stringify(&ser->remote_address));
541 ast_http_error(ser, 426, "Upgrade Required", NULL);
543 } else if (ast_strlen_zero(requested_protocols)) {
544 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols requested\n",
545 ast_sockaddr_stringify(&ser->remote_address));
546 fputs("HTTP/1.1 400 Bad Request\r\n"
547 "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f);
549 } else if (key1 && key2) {
550 /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 and
551 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 -- not currently supported*/
552 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '00/76' chosen\n",
553 ast_sockaddr_stringify(&ser->remote_address));
554 fputs("HTTP/1.1 400 Bad Request\r\n"
555 "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f);
559 /* Iterate through the requested protocols trying to find one that we have a handler for */
560 while ((protocol = strsep(&requested_protocols, ","))) {
561 if ((protocol_handler = ao2_find(server->protocols, ast_strip(protocol), OBJ_KEY))) {
566 /* If no protocol handler exists bump this back to the requester */
567 if (!protocol_handler) {
568 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - no protocols out of '%s' supported\n",
569 ast_sockaddr_stringify(&ser->remote_address), protos);
570 fputs("HTTP/1.1 400 Bad Request\r\n"
571 "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f);
575 /* Determine how to respond depending on the version */
576 if (version == 7 || version == 8 || version == 13) {
577 /* Version 7 defined in specification http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07 */
578 /* Version 8 defined in specification http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 */
579 /* Version 13 defined in specification http://tools.ietf.org/html/rfc6455 */
580 char combined[strlen(key) + strlen(WEBSOCKET_GUID) + 1], base64[64];
583 if (!(session = ao2_alloc(sizeof(*session), session_destroy_fn))) {
584 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted\n",
585 ast_sockaddr_stringify(&ser->remote_address));
586 fputs("HTTP/1.1 400 Bad Request\r\n"
587 "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f);
588 ao2_ref(protocol_handler, -1);
592 snprintf(combined, sizeof(combined), "%s%s", key, WEBSOCKET_GUID);
593 ast_sha1_hash_uint(sha, combined);
594 ast_base64encode(base64, (const unsigned char*)sha, 20, sizeof(base64));
596 fprintf(ser->f, "HTTP/1.1 101 Switching Protocols\r\n"
598 "Connection: Upgrade\r\n"
599 "Sec-WebSocket-Accept: %s\r\n"
600 "Sec-WebSocket-Protocol: %s\r\n\r\n",
606 /* Specification defined in http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 or completely unknown */
607 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - unsupported version '%d' chosen\n",
608 ast_sockaddr_stringify(&ser->remote_address), version ? version : 75);
609 fputs("HTTP/1.1 400 Bad Request\r\n"
610 "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f);
611 ao2_ref(protocol_handler, -1);
615 /* Enable keepalive on all sessions so the underlying user does not have to */
616 if (setsockopt(ser->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
617 ast_log(LOG_WARNING, "WebSocket connection from '%s' could not be accepted - failed to enable keepalive\n",
618 ast_sockaddr_stringify(&ser->remote_address));
619 fputs("HTTP/1.1 400 Bad Request\r\n"
620 "Sec-WebSocket-Version: 7, 8, 13\r\n\r\n", ser->f);
621 ao2_ref(session, -1);
622 ao2_ref(protocol_handler, -1);
626 ast_verb(2, "WebSocket connection from '%s' for protocol '%s' accepted using version '%d'\n", ast_sockaddr_stringify(&ser->remote_address), protocol, version);
628 /* Populate the session with all the needed details */
630 session->fd = ser->fd;
631 ast_sockaddr_copy(&session->address, &ser->remote_address);
632 session->opcode = -1;
633 session->reconstruct = DEFAULT_RECONSTRUCTION_CEILING;
634 session->secure = ser->ssl ? 1 : 0;
636 /* Give up ownership of the socket and pass it to the protocol handler */
637 protocol_handler->callback(session, get_vars, headers);
638 ao2_ref(protocol_handler, -1);
640 /* By dropping the FILE* from the session it won't get closed when the HTTP server cleans up */
646 static struct ast_http_uri websocketuri = {
647 .callback = ast_websocket_uri_cb,
648 .description = "Asterisk HTTP WebSocket",
655 /*! \brief Simple echo implementation which echoes received text and binary frames */
656 static void websocket_echo_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
660 if ((flags = fcntl(ast_websocket_fd(session), F_GETFL)) == -1) {
666 if (fcntl(ast_websocket_fd(session), F_SETFL, flags) == -1) {
670 while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
672 uint64_t payload_len;
673 enum ast_websocket_opcode opcode;
676 if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
677 /* We err on the side of caution and terminate the session if any error occurs */
681 if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
682 ast_websocket_write(session, opcode, payload, payload_len);
683 } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
689 ast_websocket_unref(session);
692 int AST_OPTIONAL_API_NAME(ast_websocket_add_protocol)(const char *name, ast_websocket_callback callback)
694 struct ast_websocket_server *ws_server = websocketuri.data;
698 return ast_websocket_server_add_protocol(ws_server, name, callback);
701 int AST_OPTIONAL_API_NAME(ast_websocket_remove_protocol)(const char *name, ast_websocket_callback callback)
703 struct ast_websocket_server *ws_server = websocketuri.data;
707 return ast_websocket_server_remove_protocol(ws_server, name, callback);
710 static int load_module(void)
712 websocketuri.data = ast_websocket_server_create();
713 if (!websocketuri.data) {
714 return AST_MODULE_LOAD_FAILURE;
716 ast_http_uri_link(&websocketuri);
717 ast_websocket_add_protocol("echo", websocket_echo_callback);
722 static int unload_module(void)
724 ast_websocket_remove_protocol("echo", websocket_echo_callback);
725 ast_http_uri_unlink(&websocketuri);
726 ao2_ref(websocketuri.data, -1);
727 websocketuri.data = NULL;
732 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "HTTP WebSocket Support",
734 .unload = unload_module,
735 .load_pri = AST_MODPRI_CHANNEL_DEPEND,