res_pjsip_transport_websocket: Fix use-after-free bugs.
[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_ws;
42 static int transport_type_wss;
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
67         if (ast_websocket_write(wstransport->ws_session, AST_WEBSOCKET_OPCODE_TEXT, tdata->buf.start, (int)(tdata->buf.cur - tdata->buf.start))) {
68                 return PJ_EUNKNOWN;
69         }
70
71         return PJ_SUCCESS;
72 }
73
74 /*!
75  * \brief Destroy the pjsip transport.
76  *
77  * Called by pjsip transport manager.
78  */
79 static pj_status_t ws_destroy(pjsip_transport *transport)
80 {
81         struct ws_transport *wstransport = (struct ws_transport *)transport;
82         int fd = ast_websocket_fd(wstransport->ws_session);
83
84         if (fd > 0) {
85                 ast_websocket_close(wstransport->ws_session, 1000);
86                 shutdown(fd, SHUT_RDWR);
87         }
88
89         ao2_ref(wstransport, -1);
90
91         return PJ_SUCCESS;
92 }
93
94 static void transport_dtor(void *arg)
95 {
96         struct ws_transport *wstransport = arg;
97
98         if (wstransport->ws_session) {
99                 ast_websocket_unref(wstransport->ws_session);
100         }
101
102         if (wstransport->transport.ref_cnt) {
103                 pj_atomic_destroy(wstransport->transport.ref_cnt);
104         }
105
106         if (wstransport->transport.lock) {
107                 pj_lock_destroy(wstransport->transport.lock);
108         }
109
110         if (wstransport->transport.endpt && wstransport->transport.pool) {
111                 pjsip_endpt_release_pool(wstransport->transport.endpt, wstransport->transport.pool);
112         }
113
114         if (wstransport->rdata.tp_info.pool) {
115                 pjsip_endpt_release_pool(wstransport->transport.endpt, wstransport->rdata.tp_info.pool);
116         }
117 }
118
119 static int transport_shutdown(void *data)
120 {
121         struct ws_transport *wstransport = data;
122
123         if (!wstransport->transport.is_shutdown && !wstransport->transport.is_destroying) {
124                 pjsip_transport_shutdown(&wstransport->transport);
125         }
126
127         /* Note that the destructor calls PJSIP functions,
128          * therefore it must be called in a PJSIP thread.
129          */
130         ao2_ref(wstransport, -1);
131
132         return 0;
133 }
134
135 struct transport_create_data {
136         struct ws_transport *transport;
137         struct ast_websocket *ws_session;
138 };
139
140 /*!
141  * \brief Create a pjsip transport.
142  */
143 static int transport_create(void *data)
144 {
145         struct transport_create_data *create_data = data;
146         struct ws_transport *newtransport = NULL;
147
148         pjsip_endpoint *endpt = ast_sip_get_pjsip_endpoint();
149         struct pjsip_tpmgr *tpmgr = pjsip_endpt_get_tpmgr(endpt);
150
151         pj_pool_t *pool;
152         pj_str_t buf;
153         pj_status_t status;
154
155         newtransport = ao2_t_alloc_options(sizeof(*newtransport), transport_dtor,
156                         AO2_ALLOC_OPT_LOCK_NOLOCK, "pjsip websocket transport");
157         if (!newtransport) {
158                 ast_log(LOG_ERROR, "Failed to allocate WebSocket transport.\n");
159                 goto on_error;
160         }
161
162         newtransport->transport.endpt = endpt;
163
164         if (!(pool = pjsip_endpt_create_pool(endpt, "ws", 512, 512))) {
165                 ast_log(LOG_ERROR, "Failed to allocate WebSocket endpoint pool.\n");
166                 goto on_error;
167         }
168
169         newtransport->transport.pool = pool;
170         newtransport->ws_session = create_data->ws_session;
171
172         /* Keep the session until transport dies */
173         ast_websocket_ref(newtransport->ws_session);
174
175         status = pj_atomic_create(pool, 0, &newtransport->transport.ref_cnt);
176         if (status != PJ_SUCCESS) {
177                 goto on_error;
178         }
179
180         status = pj_lock_create_recursive_mutex(pool, pool->obj_name, &newtransport->transport.lock);
181         if (status != PJ_SUCCESS) {
182                 goto on_error;
183         }
184
185         pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&buf, ast_sockaddr_stringify(ast_websocket_remote_address(newtransport->ws_session))), &newtransport->transport.key.rem_addr);
186         newtransport->transport.key.rem_addr.addr.sa_family = pj_AF_INET();
187         newtransport->transport.key.type = ast_websocket_is_secure(newtransport->ws_session) ? transport_type_wss : transport_type_ws;
188
189         newtransport->transport.addr_len = pj_sockaddr_get_len(&newtransport->transport.key.rem_addr);
190
191         pj_sockaddr_cp(&newtransport->transport.local_addr, &newtransport->transport.key.rem_addr);
192
193         newtransport->transport.local_name.host.ptr = (char *)pj_pool_alloc(pool, newtransport->transport.addr_len+4);
194         pj_sockaddr_print(&newtransport->transport.key.rem_addr, newtransport->transport.local_name.host.ptr, newtransport->transport.addr_len+4, 0);
195         newtransport->transport.local_name.host.slen = pj_ansi_strlen(newtransport->transport.local_name.host.ptr);
196         newtransport->transport.local_name.port = pj_sockaddr_get_port(&newtransport->transport.key.rem_addr);
197
198         newtransport->transport.type_name = (char *)pjsip_transport_get_type_name(newtransport->transport.key.type);
199         newtransport->transport.flag = pjsip_transport_get_flag_from_type((pjsip_transport_type_e)newtransport->transport.key.type);
200         newtransport->transport.info = (char *)pj_pool_alloc(newtransport->transport.pool, 64);
201
202         newtransport->transport.tpmgr = tpmgr;
203         newtransport->transport.send_msg = &ws_send_msg;
204         newtransport->transport.destroy = &ws_destroy;
205
206         status = pjsip_transport_register(newtransport->transport.tpmgr,
207                         (pjsip_transport *)newtransport);
208         if (status != PJ_SUCCESS) {
209                 goto on_error;
210         }
211
212         /* Add a reference for pjsip transport manager */
213         ao2_ref(newtransport, +1);
214
215         newtransport->rdata.tp_info.transport = &newtransport->transport;
216         newtransport->rdata.tp_info.pool = pjsip_endpt_create_pool(endpt, "rtd%p",
217                 PJSIP_POOL_RDATA_LEN, PJSIP_POOL_RDATA_INC);
218         if (!newtransport->rdata.tp_info.pool) {
219                 ast_log(LOG_ERROR, "Failed to allocate WebSocket rdata.\n");
220                 pjsip_transport_destroy((pjsip_transport *)newtransport);
221                 goto on_error;
222         }
223
224         create_data->transport = newtransport;
225         return 0;
226
227 on_error:
228         ao2_cleanup(newtransport);
229         return -1;
230 }
231
232 struct transport_read_data {
233         struct ws_transport *transport;
234         char *payload;
235         uint64_t payload_len;
236 };
237
238 /*!
239  * \brief Pass WebSocket data into pjsip transport manager.
240  */
241 static int transport_read(void *data)
242 {
243         struct transport_read_data *read_data = data;
244         struct ws_transport *newtransport = read_data->transport;
245         struct ast_websocket *session = newtransport->ws_session;
246
247         pjsip_rx_data *rdata = &newtransport->rdata;
248         int recvd;
249         pj_str_t buf;
250         int pjsip_pkt_len;
251
252         pj_gettimeofday(&rdata->pkt_info.timestamp);
253
254         pjsip_pkt_len = PJSIP_MAX_PKT_LEN < read_data->payload_len ? PJSIP_MAX_PKT_LEN : read_data->payload_len;
255         pj_memcpy(rdata->pkt_info.packet, read_data->payload, pjsip_pkt_len);
256         rdata->pkt_info.len = pjsip_pkt_len;
257         rdata->pkt_info.zero = 0;
258
259         pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&buf, ast_sockaddr_stringify(ast_websocket_remote_address(session))), &rdata->pkt_info.src_addr);
260         rdata->pkt_info.src_addr.addr.sa_family = pj_AF_INET();
261
262         rdata->pkt_info.src_addr_len = sizeof(rdata->pkt_info.src_addr);
263
264         pj_ansi_strcpy(rdata->pkt_info.src_name, ast_sockaddr_stringify_host(ast_websocket_remote_address(session)));
265         rdata->pkt_info.src_port = ast_sockaddr_port(ast_websocket_remote_address(session));
266
267         recvd = pjsip_tpmgr_receive_packet(rdata->tp_info.transport->tpmgr, rdata);
268
269         pj_pool_reset(rdata->tp_info.pool);
270
271         return (read_data->payload_len == recvd) ? 0 : -1;
272 }
273
274 static int get_write_timeout(void)
275 {
276         int write_timeout = -1;
277         struct ao2_container *transports;
278
279         transports = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "transport", AST_RETRIEVE_FLAG_ALL, NULL);
280
281         if (transports) {
282                 struct ao2_iterator it_transports = ao2_iterator_init(transports, 0);
283                 struct ast_sip_transport *transport;
284
285                 for (; (transport = ao2_iterator_next(&it_transports)); ao2_cleanup(transport)) {
286                         if (transport->type != AST_TRANSPORT_WS && transport->type != AST_TRANSPORT_WSS) {
287                                 continue;
288                         }
289                         ast_debug(5, "Found %s transport with write timeout: %d\n",
290                                 transport->type == AST_TRANSPORT_WS ? "WS" : "WSS",
291                                 transport->write_timeout);
292                         write_timeout = MAX(write_timeout, transport->write_timeout);
293                 }
294                 ao2_cleanup(transports);
295         }
296
297         if (write_timeout < 0) {
298                 write_timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
299         }
300
301         ast_debug(1, "Write timeout for WS/WSS transports: %d\n", write_timeout);
302         return write_timeout;
303 }
304
305 /*!
306  \brief WebSocket connection handler.
307  */
308 static void websocket_cb(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
309 {
310         struct ast_taskprocessor *serializer = NULL;
311         struct transport_create_data create_data;
312         struct ws_transport *transport = NULL;
313         struct transport_read_data read_data;
314
315         if (ast_websocket_set_nonblock(session)) {
316                 ast_websocket_unref(session);
317                 return;
318         }
319
320         if (ast_websocket_set_timeout(session, get_write_timeout())) {
321                 ast_websocket_unref(session);
322                 return;
323         }
324
325         if (!(serializer = ast_sip_create_serializer())) {
326                 ast_websocket_unref(session);
327                 return;
328         }
329
330         create_data.ws_session = session;
331
332         if (ast_sip_push_task_synchronous(serializer, transport_create, &create_data)) {
333                 ast_log(LOG_ERROR, "Could not create WebSocket transport.\n");
334                 ast_websocket_unref(session);
335                 return;
336         }
337
338         transport = create_data.transport;
339         read_data.transport = transport;
340
341         while (ast_wait_for_input(ast_websocket_fd(session), -1) > 0) {
342                 enum ast_websocket_opcode opcode;
343                 int fragmented;
344
345                 if (ast_websocket_read(session, &read_data.payload, &read_data.payload_len, &opcode, &fragmented)) {
346                         break;
347                 }
348
349                 if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
350                         ast_sip_push_task_synchronous(serializer, transport_read, &read_data);
351                 } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
352                         break;
353                 }
354         }
355
356         ast_sip_push_task_synchronous(serializer, transport_shutdown, transport);
357
358         ast_taskprocessor_unreference(serializer);
359         ast_websocket_unref(session);
360 }
361
362 /*!
363  * \brief Store the transport a message came in on, so it can be used for outbound messages to that contact.
364  */
365 static pj_bool_t websocket_on_rx_msg(pjsip_rx_data *rdata)
366 {
367         static const pj_str_t STR_WS = { "ws", 2 };
368         static const pj_str_t STR_WSS = { "wss", 3 };
369         pjsip_contact_hdr *contact;
370
371         long type = rdata->tp_info.transport->key.type;
372
373         if (type != (long)transport_type_ws && type != (long)transport_type_wss) {
374                 return PJ_FALSE;
375         }
376
377         if ((contact = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL)) && !contact->star &&
378                 (PJSIP_URI_SCHEME_IS_SIP(contact->uri) || PJSIP_URI_SCHEME_IS_SIPS(contact->uri))) {
379                 pjsip_sip_uri *uri = pjsip_uri_get_uri(contact->uri);
380
381                 pj_cstr(&uri->host, rdata->pkt_info.src_name);
382                 uri->port = rdata->pkt_info.src_port;
383                 ast_debug(4, "Re-wrote Contact URI host/port to %.*s:%d\n",
384                         (int)pj_strlen(&uri->host), pj_strbuf(&uri->host), uri->port);
385                 pj_strdup(rdata->tp_info.pool, &uri->transport_param, (type == (long)transport_type_ws) ? &STR_WS : &STR_WSS);
386         }
387
388         rdata->msg_info.via->rport_param = 0;
389
390         return PJ_FALSE;
391 }
392
393 static pjsip_module websocket_module = {
394         .name = { "WebSocket Transport Module", 26 },
395         .id = -1,
396         .priority = PJSIP_MOD_PRIORITY_TRANSPORT_LAYER,
397         .on_rx_request = websocket_on_rx_msg,
398         .on_rx_response = websocket_on_rx_msg,
399 };
400
401 /*! \brief Function called when an INVITE goes out */
402 static void websocket_outgoing_invite_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
403 {
404         if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
405                 pjsip_dlg_add_usage(session->inv_session->dlg, &websocket_module, NULL);
406         }
407 }
408
409 /*! \brief Supplement for adding Websocket functionality to dialog */
410 static struct ast_sip_session_supplement websocket_supplement = {
411         .method = "INVITE",
412         .priority = AST_SIP_SUPPLEMENT_PRIORITY_FIRST + 1,
413         .outgoing_request = websocket_outgoing_invite_request,
414 };
415
416 static int load_module(void)
417 {
418         CHECK_PJSIP_MODULE_LOADED();
419
420         pjsip_transport_register_type(PJSIP_TRANSPORT_RELIABLE, "WS", 5060, &transport_type_ws);
421         pjsip_transport_register_type(PJSIP_TRANSPORT_RELIABLE, "WSS", 5060, &transport_type_wss);
422
423         if (ast_sip_register_service(&websocket_module) != PJ_SUCCESS) {
424                 return AST_MODULE_LOAD_DECLINE;
425         }
426
427         if (ast_sip_session_register_supplement(&websocket_supplement)) {
428                 ast_sip_unregister_service(&websocket_module);
429                 return AST_MODULE_LOAD_DECLINE;
430         }
431
432         if (ast_websocket_add_protocol("sip", websocket_cb)) {
433                 ast_sip_session_unregister_supplement(&websocket_supplement);
434                 ast_sip_unregister_service(&websocket_module);
435                 return AST_MODULE_LOAD_DECLINE;
436         }
437
438         return AST_MODULE_LOAD_SUCCESS;
439 }
440
441 static int unload_module(void)
442 {
443         ast_sip_unregister_service(&websocket_module);
444         ast_sip_session_unregister_supplement(&websocket_supplement);
445         ast_websocket_remove_protocol("sip", websocket_cb);
446
447         return 0;
448 }
449
450 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP WebSocket Transport Support",
451         .support_level = AST_MODULE_SUPPORT_CORE,
452         .load = load_module,
453         .unload = unload_module,
454         .load_pri = AST_MODPRI_APP_DEPEND,
455 );