22ec19540dc52839f266aaf75495accb0ff72bbe
[asterisk/asterisk.git] / res / res_pjsip_transport_websocket.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Jason Parker <jparker@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 /*!
20  * \brief WebSocket transport module
21  */
22
23 /*** MODULEINFO
24         <depend>pjproject</depend>
25         <depend>res_pjsip</depend>
26         <depend>res_http_websocket</depend>
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 #include <pjsip.h>
33 #include <pjsip_ua.h>
34
35 #include "asterisk/module.h"
36 #include "asterisk/http_websocket.h"
37 #include "asterisk/res_pjsip.h"
38 #include "asterisk/res_pjsip_session.h"
39 #include "asterisk/taskprocessor.h"
40
41 static int transport_type_wss;
42 static int transport_type_wss_ipv6;
43
44 /*!
45  * \brief Wrapper for pjsip_transport, for storing the WebSocket session
46  */
47 struct ws_transport {
48         pjsip_transport transport;
49         pjsip_rx_data rdata;
50         struct ast_websocket *ws_session;
51 };
52
53 /*!
54  * \brief Send a message over the WebSocket connection.
55  *
56  * Called by pjsip transport manager.
57  */
58 static pj_status_t ws_send_msg(pjsip_transport *transport,
59                             pjsip_tx_data *tdata,
60                             const pj_sockaddr_t *rem_addr,
61                             int addr_len,
62                             void *token,
63                             pjsip_transport_callback callback)
64 {
65         struct ws_transport *wstransport = (struct ws_transport *)transport;
66         uint64_t len = tdata->buf.cur - tdata->buf.start;
67
68         if (ast_websocket_write(wstransport->ws_session, AST_WEBSOCKET_OPCODE_TEXT, tdata->buf.start, len)) {
69                 return PJ_EUNKNOWN;
70         }
71
72         return PJ_SUCCESS;
73 }
74
75 /*!
76  * \brief Destroy the pjsip transport.
77  *
78  * Called by pjsip transport manager.
79  */
80 static pj_status_t ws_destroy(pjsip_transport *transport)
81 {
82         struct ws_transport *wstransport = (struct ws_transport *)transport;
83         int fd = ast_websocket_fd(wstransport->ws_session);
84
85         if (fd > 0) {
86                 ast_websocket_close(wstransport->ws_session, 1000);
87                 shutdown(fd, SHUT_RDWR);
88         }
89
90         ao2_ref(wstransport, -1);
91
92         return PJ_SUCCESS;
93 }
94
95 static void transport_dtor(void *arg)
96 {
97         struct ws_transport *wstransport = arg;
98
99         if (wstransport->ws_session) {
100                 ast_websocket_unref(wstransport->ws_session);
101         }
102
103         if (wstransport->transport.ref_cnt) {
104                 pj_atomic_destroy(wstransport->transport.ref_cnt);
105         }
106
107         if (wstransport->transport.lock) {
108                 pj_lock_destroy(wstransport->transport.lock);
109         }
110
111         if (wstransport->transport.endpt && wstransport->transport.pool) {
112                 pjsip_endpt_release_pool(wstransport->transport.endpt, wstransport->transport.pool);
113         }
114
115         if (wstransport->rdata.tp_info.pool) {
116                 pjsip_endpt_release_pool(wstransport->transport.endpt, wstransport->rdata.tp_info.pool);
117         }
118 }
119
120 static int transport_shutdown(void *data)
121 {
122         struct ws_transport *wstransport = data;
123
124         if (!wstransport->transport.is_shutdown && !wstransport->transport.is_destroying) {
125                 pjsip_transport_shutdown(&wstransport->transport);
126         }
127
128         /* Note that the destructor calls PJSIP functions,
129          * therefore it must be called in a PJSIP thread.
130          */
131         ao2_ref(wstransport, -1);
132
133         return 0;
134 }
135
136 struct transport_create_data {
137         struct ws_transport *transport;
138         struct ast_websocket *ws_session;
139 };
140
141 /*!
142  * \brief Create a pjsip transport.
143  */
144 static int transport_create(void *data)
145 {
146         struct transport_create_data *create_data = data;
147         struct ws_transport *newtransport = NULL;
148         pjsip_tp_state_callback state_cb;
149
150         pjsip_endpoint *endpt = ast_sip_get_pjsip_endpoint();
151         struct pjsip_tpmgr *tpmgr = pjsip_endpt_get_tpmgr(endpt);
152
153         char *ws_addr_str;
154         pj_pool_t *pool;
155         pj_str_t buf;
156         pj_status_t status;
157
158         newtransport = ao2_t_alloc_options(sizeof(*newtransport), transport_dtor,
159                         AO2_ALLOC_OPT_LOCK_NOLOCK, "pjsip websocket transport");
160         if (!newtransport) {
161                 ast_log(LOG_ERROR, "Failed to allocate WebSocket transport.\n");
162                 goto on_error;
163         }
164
165         /* Give websocket transport a unique name for its lifetime */
166         snprintf(newtransport->transport.obj_name, PJ_MAX_OBJ_NAME, "ws%p",
167                 &newtransport->transport);
168
169         newtransport->transport.endpt = endpt;
170
171         if (!(pool = pjsip_endpt_create_pool(endpt, "ws", 512, 512))) {
172                 ast_log(LOG_ERROR, "Failed to allocate WebSocket endpoint pool.\n");
173                 goto on_error;
174         }
175
176         newtransport->transport.pool = pool;
177         newtransport->ws_session = create_data->ws_session;
178
179         /* Keep the session until transport dies */
180         ast_websocket_ref(newtransport->ws_session);
181
182         status = pj_atomic_create(pool, 0, &newtransport->transport.ref_cnt);
183         if (status != PJ_SUCCESS) {
184                 goto on_error;
185         }
186
187         status = pj_lock_create_recursive_mutex(pool, pool->obj_name, &newtransport->transport.lock);
188         if (status != PJ_SUCCESS) {
189                 goto on_error;
190         }
191
192         /*
193          * The type_name here is mostly used by log messages eihter in
194          * pjproject or Asterisk.  Other places are reconstituting subscriptions
195          * after a restart (which could never work for a websocket connection anyway),
196          * received MESSAGE requests to set PJSIP_TRANSPORT, and most importantly
197          * by pjproject when generating the Via header.
198          */
199         newtransport->transport.type_name = ast_websocket_is_secure(newtransport->ws_session)
200                 ? "WSS" : "WS";
201
202         ws_addr_str = ast_sockaddr_stringify(ast_websocket_remote_address(newtransport->ws_session));
203         ast_debug(4, "Creating websocket transport for %s:%s\n",
204                 newtransport->transport.type_name, ws_addr_str);
205
206         pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&buf, ws_addr_str), &newtransport->transport.key.rem_addr);
207         if (newtransport->transport.key.rem_addr.addr.sa_family == pj_AF_INET6()) {
208                 newtransport->transport.key.type = transport_type_wss_ipv6;
209                 newtransport->transport.local_name.host.ptr = (char *)pj_pool_alloc(pool, PJ_INET6_ADDRSTRLEN);
210                 pj_sockaddr_print(&newtransport->transport.key.rem_addr, newtransport->transport.local_name.host.ptr, PJ_INET6_ADDRSTRLEN, 0);
211         } else {
212                 newtransport->transport.key.type = transport_type_wss;
213                 newtransport->transport.local_name.host.ptr = (char *)pj_pool_alloc(pool, PJ_INET_ADDRSTRLEN);
214                 pj_sockaddr_print(&newtransport->transport.key.rem_addr, newtransport->transport.local_name.host.ptr, PJ_INET_ADDRSTRLEN, 0);
215         }
216
217         newtransport->transport.addr_len = pj_sockaddr_get_len(&newtransport->transport.key.rem_addr);
218
219         pj_sockaddr_cp(&newtransport->transport.local_addr, &newtransport->transport.key.rem_addr);
220
221         newtransport->transport.local_name.host.slen = pj_ansi_strlen(newtransport->transport.local_name.host.ptr);
222         newtransport->transport.local_name.port = pj_sockaddr_get_port(&newtransport->transport.key.rem_addr);
223
224         newtransport->transport.flag = pjsip_transport_get_flag_from_type((pjsip_transport_type_e)newtransport->transport.key.type);
225         newtransport->transport.info = (char *)pj_pool_alloc(newtransport->transport.pool, 64);
226
227         newtransport->transport.dir = PJSIP_TP_DIR_INCOMING;
228         newtransport->transport.tpmgr = tpmgr;
229         newtransport->transport.send_msg = &ws_send_msg;
230         newtransport->transport.destroy = &ws_destroy;
231
232         status = pjsip_transport_register(newtransport->transport.tpmgr,
233                         (pjsip_transport *)newtransport);
234         if (status != PJ_SUCCESS) {
235                 goto on_error;
236         }
237
238         /* Add a reference for pjsip transport manager */
239         ao2_ref(newtransport, +1);
240
241         newtransport->rdata.tp_info.transport = &newtransport->transport;
242         newtransport->rdata.tp_info.pool = pjsip_endpt_create_pool(endpt, "rtd%p",
243                 PJSIP_POOL_RDATA_LEN, PJSIP_POOL_RDATA_INC);
244         if (!newtransport->rdata.tp_info.pool) {
245                 ast_log(LOG_ERROR, "Failed to allocate WebSocket rdata.\n");
246                 pjsip_transport_destroy((pjsip_transport *)newtransport);
247                 goto on_error;
248         }
249
250         create_data->transport = newtransport;
251
252         /* Notify application of transport state */
253         state_cb = pjsip_tpmgr_get_state_cb(newtransport->transport.tpmgr);
254         if (state_cb) {
255                 pjsip_transport_state_info state_info;
256
257                 memset(&state_info, 0, sizeof(state_info));
258                 state_cb(&newtransport->transport, PJSIP_TP_STATE_CONNECTED, &state_info);
259         }
260
261         return 0;
262
263 on_error:
264         ao2_cleanup(newtransport);
265         return -1;
266 }
267
268 struct transport_read_data {
269         struct ws_transport *transport;
270         char *payload;
271         uint64_t payload_len;
272 };
273
274 /*!
275  * \brief Pass WebSocket data into pjsip transport manager.
276  */
277 static int transport_read(void *data)
278 {
279         struct transport_read_data *read_data = data;
280         struct ws_transport *newtransport = read_data->transport;
281         struct ast_websocket *session = newtransport->ws_session;
282
283         pjsip_rx_data *rdata = &newtransport->rdata;
284         int recvd;
285         pj_str_t buf;
286         int pjsip_pkt_len;
287
288         pj_gettimeofday(&rdata->pkt_info.timestamp);
289
290         pjsip_pkt_len = PJSIP_MAX_PKT_LEN < read_data->payload_len ? PJSIP_MAX_PKT_LEN : read_data->payload_len;
291         pj_memcpy(rdata->pkt_info.packet, read_data->payload, pjsip_pkt_len);
292         rdata->pkt_info.len = pjsip_pkt_len;
293         rdata->pkt_info.zero = 0;
294
295         pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&buf, ast_sockaddr_stringify(ast_websocket_remote_address(session))), &rdata->pkt_info.src_addr);
296         rdata->pkt_info.src_addr_len = sizeof(rdata->pkt_info.src_addr);
297
298         pj_ansi_strcpy(rdata->pkt_info.src_name, ast_sockaddr_stringify_host(ast_websocket_remote_address(session)));
299         rdata->pkt_info.src_port = ast_sockaddr_port(ast_websocket_remote_address(session));
300
301         recvd = pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, rdata);
302
303         pj_pool_reset(rdata->tp_info.pool);
304
305         return (read_data->payload_len == recvd) ? 0 : -1;
306 }
307
308 static int get_write_timeout(void)
309 {
310         int write_timeout = -1;
311         struct ao2_container *transport_states;
312
313         transport_states = ast_sip_get_transport_states();
314
315         if (transport_states) {
316                 struct ao2_iterator it_transport_states = ao2_iterator_init(transport_states, 0);
317                 struct ast_sip_transport_state *transport_state;
318
319                 for (; (transport_state = ao2_iterator_next(&it_transport_states)); ao2_cleanup(transport_state)) {
320                         struct ast_sip_transport *transport;
321
322                         if (transport_state->type != AST_TRANSPORT_WS && transport_state->type != AST_TRANSPORT_WSS) {
323                                 continue;
324                         }
325                         transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_state->id);
326                         if (!transport) {
327                                 continue;
328                         }
329                         ast_debug(5, "Found %s transport with write timeout: %d\n",
330                                 transport->type == AST_TRANSPORT_WS ? "WS" : "WSS",
331                                 transport->write_timeout);
332                         write_timeout = MAX(write_timeout, transport->write_timeout);
333                 }
334                 ao2_iterator_destroy(&it_transport_states);
335                 ao2_cleanup(transport_states);
336         }
337
338         if (write_timeout < 0) {
339                 write_timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
340         }
341
342         ast_debug(1, "Write timeout for WS/WSS transports: %d\n", write_timeout);
343         return write_timeout;
344 }
345
346 static struct ast_taskprocessor *create_websocket_serializer(void)
347 {
348         char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
349
350         /* Create name with seq number appended. */
351         ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/websocket");
352
353         return ast_sip_create_serializer(tps_name);
354 }
355
356 /*! \brief WebSocket connection handler. */
357 static void websocket_cb(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
358 {
359         struct ast_taskprocessor *serializer;
360         struct transport_create_data create_data;
361         struct ws_transport *transport;
362         struct transport_read_data read_data;
363
364         if (ast_websocket_set_nonblock(session)) {
365                 ast_websocket_unref(session);
366                 return;
367         }
368
369         if (ast_websocket_set_timeout(session, get_write_timeout())) {
370                 ast_websocket_unref(session);
371                 return;
372         }
373
374         serializer = create_websocket_serializer();
375         if (!serializer) {
376                 ast_websocket_unref(session);
377                 return;
378         }
379
380         create_data.ws_session = session;
381
382         if (ast_sip_push_task_synchronous(serializer, transport_create, &create_data)) {
383                 ast_log(LOG_ERROR, "Could not create WebSocket transport.\n");
384                 ast_taskprocessor_unreference(serializer);
385                 ast_websocket_unref(session);
386                 return;
387         }
388
389         transport = create_data.transport;
390         read_data.transport = transport;
391
392         while (ast_wait_for_input(ast_websocket_fd(session), -1) > 0) {
393                 enum ast_websocket_opcode opcode;
394                 int fragmented;
395
396                 if (ast_websocket_read(session, &read_data.payload, &read_data.payload_len, &opcode, &fragmented)) {
397                         break;
398                 }
399
400                 if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
401                         ast_sip_push_task_synchronous(serializer, transport_read, &read_data);
402                 } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
403                         break;
404                 }
405         }
406
407         ast_sip_push_task_synchronous(serializer, transport_shutdown, transport);
408
409         ast_taskprocessor_unreference(serializer);
410         ast_websocket_unref(session);
411 }
412
413 /*!
414  * \brief Store the transport a message came in on, so it can be used for outbound messages to that contact.
415  */
416 static pj_bool_t websocket_on_rx_msg(pjsip_rx_data *rdata)
417 {
418         static const pj_str_t STR_WS = { "ws", 2 };
419         pjsip_contact_hdr *contact;
420
421         long type = rdata->tp_info.transport->key.type;
422
423         if (type != (long) transport_type_wss && type != (long) transport_type_wss_ipv6) {
424                 return PJ_FALSE;
425         }
426
427         contact = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL);
428         if (contact
429                 && !contact->star
430                 && (PJSIP_URI_SCHEME_IS_SIP(contact->uri) || PJSIP_URI_SCHEME_IS_SIPS(contact->uri))) {
431                 pjsip_sip_uri *uri = pjsip_uri_get_uri(contact->uri);
432                 const pj_str_t *txp_str = &STR_WS;
433
434                 ast_debug(4, "%s re-writing Contact URI from %.*s:%d%s%.*s to %s:%d;transport=%s\n",
435                         pjsip_rx_data_get_info(rdata),
436                         (int)pj_strlen(&uri->host), pj_strbuf(&uri->host), uri->port,
437                         pj_strlen(&uri->transport_param) ? ";transport=" : "",
438                         (int)pj_strlen(&uri->transport_param), pj_strbuf(&uri->transport_param),
439                         rdata->pkt_info.src_name ?: "", rdata->pkt_info.src_port, pj_strbuf(txp_str));
440
441                 pj_cstr(&uri->host, rdata->pkt_info.src_name);
442                 uri->port = rdata->pkt_info.src_port;
443                 pj_strdup(rdata->tp_info.pool, &uri->transport_param, txp_str);
444         }
445
446         rdata->msg_info.via->rport_param = 0;
447
448         return PJ_FALSE;
449 }
450
451 static pjsip_module websocket_module = {
452         .name = { "WebSocket Transport Module", 26 },
453         .id = -1,
454         .priority = PJSIP_MOD_PRIORITY_TRANSPORT_LAYER,
455         .on_rx_request = websocket_on_rx_msg,
456         .on_rx_response = websocket_on_rx_msg,
457 };
458
459 /*! \brief Function called when an INVITE goes out */
460 static void websocket_outgoing_invite_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
461 {
462         if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
463                 pjsip_dlg_add_usage(session->inv_session->dlg, &websocket_module, NULL);
464         }
465 }
466
467 /*! \brief Supplement for adding Websocket functionality to dialog */
468 static struct ast_sip_session_supplement websocket_supplement = {
469         .method = "INVITE",
470         .priority = AST_SIP_SUPPLEMENT_PRIORITY_FIRST + 1,
471         .outgoing_request = websocket_outgoing_invite_request,
472 };
473
474 static int load_module(void)
475 {
476         CHECK_PJSIP_MODULE_LOADED();
477
478         /*
479          * We only need one transport type name (ws) defined.  Firefox
480          * and Chrome do not support anything other than secure websockets
481          * anymore.
482          *
483          * Also we really cannot have two transports with the same name
484          * and address family because it would be ambiguous.  Outgoing
485          * requests may try to find the transport by name and pjproject
486          * only finds the first one registered.
487          */
488         pjsip_transport_register_type(PJSIP_TRANSPORT_RELIABLE | PJSIP_TRANSPORT_SECURE, "ws", 5060, &transport_type_wss);
489         pjsip_transport_register_type(PJSIP_TRANSPORT_RELIABLE | PJSIP_TRANSPORT_SECURE | PJSIP_TRANSPORT_IPV6, "ws", 5060, &transport_type_wss_ipv6);
490
491         if (ast_sip_register_service(&websocket_module) != PJ_SUCCESS) {
492                 return AST_MODULE_LOAD_DECLINE;
493         }
494
495         if (ast_sip_session_register_supplement(&websocket_supplement)) {
496                 ast_sip_unregister_service(&websocket_module);
497                 return AST_MODULE_LOAD_DECLINE;
498         }
499
500         if (ast_websocket_add_protocol("sip", websocket_cb)) {
501                 ast_sip_session_unregister_supplement(&websocket_supplement);
502                 ast_sip_unregister_service(&websocket_module);
503                 return AST_MODULE_LOAD_DECLINE;
504         }
505
506         return AST_MODULE_LOAD_SUCCESS;
507 }
508
509 static int unload_module(void)
510 {
511         ast_sip_unregister_service(&websocket_module);
512         ast_sip_session_unregister_supplement(&websocket_supplement);
513         ast_websocket_remove_protocol("sip", websocket_cb);
514
515         return 0;
516 }
517
518 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP WebSocket Transport Support",
519         .support_level = AST_MODULE_SUPPORT_CORE,
520         .load = load_module,
521         .unload = unload_module,
522         .load_pri = AST_MODPRI_APP_DEPEND,
523 );