Stasis: Update security events to use Stasis
[asterisk/asterisk.git] / res / res_sip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Michelson <mmichelson@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 #include "asterisk.h"
20
21 #include <pjsip.h>
22 /* Needed for SUBSCRIBE, NOTIFY, and PUBLISH method definitions */
23 #include <pjsip_simple.h>
24 #include <pjlib.h>
25
26 #include "asterisk/res_sip.h"
27 #include "res_sip/include/res_sip_private.h"
28 #include "asterisk/linkedlists.h"
29 #include "asterisk/logger.h"
30 #include "asterisk/lock.h"
31 #include "asterisk/utils.h"
32 #include "asterisk/astobj2.h"
33 #include "asterisk/module.h"
34 #include "asterisk/threadpool.h"
35 #include "asterisk/taskprocessor.h"
36 #include "asterisk/uuid.h"
37 #include "asterisk/sorcery.h"
38
39 /*** MODULEINFO
40         <depend>pjproject</depend>
41         <depend>res_sorcery_config</depend>
42         <support_level>core</support_level>
43  ***/
44
45 static pjsip_endpoint *ast_pjsip_endpoint;
46
47 static struct ast_threadpool *sip_threadpool;
48
49 static int register_service(void *data)
50 {
51         pjsip_module **module = data;
52         if (!ast_pjsip_endpoint) {
53                 ast_log(LOG_ERROR, "There is no PJSIP endpoint. Unable to register services\n");
54                 return -1;
55         }
56         if (pjsip_endpt_register_module(ast_pjsip_endpoint, *module) != PJ_SUCCESS) {
57                 ast_log(LOG_ERROR, "Unable to register module %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
58                 return -1;
59         }
60         ast_debug(1, "Registered SIP service %.*s (%p)\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name), *module);
61         ast_module_ref(ast_module_info->self);
62         return 0;
63 }
64
65 int ast_sip_register_service(pjsip_module *module)
66 {
67         return ast_sip_push_task_synchronous(NULL, register_service, &module);
68 }
69
70 static int unregister_service(void *data)
71 {
72         pjsip_module **module = data;
73         ast_module_unref(ast_module_info->self);
74         if (!ast_pjsip_endpoint) {
75                 return -1;
76         }
77         pjsip_endpt_unregister_module(ast_pjsip_endpoint, *module);
78         ast_debug(1, "Unregistered SIP service %.*s\n", (int) pj_strlen(&(*module)->name), pj_strbuf(&(*module)->name));
79         return 0;
80 }
81
82 void ast_sip_unregister_service(pjsip_module *module)
83 {
84         ast_sip_push_task_synchronous(NULL, unregister_service, &module);
85 }
86
87 static struct ast_sip_authenticator *registered_authenticator;
88
89 int ast_sip_register_authenticator(struct ast_sip_authenticator *auth)
90 {
91         if (registered_authenticator) {
92                 ast_log(LOG_WARNING, "Authenticator %p is already registered. Cannot register a new one\n", registered_authenticator);
93                 return -1;
94         }
95         registered_authenticator = auth;
96         ast_debug(1, "Registered SIP authenticator module %p\n", auth);
97         ast_module_ref(ast_module_info->self);
98         return 0;
99 }
100
101 void ast_sip_unregister_authenticator(struct ast_sip_authenticator *auth)
102 {
103         if (registered_authenticator != auth) {
104                 ast_log(LOG_WARNING, "Trying to unregister authenticator %p but authenticator %p registered\n",
105                                 auth, registered_authenticator);
106                 return;
107         }
108         registered_authenticator = NULL;
109         ast_debug(1, "Unregistered SIP authenticator %p\n", auth);
110         ast_module_unref(ast_module_info->self);
111 }
112
113 int ast_sip_requires_authentication(struct ast_sip_endpoint *endpoint, pjsip_rx_data *rdata)
114 {
115         if (!registered_authenticator) {
116                 ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is not required\n");
117                 return 0;
118         }
119
120         return registered_authenticator->requires_authentication(endpoint, rdata);
121 }
122
123 enum ast_sip_check_auth_result ast_sip_check_authentication(struct ast_sip_endpoint *endpoint,
124                 pjsip_rx_data *rdata, pjsip_tx_data *tdata)
125 {
126         if (!registered_authenticator) {
127                 ast_log(LOG_WARNING, "No SIP authenticator registered. Assuming authentication is successful\n");
128                 return 0;
129         }
130         return registered_authenticator->check_authentication(endpoint, rdata, tdata);
131 }
132
133 static struct ast_sip_outbound_authenticator *registered_outbound_authenticator;
134
135 int ast_sip_register_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
136 {
137         if (registered_outbound_authenticator) {
138                 ast_log(LOG_WARNING, "Outbound authenticator %p is already registered. Cannot register a new one\n", registered_outbound_authenticator);
139                 return -1;
140         }
141         registered_outbound_authenticator = auth;
142         ast_debug(1, "Registered SIP outbound authenticator module %p\n", auth);
143         ast_module_ref(ast_module_info->self);
144         return 0;
145 }
146
147 void ast_sip_unregister_outbound_authenticator(struct ast_sip_outbound_authenticator *auth)
148 {
149         if (registered_outbound_authenticator != auth) {
150                 ast_log(LOG_WARNING, "Trying to unregister outbound authenticator %p but outbound authenticator %p registered\n",
151                                 auth, registered_outbound_authenticator);
152                 return;
153         }
154         registered_outbound_authenticator = NULL;
155         ast_debug(1, "Unregistered SIP outbound authenticator %p\n", auth);
156         ast_module_unref(ast_module_info->self);
157 }
158
159 int ast_sip_create_request_with_auth(const char **auths, size_t num_auths, pjsip_rx_data *challenge,
160                 pjsip_transaction *tsx, pjsip_tx_data **new_request)
161 {
162         if (!registered_outbound_authenticator) {
163                 ast_log(LOG_WARNING, "No SIP outbound authenticator registered. Cannot respond to authentication challenge\n");
164                 return -1;
165         }
166         return registered_outbound_authenticator->create_request_with_auth(auths, num_auths, challenge, tsx, new_request);
167 }
168
169 struct endpoint_identifier_list {
170         struct ast_sip_endpoint_identifier *identifier;
171         AST_RWLIST_ENTRY(endpoint_identifier_list) list;
172 };
173
174 static AST_RWLIST_HEAD_STATIC(endpoint_identifiers, endpoint_identifier_list);
175
176 int ast_sip_register_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
177 {
178         struct endpoint_identifier_list *id_list_item;
179         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
180
181         id_list_item = ast_calloc(1, sizeof(*id_list_item));
182         if (!id_list_item) {
183                 ast_log(LOG_ERROR, "Unabled to add endpoint identifier. Out of memory.\n");
184                 return -1;
185         }
186         id_list_item->identifier = identifier;
187
188         AST_RWLIST_INSERT_TAIL(&endpoint_identifiers, id_list_item, list);
189         ast_debug(1, "Registered endpoint identifier %p\n", identifier);
190
191         ast_module_ref(ast_module_info->self);
192         return 0;
193 }
194
195 void ast_sip_unregister_endpoint_identifier(struct ast_sip_endpoint_identifier *identifier)
196 {
197         struct endpoint_identifier_list *iter;
198         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
199         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&endpoint_identifiers, iter, list) {
200                 if (iter->identifier == identifier) {
201                         AST_RWLIST_REMOVE_CURRENT(list);
202                         ast_free(iter);
203                         ast_debug(1, "Unregistered endpoint identifier %p\n", identifier);
204                         ast_module_unref(ast_module_info->self);
205                         break;
206                 }
207         }
208         AST_RWLIST_TRAVERSE_SAFE_END;
209 }
210
211 struct ast_sip_endpoint *ast_sip_identify_endpoint(pjsip_rx_data *rdata)
212 {
213         struct endpoint_identifier_list *iter;
214         struct ast_sip_endpoint *endpoint = NULL;
215         SCOPED_LOCK(lock, &endpoint_identifiers, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
216         AST_RWLIST_TRAVERSE(&endpoint_identifiers, iter, list) {
217                 ast_assert(iter->identifier->identify_endpoint != NULL);
218                 endpoint = iter->identifier->identify_endpoint(rdata);
219                 if (endpoint) {
220                         break;
221                 }
222         }
223         return endpoint;
224 }
225
226 pjsip_endpoint *ast_sip_get_pjsip_endpoint(void)
227 {
228         return ast_pjsip_endpoint;
229 }
230
231 static int sip_dialog_create_from(pj_pool_t *pool, pj_str_t *from, const char *user, const pj_str_t *target, pjsip_tpselector *selector)
232 {
233         pj_str_t tmp, local_addr;
234         pjsip_uri *uri;
235         pjsip_sip_uri *sip_uri;
236         pjsip_transport_type_e type = PJSIP_TRANSPORT_UNSPECIFIED;
237         int local_port;
238         char uuid_str[AST_UUID_STR_LEN];
239
240         if (!user) {
241                 RAII_VAR(struct ast_uuid *, uuid, ast_uuid_generate(), ast_free_ptr);
242                 if (!uuid) {
243                         return -1;
244                 }
245                 user = ast_uuid_to_str(uuid, uuid_str, sizeof(uuid_str));
246         }
247
248         /* Parse the provided target URI so we can determine what transport it will end up using */
249         pj_strdup_with_null(pool, &tmp, target);
250
251         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
252             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
253                 return -1;
254         }
255
256         sip_uri = pjsip_uri_get_uri(uri);
257
258         /* Determine the transport type to use */
259         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
260                 type = PJSIP_TRANSPORT_TLS;
261         } else if (!sip_uri->transport_param.slen) {
262                 type = PJSIP_TRANSPORT_UDP;
263         } else {
264                 type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
265         }
266
267         if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
268                 return -1;
269         }
270
271         /* If the host is IPv6 turn the transport into an IPv6 version */
272         if (pj_strchr(&sip_uri->host, ':')) {
273                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
274         }
275
276         /* Get the local bound address for the transport that will be used when communicating with the provided URI */
277         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()), pool, type, selector,
278                                                               &local_addr, &local_port) != PJ_SUCCESS) {
279                 return -1;
280         }
281
282         /* If IPv6 was not specified in the host but is in the transport, set the proper type */
283         if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
284                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
285         }
286
287         from->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
288         from->slen = pj_ansi_snprintf(from->ptr, PJSIP_MAX_URL_SIZE,
289                                       "<%s:%s@%s%.*s%s:%d%s%s>",
290                                       (pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) ? "sips" : "sip",
291                                       user,
292                                       (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
293                                       (int)local_addr.slen,
294                                       local_addr.ptr,
295                                       (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
296                                       local_port,
297                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
298                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
299
300         return 0;
301 }
302
303 static int sip_get_tpselector_from_endpoint(const struct ast_sip_endpoint *endpoint, pjsip_tpselector *selector)
304 {
305         RAII_VAR(struct ast_sip_transport *, transport, NULL, ao2_cleanup);
306         const char *transport_name = endpoint->transport;
307
308         if (ast_strlen_zero(transport_name)) {
309                 return 0;
310         }
311
312         transport = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", transport_name);
313
314         if (!transport || !transport->state) {
315                 return -1;
316         }
317
318         if (transport->type == AST_TRANSPORT_UDP) {
319                 selector->type = PJSIP_TPSELECTOR_TRANSPORT;
320                 selector->u.transport = transport->state->transport;
321         } else if (transport->type == AST_TRANSPORT_TCP || transport->type == AST_TRANSPORT_TLS) {
322                 selector->type = PJSIP_TPSELECTOR_LISTENER;
323                 selector->u.listener = transport->state->factory;
324         } else {
325                 return -1;
326         }
327
328         return 0;
329 }
330
331 pjsip_dialog *ast_sip_create_dialog(const struct ast_sip_endpoint *endpoint, const char *uri, const char *request_user)
332 {
333         pj_str_t local_uri = { "sip:temp@temp", 13 }, remote_uri;
334         pjsip_dialog *dlg = NULL;
335         const char *outbound_proxy = endpoint->outbound_proxy;
336         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
337         static const pj_str_t HCONTACT = { "Contact", 7 };
338
339         pj_cstr(&remote_uri, uri);
340
341         if (pjsip_dlg_create_uac(pjsip_ua_instance(), &local_uri, NULL, &remote_uri, NULL, &dlg) != PJ_SUCCESS) {
342                 return NULL;
343         }
344
345         if (sip_get_tpselector_from_endpoint(endpoint, &selector)) {
346                 pjsip_dlg_terminate(dlg);
347                 return NULL;
348         }
349
350         if (sip_dialog_create_from(dlg->pool, &local_uri, NULL, &remote_uri, &selector)) {
351                 pjsip_dlg_terminate(dlg);
352                 return NULL;
353         }
354
355         /* Update the dialog with the new local URI, we do it afterwards so we can use the dialog pool for construction */
356         pj_strdup_with_null(dlg->pool, &dlg->local.info_str, &local_uri);
357         dlg->local.info->uri = pjsip_parse_uri(dlg->pool, dlg->local.info_str.ptr, dlg->local.info_str.slen, 0);
358         dlg->local.contact = pjsip_parse_hdr(dlg->pool, &HCONTACT, local_uri.ptr, local_uri.slen, NULL);
359
360         /* If a request user has been specified and we are permitted to change it, do so */
361         if (!ast_strlen_zero(request_user) && (PJSIP_URI_SCHEME_IS_SIP(dlg->target) || PJSIP_URI_SCHEME_IS_SIPS(dlg->target))) {
362                 pjsip_sip_uri *target = pjsip_uri_get_uri(dlg->target);
363                 pj_strdup2(dlg->pool, &target->user, request_user);
364         }
365
366         /* We have to temporarily bump up the sess_count here so the dialog is not prematurely destroyed */
367         dlg->sess_count++;
368
369         pjsip_dlg_set_transport(dlg, &selector);
370
371         if (!ast_strlen_zero(outbound_proxy)) {
372                 pjsip_route_hdr route_set, *route;
373                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
374                 pj_str_t tmp;
375
376                 pj_list_init(&route_set);
377
378                 pj_strdup2_with_null(dlg->pool, &tmp, outbound_proxy);
379                 if (!(route = pjsip_parse_hdr(dlg->pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
380                         pjsip_dlg_terminate(dlg);
381                         return NULL;
382                 }
383                 pj_list_push_back(&route_set, route);
384
385                 pjsip_dlg_set_route_set(dlg, &route_set);
386         }
387
388         dlg->sess_count--;
389
390         return dlg;
391 }
392
393 /* PJSIP doesn't know about the INFO method, so we have to define it ourselves */
394 const pjsip_method pjsip_info_method = {PJSIP_OTHER_METHOD, {"INFO", 4} };
395
396 static struct {
397         const char *method;
398         const pjsip_method *pmethod;
399 } methods [] = {
400         { "INVITE", &pjsip_invite_method },
401         { "CANCEL", &pjsip_cancel_method },
402         { "ACK", &pjsip_ack_method },
403         { "BYE", &pjsip_bye_method },
404         { "REGISTER", &pjsip_register_method },
405         { "OPTIONS", &pjsip_options_method },
406         { "SUBSCRIBE", &pjsip_subscribe_method },
407         { "NOTIFY", &pjsip_notify_method },
408         { "PUBLISH", &pjsip_publish_method },
409         { "INFO", &pjsip_info_method },
410 };
411
412 static const pjsip_method *get_pjsip_method(const char *method)
413 {
414         int i;
415         for (i = 0; i < ARRAY_LEN(methods); ++i) {
416                 if (!strcmp(method, methods[i].method)) {
417                         return methods[i].pmethod;
418                 }
419         }
420         return NULL;
421 }
422
423 static int create_in_dialog_request(const pjsip_method *method, struct pjsip_dialog *dlg, pjsip_tx_data **tdata)
424 {
425         if (pjsip_dlg_create_request(dlg, method, -1, tdata) != PJ_SUCCESS) {
426                 ast_log(LOG_WARNING, "Unable to create in-dialog request.\n");
427                 return -1;
428         }
429
430         return 0;
431 }
432
433 static int create_out_of_dialog_request(const pjsip_method *method, struct ast_sip_endpoint *endpoint,
434                 const char *uri, pjsip_tx_data **tdata)
435 {
436         RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
437         pj_str_t remote_uri;
438         pj_str_t from;
439         pj_pool_t *pool;
440         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
441
442         if (ast_strlen_zero(uri)) {
443                 contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
444                 if (!contact || ast_strlen_zero(contact->uri)) {
445                         ast_log(LOG_ERROR, "Unable to retrieve contact for endpoint %s\n",
446                                         ast_sorcery_object_get_id(endpoint));
447                         return -1;
448                 }
449
450                 pj_cstr(&remote_uri, contact->uri);
451         } else {
452                 pj_cstr(&remote_uri, uri);
453         }
454
455         if (sip_get_tpselector_from_endpoint(endpoint, &selector)) {
456                 ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport selector for endpoint %s\n",
457                                 ast_sorcery_object_get_id(endpoint));
458                 return -1;
459         }
460
461         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Outbound request", 256, 256);
462
463         if (!pool) {
464                 ast_log(LOG_ERROR, "Unable to create PJLIB memory pool\n");
465                 return -1;
466         }
467
468         if (sip_dialog_create_from(pool, &from, NULL, &remote_uri, &selector)) {
469                 ast_log(LOG_ERROR, "Unable to create From header for %.*s request to endpoint %s\n",
470                                 (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
471                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
472                 return -1;
473         }
474
475         if (pjsip_endpt_create_request(ast_sip_get_pjsip_endpoint(), method, &remote_uri,
476                         &from, &remote_uri, &from, NULL, -1, NULL, tdata) != PJ_SUCCESS) {
477                 ast_log(LOG_ERROR, "Unable to create outbound %.*s request to endpoint %s\n",
478                                 (int) pj_strlen(&method->name), pj_strbuf(&method->name), ast_sorcery_object_get_id(endpoint));
479                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
480                 return -1;
481         }
482
483         /* We can release this pool since request creation copied all the necessary
484          * data into the outbound request's pool
485          */
486         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
487         return 0;
488 }
489
490 int ast_sip_create_request(const char *method, struct pjsip_dialog *dlg,
491                 struct ast_sip_endpoint *endpoint, const char *uri, pjsip_tx_data **tdata)
492 {
493         const pjsip_method *pmethod = get_pjsip_method(method);
494
495         if (!pmethod) {
496                 ast_log(LOG_WARNING, "Unknown method '%s'. Cannot send request\n", method);
497                 return -1;
498         }
499
500         if (dlg) {
501                 return create_in_dialog_request(pmethod, dlg, tdata);
502         } else {
503                 return create_out_of_dialog_request(pmethod, endpoint, uri, tdata);
504         }
505 }
506
507 static int send_in_dialog_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg)
508 {
509         if (pjsip_dlg_send_request(dlg, tdata, -1, NULL) != PJ_SUCCESS) {
510                 ast_log(LOG_WARNING, "Unable to send in-dialog request.\n");
511                 return -1;
512         }
513         return 0;
514 }
515
516 static void send_request_cb(void *token, pjsip_event *e)
517 {
518         RAII_VAR(struct ast_sip_endpoint *, endpoint, token, ao2_cleanup);
519         pjsip_transaction *tsx = e->body.tsx_state.tsx;
520         pjsip_rx_data *challenge = e->body.tsx_state.src.rdata;
521         pjsip_tx_data *tdata;
522
523         if (tsx->status_code != 401 && tsx->status_code != 407) {
524                 return;
525         }
526
527         if (!ast_sip_create_request_with_auth(endpoint->sip_outbound_auths, endpoint->num_outbound_auths, challenge, tsx, &tdata)) {
528                 pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata, -1, NULL, NULL);
529         }
530 }
531
532 static int send_out_of_dialog_request(pjsip_tx_data *tdata, struct ast_sip_endpoint *endpoint)
533 {
534         ao2_ref(endpoint, +1);
535         if (pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata, -1, endpoint, send_request_cb) != PJ_SUCCESS) {
536                 ast_log(LOG_ERROR, "Error attempting to send outbound %.*s request to endpoint %s\n",
537                                 (int) pj_strlen(&tdata->msg->line.req.method.name),
538                                 pj_strbuf(&tdata->msg->line.req.method.name),
539                                 ast_sorcery_object_get_id(endpoint));
540                 ao2_ref(endpoint, -1);
541                 return -1;
542         }
543
544         return 0;
545 }
546
547 int ast_sip_send_request(pjsip_tx_data *tdata, struct pjsip_dialog *dlg, struct ast_sip_endpoint *endpoint)
548 {
549         ast_assert(tdata->msg->type == PJSIP_REQUEST_MSG);
550
551         if (dlg) {
552                 return send_in_dialog_request(tdata, dlg);
553         } else {
554                 return send_out_of_dialog_request(tdata, endpoint);
555         }
556 }
557
558 int ast_sip_add_header(pjsip_tx_data *tdata, const char *name, const char *value)
559 {
560         pj_str_t hdr_name;
561         pj_str_t hdr_value;
562         pjsip_generic_string_hdr *hdr;
563         
564         pj_cstr(&hdr_name, name);
565         pj_cstr(&hdr_value, value);
566
567         hdr = pjsip_generic_string_hdr_create(tdata->pool, &hdr_name, &hdr_value);
568
569         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *) hdr);
570         return 0;
571 }
572
573 static pjsip_msg_body *ast_body_to_pjsip_body(pj_pool_t *pool, const struct ast_sip_body *body)
574 {
575         pj_str_t type;
576         pj_str_t subtype;
577         pj_str_t body_text;
578
579         pj_cstr(&type, body->type);
580         pj_cstr(&subtype, body->subtype);
581         pj_cstr(&body_text, body->body_text);
582         
583         return pjsip_msg_body_create(pool, &type, &subtype, &body_text);
584 }
585
586 int ast_sip_add_body(pjsip_tx_data *tdata, const struct ast_sip_body *body)
587 {
588         pjsip_msg_body *pjsip_body = ast_body_to_pjsip_body(tdata->pool, body);
589         tdata->msg->body = pjsip_body;
590         return 0;
591 }
592
593 int ast_sip_add_body_multipart(pjsip_tx_data *tdata, const struct ast_sip_body *bodies[], int num_bodies)
594 {
595         int i;
596         /* NULL for type and subtype automatically creates "multipart/mixed" */
597         pjsip_msg_body *body = pjsip_multipart_create(tdata->pool, NULL, NULL);
598
599         for (i = 0; i < num_bodies; ++i) {
600                 pjsip_multipart_part *part = pjsip_multipart_create_part(tdata->pool);
601                 part->body = ast_body_to_pjsip_body(tdata->pool, bodies[i]);
602                 pjsip_multipart_add_part(tdata->pool, body, part);
603         }
604
605         tdata->msg->body = body;
606         return 0;
607 }
608
609 int ast_sip_append_body(pjsip_tx_data *tdata, const char *body_text)
610 {
611         size_t combined_size = strlen(body_text) + tdata->msg->body->len;
612         struct ast_str *body_buffer = ast_str_alloca(combined_size);
613
614         ast_str_set(&body_buffer, 0, "%.*s%s", (int) tdata->msg->body->len, (char *) tdata->msg->body->data, body_text);
615
616         tdata->msg->body->data = pj_pool_alloc(tdata->pool, combined_size);
617         pj_memcpy(tdata->msg->body->data, ast_str_buffer(body_buffer), combined_size);
618         tdata->msg->body->len = combined_size;
619
620         return 0;
621 }
622
623 struct ast_taskprocessor *ast_sip_create_serializer(void)
624 {
625         struct ast_taskprocessor *serializer;
626         RAII_VAR(struct ast_uuid *, uuid, ast_uuid_generate(), ast_free_ptr);
627         char name[AST_UUID_STR_LEN];
628
629         if (!uuid) {
630                 return NULL;
631         }
632
633         ast_uuid_to_str(uuid, name, sizeof(name));
634
635         serializer = ast_threadpool_serializer(name, sip_threadpool);
636         if (!serializer) {
637                 return NULL;
638         }
639         return serializer;
640 }
641
642 int ast_sip_push_task(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
643 {
644         if (serializer) {
645                 return ast_taskprocessor_push(serializer, sip_task, task_data);
646         } else {
647                 return ast_threadpool_push(sip_threadpool, sip_task, task_data);
648         }
649 }
650
651 struct sync_task_data {
652         ast_mutex_t lock;
653         ast_cond_t cond;
654         int complete;
655         int fail;
656         int (*task)(void *);
657         void *task_data;
658 };
659
660 static int sync_task(void *data)
661 {
662         struct sync_task_data *std = data;
663         std->fail = std->task(std->task_data);
664
665         ast_mutex_lock(&std->lock);
666         std->complete = 1;
667         ast_cond_signal(&std->cond);
668         ast_mutex_unlock(&std->lock);
669         return std->fail;
670 }
671
672 int ast_sip_push_task_synchronous(struct ast_taskprocessor *serializer, int (*sip_task)(void *), void *task_data)
673 {
674         /* This method is an onion */
675         struct sync_task_data std;
676         ast_mutex_init(&std.lock);
677         ast_cond_init(&std.cond, NULL);
678         std.fail = std.complete = 0;
679         std.task = sip_task;
680         std.task_data = task_data;
681
682         if (serializer) {
683                 if (ast_taskprocessor_push(serializer, sync_task, &std)) {
684                         return -1;
685                 }
686         } else {
687                 if (ast_threadpool_push(sip_threadpool, sync_task, &std)) {
688                         return -1;
689                 }
690         }
691
692         ast_mutex_lock(&std.lock);
693         while (!std.complete) {
694                 ast_cond_wait(&std.cond, &std.lock);
695         }
696         ast_mutex_unlock(&std.lock);
697
698         ast_mutex_destroy(&std.lock);
699         ast_cond_destroy(&std.cond);
700         return std.fail;
701 }
702
703 void ast_copy_pj_str(char *dest, pj_str_t *src, size_t size)
704 {
705         size_t chars_to_copy = MIN(size - 1, pj_strlen(src));
706         memcpy(dest, pj_strbuf(src), chars_to_copy);
707         dest[chars_to_copy] = '\0';
708 }
709
710 pj_caching_pool caching_pool;
711 pj_pool_t *memory_pool;
712 pj_thread_t *monitor_thread;
713 static int monitor_continue;
714
715 static void *monitor_thread_exec(void *endpt)
716 {
717         while (monitor_continue) {
718                 const pj_time_val delay = {0, 10};
719                 pjsip_endpt_handle_events(ast_pjsip_endpoint, &delay);
720         }
721         return NULL;
722 }
723
724 static void stop_monitor_thread(void)
725 {
726         monitor_continue = 0;
727         pj_thread_join(monitor_thread);
728 }
729
730 AST_THREADSTORAGE(pj_thread_storage);
731 AST_THREADSTORAGE(servant_id_storage);
732 #define SIP_SERVANT_ID 0xDEFECA7E
733
734 static void sip_thread_start(void)
735 {
736         pj_thread_desc *desc;
737         pj_thread_t *thread;
738         uint32_t *servant_id;
739
740         servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
741         if (!servant_id) {
742                 ast_log(LOG_ERROR, "Could not set SIP servant ID in thread-local storage.\n");
743                 return;
744         }
745         *servant_id = SIP_SERVANT_ID;
746
747         desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
748         if (!desc) {
749                 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
750                 return;
751         }
752         pj_bzero(*desc, sizeof(*desc));
753
754         if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
755                 ast_log(LOG_ERROR, "Couldn't register thread with PJLIB.\n");
756         }
757 }
758
759 int ast_sip_thread_is_servant(void)
760 {
761         uint32_t *servant_id;
762
763         servant_id = ast_threadstorage_get(&servant_id_storage, sizeof(*servant_id));
764         if (!servant_id) {
765                 return 0;
766         }
767
768         return *servant_id == SIP_SERVANT_ID;
769 }
770
771 static int load_module(void)
772 {
773     /* The third parameter is just copied from
774      * example code from PJLIB. This can be adjusted
775      * if necessary.
776          */
777         pj_status_t status;
778
779         /* XXX For the time being, create hard-coded threadpool
780          * options. Just bump up by five threads every time we
781          * don't have any available threads. Idle threads time
782          * out after a minute. No maximum size
783          */
784         struct ast_threadpool_options options = {
785                 .version = AST_THREADPOOL_OPTIONS_VERSION,
786                 .auto_increment = 5,
787                 .max_size = 0,
788                 .idle_timeout = 60,
789                 .initial_size = 0,
790                 .thread_start = sip_thread_start,
791         };
792         sip_threadpool = ast_threadpool_create("SIP", NULL, &options);
793
794         if (pj_init() != PJ_SUCCESS) {
795                 return AST_MODULE_LOAD_DECLINE;
796         }
797
798         if (pjlib_util_init() != PJ_SUCCESS) {
799                 pj_shutdown();
800                 return AST_MODULE_LOAD_DECLINE;
801         }
802
803         pj_caching_pool_init(&caching_pool, NULL, 1024 * 1024);
804         if (pjsip_endpt_create(&caching_pool.factory, "SIP", &ast_pjsip_endpoint) != PJ_SUCCESS) {
805                 ast_log(LOG_ERROR, "Failed to create PJSIP endpoint structure. Aborting load\n");
806                 goto error;
807         }
808         memory_pool = pj_pool_create(&caching_pool.factory, "SIP", 1024, 1024, NULL);
809         if (!memory_pool) {
810                 ast_log(LOG_ERROR, "Failed to create memory pool for SIP. Aborting load\n");
811                 goto error;
812         }
813
814         pjsip_tsx_layer_init_module(ast_pjsip_endpoint);
815         pjsip_ua_init_module(ast_pjsip_endpoint, NULL);
816
817         monitor_continue = 1;
818         status = pj_thread_create(memory_pool, "SIP", (pj_thread_proc *) &monitor_thread_exec,
819                         NULL, PJ_THREAD_DEFAULT_STACK_SIZE * 2, 0, &monitor_thread);
820         if (status != PJ_SUCCESS) {
821                 ast_log(LOG_ERROR, "Failed to start SIP monitor thread. Aborting load\n");
822                 goto error;
823         }
824
825         if (ast_res_sip_initialize_configuration()) {
826                 ast_log(LOG_ERROR, "Failed to initialize SIP configuration. Aborting load\n");
827                 goto error;
828         }
829
830         if (ast_sip_initialize_distributor()) {
831                 ast_log(LOG_ERROR, "Failed to register distributor module. Aborting load\n");
832                 goto error;
833         }
834
835         if (ast_sip_initialize_outbound_authentication()) {
836                 ast_log(LOG_ERROR, "Failed to initialize outbound authentication. Aborting load\n");
837                 goto error;
838         }
839
840         ast_res_sip_init_options_handling(0);
841
842 return AST_MODULE_LOAD_SUCCESS;
843
844 error:
845         ast_res_sip_destroy_configuration();
846         if (monitor_thread) {
847                 stop_monitor_thread();
848         }
849         if (memory_pool) {
850                 pj_pool_release(memory_pool);
851                 memory_pool = NULL;
852         }
853         if (ast_pjsip_endpoint) {
854                 pjsip_endpt_destroy(ast_pjsip_endpoint);
855                 ast_pjsip_endpoint = NULL;
856         }
857         pj_caching_pool_destroy(&caching_pool);
858         /* XXX Should have a way of stopping monitor thread */
859         return AST_MODULE_LOAD_DECLINE;
860 }
861
862 static int reload_module(void)
863 {
864         if (ast_res_sip_reload_configuration()) {
865                 return AST_MODULE_LOAD_DECLINE;
866         }
867         ast_res_sip_init_options_handling(1);
868         return 0;
869 }
870
871 static int unload_pjsip(void *data)
872 {
873         if (memory_pool) {
874                 pj_pool_release(memory_pool);
875                 memory_pool = NULL;
876         }
877         if (ast_pjsip_endpoint) {
878                 pjsip_endpt_destroy(ast_pjsip_endpoint);
879                 ast_pjsip_endpoint = NULL;
880         }
881         pj_caching_pool_destroy(&caching_pool);
882         return 0;
883 }
884
885 static int unload_module(void)
886 {
887         ast_res_sip_destroy_configuration();
888         if (monitor_thread) {
889                 stop_monitor_thread();
890         }
891         /* The thread this is called from cannot call PJSIP/PJLIB functions,
892          * so we have to push the work to the threadpool to handle
893          */
894         ast_sip_push_task_synchronous(NULL, unload_pjsip, NULL);
895
896         ast_threadpool_shutdown(sip_threadpool);
897
898         return 0;
899 }
900
901 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Basic SIP resource",
902                 .load = load_module,
903                 .unload = unload_module,
904                 .reload = reload_module,
905                 .load_pri = AST_MODPRI_CHANNEL_DEPEND - 5,
906 );