d96564af8c103c625b38d69c5a63d8b2d087501a
[asterisk/asterisk.git] / res / res_http_websocket.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2012, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief WebSocket support for the Asterisk internal HTTP server
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>extended</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
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"
40
41 #define AST_API_MODULE
42 #include "asterisk/http_websocket.h"
43
44 /*! \brief GUID used to compute the accept key, defined in the specifications */
45 #define WEBSOCKET_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
46
47 /*! \brief Number of buckets for registered protocols */
48 #define MAX_PROTOCOL_BUCKETS 7
49
50 /*! \brief Size of the pre-determined buffer for WebSocket frames */
51 #define MAXIMUM_FRAME_SIZE 8192
52
53 /*! \brief Default reconstruction size for multi-frame payload reconstruction. If exceeded the next frame will start a
54  *         payload.
55  */
56 #define DEFAULT_RECONSTRUCTION_CEILING 16384
57
58 /*! \brief Maximum reconstruction size for multi-frame payload reconstruction. */
59 #define MAXIMUM_RECONSTRUCTION_CEILING 16384
60
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 */
72 };
73
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 */
78 };
79
80 /*! \brief Hashing function for protocols */
81 static int protocol_hash_fn(const void *obj, const int flags)
82 {
83         const struct websocket_protocol *protocol = obj;
84         const char *name = obj;
85
86         return ast_str_case_hash(flags & OBJ_KEY ? name : protocol->name);
87 }
88
89 /*! \brief Comparison function for protocols */
90 static int protocol_cmp_fn(void *obj, void *arg, int flags)
91 {
92         const struct websocket_protocol *protocol1 = obj, *protocol2 = arg;
93         const char *protocol = arg;
94
95         return !strcasecmp(protocol1->name, flags & OBJ_KEY ? protocol : protocol2->name) ? CMP_MATCH | CMP_STOP : 0;
96 }
97
98 /*! \brief Destructor function for protocols */
99 static void protocol_destroy_fn(void *obj)
100 {
101         struct websocket_protocol *protocol = obj;
102         ast_free(protocol->name);
103 }
104
105 /*! \brief Structure for a WebSocket server */
106 struct ast_websocket_server {
107         struct ao2_container *protocols; /*!< Container for registered protocols */
108 };
109
110 static void websocket_server_dtor(void *obj)
111 {
112         struct ast_websocket_server *server = obj;
113         ao2_cleanup(server->protocols);
114         server->protocols = NULL;
115 }
116
117 struct ast_websocket_server *ast_websocket_server_create(void)
118 {
119         RAII_VAR(struct ast_websocket_server *, server, NULL, ao2_cleanup);
120
121         server = ao2_alloc(sizeof(*server), websocket_server_dtor);
122         if (!server) {
123                 return NULL;
124         }
125
126         server->protocols = ao2_container_alloc(MAX_PROTOCOL_BUCKETS, protocol_hash_fn, protocol_cmp_fn);
127         if (!server->protocols) {
128                 return NULL;
129         }
130
131         ao2_ref(server, +1);
132         return server;
133 }
134
135 /*! \brief Destructor function for sessions */
136 static void session_destroy_fn(void *obj)
137 {
138         struct ast_websocket *session = obj;
139
140         if (session->f) {
141                 fclose(session->f);
142                 ast_verb(2, "WebSocket connection from '%s' closed\n", ast_sockaddr_stringify(&session->address));
143         }
144
145         ast_free(session->payload);
146 }
147
148 int AST_OPTIONAL_API_NAME(ast_websocket_server_add_protocol)(struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
149 {
150         struct websocket_protocol *protocol;
151
152         if (!server->protocols) {
153                 return -1;
154         }
155
156         ao2_lock(server->protocols);
157
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);
162                 return -1;
163         }
164
165         if (!(protocol = ao2_alloc(sizeof(*protocol), protocol_destroy_fn))) {
166                 ao2_unlock(server->protocols);
167                 return -1;
168         }
169
170         if (!(protocol->name = ast_strdup(name))) {
171                 ao2_ref(protocol, -1);
172                 ao2_unlock(server->protocols);
173                 return -1;
174         }
175
176         protocol->callback = callback;
177
178         ao2_link_flags(server->protocols, protocol, OBJ_NOLOCK);
179         ao2_unlock(server->protocols);
180         ao2_ref(protocol, -1);
181
182         ast_verb(2, "WebSocket registered sub-protocol '%s'\n", name);
183
184         return 0;
185 }
186
187 int AST_OPTIONAL_API_NAME(ast_websocket_server_remove_protocol)(struct ast_websocket_server *server, const char *name, ast_websocket_callback callback)
188 {
189         struct websocket_protocol *protocol;
190
191         if (!(protocol = ao2_find(server->protocols, name, OBJ_KEY))) {
192                 return -1;
193         }
194
195         if (protocol->callback != callback) {
196                 ao2_ref(protocol, -1);
197                 return -1;
198         }
199
200         ao2_unlink(server->protocols, protocol);
201         ao2_ref(protocol, -1);
202
203         ast_verb(2, "WebSocket unregistered sub-protocol '%s'\n", name);
204
205         return 0;
206 }
207
208 /*! \brief Close function for websocket session */
209 int AST_OPTIONAL_API_NAME(ast_websocket_close)(struct ast_websocket *session, uint16_t reason)
210 {
211         char frame[4] = { 0, }; /* The header is 2 bytes and the reason code takes up another 2 bytes */
212
213         frame[0] = AST_WEBSOCKET_OPCODE_CLOSE | 0x80;
214         frame[1] = 2; /* The reason code is always 2 bytes */
215
216         /* If no reason has been specified assume 1000 which is normal closure */
217         put_unaligned_uint16(&frame[2], htons(reason ? reason : 1000));
218
219         session->closing = 1;
220
221         return (fwrite(frame, 1, 4, session->f) == 4) ? 0 : -1;
222 }
223
224
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)
227 {
228         size_t header_size = 2; /* The minimum size of a websocket frame is 2 bytes */
229         char *frame;
230         uint64_t length = 0;
231
232         if (actual_length < 126) {
233                 length = actual_length;
234         } else if (actual_length < (1 << 16)) {
235                 length = 126;
236                 /* We need an additional 2 bytes to store the extended length */
237                 header_size += 2;
238         } else {
239                 length = 127;
240                 /* We need an additional 8 bytes to store the really really extended length */
241                 header_size += 8;
242         }
243
244         frame = ast_alloca(header_size);
245         memset(frame, 0, sizeof(*frame));
246
247         frame[0] = opcode | 0x80;
248         frame[1] = length;
249
250         /* Use the additional available bytes to store the length */
251         if (length == 126) {
252                 put_unaligned_uint16(&frame[2], htons(actual_length));
253         } else if (length == 127) {
254                 put_unaligned_uint64(&frame[2], htonl(actual_length));
255         }
256
257         if (fwrite(frame, 1, header_size, session->f) != header_size) {
258                 return -1;
259         }
260
261         if (fwrite(payload, 1, actual_length, session->f) != actual_length) {
262                 return -1;
263         }
264
265         return 0;
266 }
267
268 void AST_OPTIONAL_API_NAME(ast_websocket_reconstruct_enable)(struct ast_websocket *session, size_t bytes)
269 {
270         session->reconstruct = MIN(bytes, MAXIMUM_RECONSTRUCTION_CEILING);
271 }
272
273 void AST_OPTIONAL_API_NAME(ast_websocket_reconstruct_disable)(struct ast_websocket *session)
274 {
275         session->reconstruct = 0;
276 }
277
278 void AST_OPTIONAL_API_NAME(ast_websocket_ref)(struct ast_websocket *session)
279 {
280         ao2_ref(session, +1);
281 }
282
283 void AST_OPTIONAL_API_NAME(ast_websocket_unref)(struct ast_websocket *session)
284 {
285         ao2_ref(session, -1);
286 }
287
288 int AST_OPTIONAL_API_NAME(ast_websocket_fd)(struct ast_websocket *session)
289 {
290         return session->closing ? -1 : session->fd;
291 }
292
293 struct ast_sockaddr * AST_OPTIONAL_API_NAME(ast_websocket_remote_address)(struct ast_websocket *session)
294 {
295         return &session->address;
296 }
297
298 int AST_OPTIONAL_API_NAME(ast_websocket_is_secure)(struct ast_websocket *session)
299 {
300         return session->secure;
301 }
302
303 int AST_OPTIONAL_API_NAME(ast_websocket_set_nonblock)(struct ast_websocket *session)
304 {
305         int flags;
306
307         if ((flags = fcntl(session->fd, F_GETFL)) == -1) {
308                 return -1;
309         }
310
311         flags |= O_NONBLOCK;
312
313         if ((flags = fcntl(session->fd, F_SETFL, flags)) == -1) {
314                 return -1;
315         }
316
317         return 0;
318 }
319
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)
321 {
322         char buf[MAXIMUM_FRAME_SIZE] = "";
323         size_t frame_size, expected = 2;
324
325         *payload = NULL;
326         *payload_len = 0;
327         *fragmented = 0;
328
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) {
331                 return -1;
332         }
333
334         /* The minimum size for a WebSocket frame is 2 bytes */
335         if (frame_size < expected) {
336                 return -1;
337         }
338
339         *opcode = buf[0] & 0xf;
340
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;
346                 size_t remaining;
347
348                 if (mask_present) {
349                         /* The mask should take up 4 bytes */
350                         expected += 4;
351
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);
355                                 return 0;
356                         }
357                 }
358
359                 /* Assume no extended length and no masking at the beginning */
360                 *payload_len = buf[1] & 0x7f;
361                 *payload = &buf[2];
362
363                 /* Determine if extended length is being used */
364                 if (*payload_len == 126) {
365                         /* Use the next 2 bytes to get a uint16_t */
366                         expected += 2;
367                         *payload += 2;
368
369                         if (frame_size < expected) {
370                                 ast_websocket_close(session, 1009);
371                                 return 0;
372                         }
373
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 */
377                         expected += 8;
378                         *payload += 8;
379
380                         if (frame_size < expected) {
381                                 ast_websocket_close(session, 1009);
382                                 return 0;
383                         }
384
385                         *payload_len = ntohl(get_unaligned_uint64(&buf[2]));
386                 }
387
388                 /* If masking is present the payload currently points to the mask, so move it over 4 bytes to the actual payload */
389                 if (mask_present) {
390                         mask = *payload;
391                         *payload += 4;
392                 }
393
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);
396
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);
401                         return 0;
402                 }
403
404                 new_payload = *payload + (frame_size - expected);
405
406                 /* Read in the remaining payload */
407                 while (remaining > 0) {
408                         size_t payload_read;
409
410                         /* Wait for data to come in */
411                         if (ast_wait_for_input(session->fd, -1) <= 0) {
412                                 *opcode = AST_WEBSOCKET_OPCODE_CLOSE;
413                                 *payload = NULL;
414                                 session->closing = 1;
415                                 return 0;
416                         }
417
418                         /* If some sort of failure occurs notify the caller */
419                         if ((payload_read = fread(new_payload, 1, remaining, session->f)) < 1) {
420                                 return -1;
421                         }
422
423                         remaining -= payload_read;
424                         new_payload += payload_read;
425                 }
426
427                 /* If a mask is present unmask the payload */
428                 if (mask_present) {
429                         unsigned int pos;
430                         for (pos = 0; pos < *payload_len; pos++) {
431                                 (*payload)[pos] ^= mask[pos % 4];
432                         }
433                 }
434
435                 if (!(new_payload = ast_realloc(session->payload, session->payload_len + *payload_len))) {
436                         *payload_len = 0;
437                         ast_websocket_close(session, 1009);
438                         return 0;
439                 }
440
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);
444                 }
445
446                 session->payload = new_payload;
447                 memcpy(session->payload + session->payload_len, *payload, *payload_len);
448                 session->payload_len += *payload_len;
449
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;
454                         }
455                         *opcode = AST_WEBSOCKET_OPCODE_CONTINUATION;
456                         *payload_len = 0;
457                         *payload = NULL;
458                 } else {
459                         if (*opcode == AST_WEBSOCKET_OPCODE_CONTINUATION) {
460                                 if (!fin) {
461                                         /* If this was not actually the final message tell the user it is fragmented so they can deal with it accordingly */
462                                         *fragmented = 1;
463                                 } else {
464                                         /* Final frame in multi-frame so push up the actual opcode */
465                                         *opcode = session->opcode;
466                                 }
467                         }
468                         *payload_len = session->payload_len;
469                         *payload = session->payload;
470                         session->payload_len = 0;
471                 }
472         } else if (*opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
473                 char *new_payload;
474
475                 *payload_len = buf[1] & 0x7f;
476
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;
482                 }
483
484                 if (!session->closing) {
485                         ast_websocket_close(session, 0);
486                 }
487
488                 fclose(session->f);
489                 session->f = NULL;
490                 ast_verb(2, "WebSocket connection from '%s' closed\n", ast_sockaddr_stringify(&session->address));
491         } else {
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);
495         }
496
497         return 0;
498 }
499
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)
501 {
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;
508
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");
512                 return -1;
513         }
514
515         server = urih->data;
516
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) {
532                                 version = 0;
533                         }
534                 }
535         }
536
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);
542                 return -1;
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);
548                 return -1;
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);
556                 return 0;
557         }
558
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))) {
562                         break;
563                 }
564         }
565
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);
572                 return 0;
573         }
574
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];
581                 uint8_t sha[20];
582
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);
589                         return 0;
590                 }
591
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));
595
596                 fprintf(ser->f, "HTTP/1.1 101 Switching Protocols\r\n"
597                         "Upgrade: %s\r\n"
598                         "Connection: Upgrade\r\n"
599                         "Sec-WebSocket-Accept: %s\r\n"
600                         "Sec-WebSocket-Protocol: %s\r\n\r\n",
601                         upgrade,
602                         base64,
603                         protocol);
604         } else {
605
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);
612                 return 0;
613         }
614
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);
623                 return 0;
624         }
625
626         ast_verb(2, "WebSocket connection from '%s' for protocol '%s' accepted using version '%d'\n", ast_sockaddr_stringify(&ser->remote_address), protocol, version);
627
628         /* Populate the session with all the needed details */
629         session->f = ser->f;
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;
635
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);
639
640         /* By dropping the FILE* from the session it won't get closed when the HTTP server cleans up */
641         ser->f = NULL;
642
643         return 0;
644 }
645
646 static struct ast_http_uri websocketuri = {
647         .callback = ast_websocket_uri_cb,
648         .description = "Asterisk HTTP WebSocket",
649         .uri = "ws",
650         .has_subtree = 0,
651         .data = NULL,
652         .key = __FILE__,
653 };
654
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)
657 {
658         int flags, res;
659
660         if ((flags = fcntl(ast_websocket_fd(session), F_GETFL)) == -1) {
661                 goto end;
662         }
663
664         flags |= O_NONBLOCK;
665
666         if (fcntl(ast_websocket_fd(session), F_SETFL, flags) == -1) {
667                 goto end;
668         }
669
670         while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
671                 char *payload;
672                 uint64_t payload_len;
673                 enum ast_websocket_opcode opcode;
674                 int fragmented;
675
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 */
678                         break;
679                 }
680
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) {
684                         break;
685                 }
686         }
687
688 end:
689         ast_websocket_unref(session);
690 }
691
692 int AST_OPTIONAL_API_NAME(ast_websocket_add_protocol)(const char *name, ast_websocket_callback callback)
693 {
694         struct ast_websocket_server *ws_server = websocketuri.data;
695         if (!ws_server) {
696                 return -1;
697         }
698         return ast_websocket_server_add_protocol(ws_server, name, callback);
699 }
700
701 int AST_OPTIONAL_API_NAME(ast_websocket_remove_protocol)(const char *name, ast_websocket_callback callback)
702 {
703         struct ast_websocket_server *ws_server = websocketuri.data;
704         if (!ws_server) {
705                 return -1;
706         }
707         return ast_websocket_server_remove_protocol(ws_server, name, callback);
708 }
709
710 static int load_module(void)
711 {
712         websocketuri.data = ast_websocket_server_create();
713         if (!websocketuri.data) {
714                 return AST_MODULE_LOAD_FAILURE;
715         }
716         ast_http_uri_link(&websocketuri);
717         ast_websocket_add_protocol("echo", websocket_echo_callback);
718
719         return 0;
720 }
721
722 static int unload_module(void)
723 {
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;
728
729         return 0;
730 }
731
732 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "HTTP WebSocket Support",
733                 .load = load_module,
734                 .unload = unload_module,
735                 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
736         );