Remove redundant module checks and references.
[asterisk/asterisk.git] / res / res_pjsip_nat.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, 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 /*** MODULEINFO
20         <depend>pjproject</depend>
21         <depend>res_pjsip</depend>
22         <support_level>core</support_level>
23  ***/
24
25 #include "asterisk.h"
26
27 #include <pjsip.h>
28 #include <pjsip_ua.h>
29
30 #include "asterisk/res_pjsip.h"
31 #include "asterisk/res_pjsip_session.h"
32 #include "asterisk/module.h"
33 #include "asterisk/acl.h"
34
35 static void rewrite_uri(pjsip_rx_data *rdata, pjsip_sip_uri *uri)
36 {
37         pj_cstr(&uri->host, rdata->pkt_info.src_name);
38         uri->port = rdata->pkt_info.src_port;
39         if (!strcasecmp("WSS", rdata->tp_info.transport->type_name)) {
40                 /* WSS is special, we don't want to overwrite the URI at all as it needs to be ws */
41         } else if (strcasecmp("udp", rdata->tp_info.transport->type_name)) {
42                 uri->transport_param = pj_str(rdata->tp_info.transport->type_name);
43         } else {
44                 uri->transport_param.slen = 0;
45         }
46 }
47
48 static int rewrite_route_set(pjsip_rx_data *rdata, pjsip_dialog *dlg)
49 {
50         pjsip_rr_hdr *rr = NULL;
51         pjsip_sip_uri *uri;
52
53         if (rdata->msg_info.msg->type == PJSIP_RESPONSE_MSG) {
54                 pjsip_hdr *iter;
55                 for (iter = rdata->msg_info.msg->hdr.prev; iter != &rdata->msg_info.msg->hdr; iter = iter->prev) {
56                         if (iter->type == PJSIP_H_RECORD_ROUTE) {
57                                 rr = (pjsip_rr_hdr *)iter;
58                                 break;
59                         }
60                 }
61         } else if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method)) {
62                 rr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_RECORD_ROUTE, NULL);
63         }
64
65         if (rr) {
66                 uri = pjsip_uri_get_uri(&rr->name_addr);
67                 rewrite_uri(rdata, uri);
68                 if (dlg && !pj_list_empty(&dlg->route_set) && !dlg->route_set_frozen) {
69                         pjsip_routing_hdr *route = dlg->route_set.next;
70                         uri = pjsip_uri_get_uri(&route->name_addr);
71                         rewrite_uri(rdata, uri);
72                 }
73
74                 return 0;
75         }
76
77         return -1;
78 }
79
80 static int rewrite_contact(pjsip_rx_data *rdata, pjsip_dialog *dlg)
81 {
82         pjsip_contact_hdr *contact;
83
84         contact = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, NULL);
85         if (contact && !contact->star && (PJSIP_URI_SCHEME_IS_SIP(contact->uri) || PJSIP_URI_SCHEME_IS_SIPS(contact->uri))) {
86                 pjsip_sip_uri *uri = pjsip_uri_get_uri(contact->uri);
87
88                 rewrite_uri(rdata, uri);
89
90                 if (dlg && pj_list_empty(&dlg->route_set) && (!dlg->remote.contact
91                         || pjsip_uri_cmp(PJSIP_URI_IN_REQ_URI, dlg->remote.contact->uri, contact->uri))) {
92                         dlg->remote.contact = (pjsip_contact_hdr*)pjsip_hdr_clone(dlg->pool, contact);
93                         dlg->target = dlg->remote.contact->uri;
94                 }
95                 return 0;
96         }
97
98         return -1;
99 }
100
101 static pj_bool_t handle_rx_message(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
102 {
103         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
104
105         if (!endpoint) {
106                 return PJ_FALSE;
107         }
108
109         if (endpoint->nat.rewrite_contact) {
110                 /* rewrite_contact is intended to ensure we send requests/responses to
111                  * a routeable address when NAT is involved. The URI that dictates where
112                  * we send requests/responses can be determined either by Record-Route
113                  * headers or by the Contact header if no Record-Route headers are present.
114                  * We therefore will attempt to rewrite a Record-Route header first, and if
115                  * none are present, we fall back to rewriting the Contact header instead.
116                  */
117                 if (rewrite_route_set(rdata, dlg)) {
118                         rewrite_contact(rdata, dlg);
119                 }
120         }
121
122         if (endpoint->nat.force_rport) {
123                 rdata->msg_info.via->rport_param = rdata->pkt_info.src_port;
124         }
125
126         return PJ_FALSE;
127 }
128
129 static pj_bool_t nat_on_rx_message(pjsip_rx_data *rdata)
130 {
131         pj_bool_t res;
132         struct ast_sip_endpoint *endpoint;
133
134         endpoint = ast_pjsip_rdata_get_endpoint(rdata);
135         res = handle_rx_message(endpoint, rdata);
136         ao2_cleanup(endpoint);
137         return res;
138 }
139
140 /*! \brief Structure which contains information about a transport */
141 struct request_transport_details {
142         /*! \brief Type of transport */
143         enum ast_transport type;
144         /*! \brief Potential pointer to the transport itself, if UDP */
145         pjsip_transport *transport;
146         /*! \brief Potential pointer to the transport factory itself, if TCP/TLS */
147         pjsip_tpfactory *factory;
148         /*! \brief Local address for transport */
149         pj_str_t local_address;
150         /*! \brief Local port for transport */
151         int local_port;
152 };
153
154 /*! \brief Callback function for finding the transport the request is going out on */
155 static int find_transport_state_in_use(void *obj, void *arg, int flags)
156 {
157         struct ast_sip_transport_state *transport_state = obj;
158         struct request_transport_details *details = arg;
159
160         /* If an explicit transport or factory matches then this is what is in use, if we are unavailable
161          * to compare based on that we make sure that the type is the same and the source IP address/port are the same
162          */
163         if (transport_state && ((details->transport && details->transport == transport_state->transport) ||
164                 (details->factory && details->factory == transport_state->factory) ||
165                 ((details->type == transport_state->type) && (transport_state->factory) &&
166                         !pj_strcmp(&transport_state->factory->addr_name.host, &details->local_address) &&
167                         transport_state->factory->addr_name.port == details->local_port))) {
168                 return CMP_MATCH;
169         }
170
171         return 0;
172 }
173
174 /*! \brief Helper function which returns the SIP URI of a Contact header */
175 static pjsip_sip_uri *nat_get_contact_sip_uri(pjsip_tx_data *tdata)
176 {
177         pjsip_contact_hdr *contact = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CONTACT, NULL);
178
179         if (!contact || (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri))) {
180                 return NULL;
181         }
182
183         return pjsip_uri_get_uri(contact->uri);
184 }
185
186 /*! \brief Structure which contains hook details */
187 struct nat_hook_details {
188         /*! \brief Outgoing message itself */
189         pjsip_tx_data *tdata;
190         /*! \brief Chosen transport */
191         struct ast_sip_transport *transport;
192 };
193
194 /*! \brief Callback function for invoking hooks */
195 static int nat_invoke_hook(void *obj, void *arg, int flags)
196 {
197         struct ast_sip_nat_hook *hook = obj;
198         struct nat_hook_details *details = arg;
199
200         if (hook->outgoing_external_message) {
201                 hook->outgoing_external_message(details->tdata, details->transport);
202         }
203
204         return 0;
205 }
206
207 static pj_status_t nat_on_tx_message(pjsip_tx_data *tdata)
208 {
209         RAII_VAR(struct ao2_container *, transport_states, NULL, ao2_cleanup);
210         RAII_VAR(struct ast_sip_transport *, transport, NULL, ao2_cleanup);
211         RAII_VAR(struct ast_sip_transport_state *, transport_state, NULL, ao2_cleanup);
212         struct request_transport_details details = { 0, };
213         pjsip_via_hdr *via = NULL;
214         struct ast_sockaddr addr = { { 0, } };
215         pjsip_sip_uri *uri = NULL;
216         RAII_VAR(struct ao2_container *, hooks, NULL, ao2_cleanup);
217
218         /* If a transport selector is in use we know the transport or factory, so explicitly find it */
219         if (tdata->tp_sel.type == PJSIP_TPSELECTOR_TRANSPORT) {
220                 details.transport = tdata->tp_sel.u.transport;
221         } else if (tdata->tp_sel.type == PJSIP_TPSELECTOR_LISTENER) {
222                 details.factory = tdata->tp_sel.u.listener;
223         } else if (tdata->tp_info.transport->key.type == PJSIP_TRANSPORT_UDP || tdata->tp_info.transport->key.type == PJSIP_TRANSPORT_UDP6) {
224                 /* Connectionless uses the same transport for all requests */
225                 details.type = AST_TRANSPORT_UDP;
226                 details.transport = tdata->tp_info.transport;
227         } else {
228                 if (tdata->tp_info.transport->key.type == PJSIP_TRANSPORT_TCP) {
229                         details.type = AST_TRANSPORT_TCP;
230                 } else if (tdata->tp_info.transport->key.type == PJSIP_TRANSPORT_TLS) {
231                         details.type = AST_TRANSPORT_TLS;
232                 } else {
233                         /* Unknown transport type, we can't map and thus can't apply NAT changes */
234                         return PJ_SUCCESS;
235                 }
236
237                 if ((uri = nat_get_contact_sip_uri(tdata))) {
238                         details.local_address = uri->host;
239                         details.local_port = uri->port;
240                 } else if ((tdata->msg->type == PJSIP_REQUEST_MSG) &&
241                         (via = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL))) {
242                         details.local_address = via->sent_by.host;
243                         details.local_port = via->sent_by.port;
244                 } else {
245                         return PJ_SUCCESS;
246                 }
247
248                 if (!details.local_port) {
249                         details.local_port = (details.type == AST_TRANSPORT_TLS) ? 5061 : 5060;
250                 }
251         }
252
253         if (!(transport_states = ast_sip_get_transport_states())) {
254                 return PJ_SUCCESS;
255         }
256
257         if (!(transport_state = ao2_callback(transport_states, 0, find_transport_state_in_use, &details))) {
258                 return PJ_SUCCESS;
259         }
260
261         if (!(transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_state->id))) {
262                 return PJ_SUCCESS;
263         }
264
265         if (transport_state->localnet) {
266                 ast_sockaddr_parse(&addr, tdata->tp_info.dst_name, PARSE_PORT_FORBID);
267                 ast_sockaddr_set_port(&addr, tdata->tp_info.dst_port);
268
269                 /* See if where we are sending this request is local or not, and if not that we can get a Contact URI to modify */
270                 if (ast_sip_transport_is_local(transport_state, &addr)) {
271                         ast_debug(5, "Request is being sent to local address, skipping NAT manipulation\n");
272                         return PJ_SUCCESS;
273                 }
274         }
275
276         if (!ast_sockaddr_isnull(&transport_state->external_signaling_address)) {
277                 /* Update the contact header with the external address */
278                 if (uri || (uri = nat_get_contact_sip_uri(tdata))) {
279                         pj_strdup2(tdata->pool, &uri->host, ast_sockaddr_stringify_host(&transport_state->external_signaling_address));
280                         if (transport->external_signaling_port) {
281                                 uri->port = transport->external_signaling_port;
282                                 ast_debug(4, "Re-wrote Contact URI port to %d\n", uri->port);
283                         }
284                 }
285
286                 /* Update the via header if relevant */
287                 if ((tdata->msg->type == PJSIP_REQUEST_MSG) && (via || (via = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL)))) {
288                         pj_strdup2(tdata->pool, &via->sent_by.host, ast_sockaddr_stringify_host(&transport_state->external_signaling_address));
289                         if (transport->external_signaling_port) {
290                                 via->sent_by.port = transport->external_signaling_port;
291                         }
292                 }
293         }
294
295         /* Invoke any additional hooks that may be registered */
296         if ((hooks = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "nat_hook", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL))) {
297                 struct nat_hook_details hook_details = {
298                         .tdata = tdata,
299                         .transport = transport,
300                 };
301                 ao2_callback(hooks, 0, nat_invoke_hook, &hook_details);
302         }
303
304         return PJ_SUCCESS;
305 }
306
307 static pjsip_module nat_module = {
308         .name = { "NAT", 3 },
309         .id = -1,
310         .priority = PJSIP_MOD_PRIORITY_TSX_LAYER - 2,
311         .on_rx_request = nat_on_rx_message,
312         .on_rx_response = nat_on_rx_message,
313         .on_tx_request = nat_on_tx_message,
314         .on_tx_response = nat_on_tx_message,
315 };
316
317 /*! \brief Function called when an INVITE goes out */
318 static int nat_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
319 {
320         if (session->inv_session->state == PJSIP_INV_STATE_INCOMING) {
321                 pjsip_dlg_add_usage(session->inv_session->dlg, &nat_module, NULL);
322         }
323
324         return 0;
325 }
326
327 /*! \brief Function called when an INVITE response comes in */
328 static void nat_incoming_invite_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
329 {
330         handle_rx_message(session->endpoint, rdata);
331 }
332
333 /*! \brief Function called when an INVITE comes in */
334 static void nat_outgoing_invite_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
335 {
336         if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
337                 pjsip_dlg_add_usage(session->inv_session->dlg, &nat_module, NULL);
338         }
339 }
340
341 /*! \brief Supplement for adding NAT functionality to dialog */
342 static struct ast_sip_session_supplement nat_supplement = {
343         .method = "INVITE",
344         .priority = AST_SIP_SUPPLEMENT_PRIORITY_FIRST + 1,
345         .incoming_request = nat_incoming_invite_request,
346         .outgoing_request = nat_outgoing_invite_request,
347         .incoming_response = nat_incoming_invite_response,
348 };
349
350
351 static int unload_module(void)
352 {
353         ast_sip_session_unregister_supplement(&nat_supplement);
354         ast_sip_unregister_service(&nat_module);
355         return 0;
356 }
357
358 static int load_module(void)
359 {
360         if (ast_sip_register_service(&nat_module)) {
361                 ast_log(LOG_ERROR, "Could not register NAT module for incoming and outgoing requests\n");
362                 return AST_MODULE_LOAD_DECLINE;
363         }
364
365         ast_sip_session_register_supplement(&nat_supplement);
366
367         return AST_MODULE_LOAD_SUCCESS;
368 }
369
370 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP NAT Support",
371         .support_level = AST_MODULE_SUPPORT_CORE,
372         .load = load_module,
373         .unload = unload_module,
374         .load_pri = AST_MODPRI_APP_DEPEND,
375         .requires = "res_pjsip,res_pjsip_session",
376 );