Fix crash in res_pjsip_outbound_registration when the remote server can not be resolved.
[asterisk/asterisk.git] / res / res_pjsip_outbound_registration.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/module.h"
32 #include "asterisk/taskprocessor.h"
33 #include "asterisk/cli.h"
34 #include "asterisk/stasis_system.h"
35
36 /*** DOCUMENTATION
37         <configInfo name="res_pjsip_outbound_registration" language="en_US">
38                 <synopsis>SIP resource for outbound registrations</synopsis>
39                 <description><para>
40                         <emphasis>Outbound Registration</emphasis>
41                         </para>
42                         <para>This module allows <literal>res_pjsip</literal> to register to other SIP servers.</para>
43                 </description>
44                 <configFile name="pjsip.conf">
45                         <configObject name="registration">
46                                 <synopsis>The configuration for outbound registration</synopsis>
47                                 <description><para>
48                                         Registration is <emphasis>COMPLETELY</emphasis> separate from the rest of
49                                         <literal>pjsip.conf</literal>. A minimal configuration consists of
50                                         setting a <literal>server_uri</literal> and a <literal>client_uri</literal>.
51                                 </para></description>
52                                 <configOption name="auth_rejection_permanent" default="yes">
53                                         <synopsis>Determines whether failed authentication challenges are treated
54                                         as permanent failures.</synopsis>
55                                         <description><para>If this option is enabled and an authentication challenge fails,
56                                         registration will not be attempted again until the configuration is reloaded.</para></description>
57                                 </configOption>
58                                 <configOption name="client_uri">
59                                         <synopsis>Client SIP URI used when attemping outbound registration</synopsis>
60                                 </configOption>
61                                 <configOption name="contact_user">
62                                         <synopsis>Contact User to use in request</synopsis>
63                                 </configOption>
64                                 <configOption name="expiration" default="3600">
65                                         <synopsis>Expiration time for registrations in seconds</synopsis>
66                                 </configOption>
67                                 <configOption name="max_retries" default="10">
68                                         <synopsis>Maximum number of registration attempts.</synopsis>
69                                 </configOption>
70                                 <configOption name="outbound_auth" default="">
71                                         <synopsis>Authentication object to be used for outbound registrations.</synopsis>
72                                 </configOption>
73                                 <configOption name="outbound_proxy" default="">
74                                         <synopsis>Outbound Proxy used to send registrations</synopsis>
75                                 </configOption>
76                                 <configOption name="retry_interval" default="60">
77                                         <synopsis>Interval in seconds between retries if outbound registration is unsuccessful</synopsis>
78                                 </configOption>
79                                 <configOption name="server_uri">
80                                         <synopsis>SIP URI of the server to register against</synopsis>
81                                 </configOption>
82                                 <configOption name="transport">
83                                         <synopsis>Transport used for outbound authentication</synopsis>
84                                         <description>
85                                                 <note><para>A <replaceable>transport</replaceable> configured in
86                                                 <literal>pjsip.conf</literal>. As with other <literal>res_pjsip</literal> modules, this will use the first available transport of the appropriate type if unconfigured.</para></note>
87                                         </description>
88                                 </configOption>
89                                 <configOption name="type">
90                                         <synopsis>Must be of type 'registration'.</synopsis>
91                                 </configOption>
92                         </configObject>
93                 </configFile>
94         </configInfo>
95         <manager name="PJSIPUnregister" language="en_US">
96                 <synopsis>
97                         Unregister an outbound registration.
98                 </synopsis>
99                 <syntax>
100                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
101                         <parameter name="Registration" required="true">
102                                 <para>The outbound registration to unregister.</para>
103                         </parameter>
104                 </syntax>
105         </manager>
106  ***/
107
108 /*! \brief Amount of buffer time (in seconds) before expiration that we re-register at */
109 #define REREGISTER_BUFFER_TIME 10
110
111 /*! \brief Various states that an outbound registration may be in */
112 enum sip_outbound_registration_status {
113         /*! \brief Currently unregistered */
114         SIP_REGISTRATION_UNREGISTERED = 0,
115         /*! \brief Registered, yay! */
116         SIP_REGISTRATION_REGISTERED,
117         /*! \brief Registration was rejected, but response was temporal */
118         SIP_REGISTRATION_REJECTED_TEMPORARY,
119         /*! \brief Registration was rejected, permanently */
120         SIP_REGISTRATION_REJECTED_PERMANENT,
121         /*! \brief Registration has been stopped */
122         SIP_REGISTRATION_STOPPED,
123 };
124
125 static const char *sip_outbound_registration_status_str[] = {
126         [SIP_REGISTRATION_UNREGISTERED] = "Unregistered",
127         [SIP_REGISTRATION_REGISTERED] = "Registered",
128         [SIP_REGISTRATION_REJECTED_TEMPORARY] = "Rejected",
129         [SIP_REGISTRATION_REJECTED_PERMANENT] = "Rejected",
130         [SIP_REGISTRATION_STOPPED] = "Stopped",
131 };
132
133 /*! \brief Outbound registration client state information (persists for lifetime of regc) */
134 struct sip_outbound_registration_client_state {
135         /*! \brief Current status of this registration */
136         enum sip_outbound_registration_status status;
137         /*! \brief Outbound registration client */
138         pjsip_regc *client;
139         /*! \brief Timer entry for retrying on temporal responses */
140         pj_timer_entry timer;
141         /*! \brief Current number of retries */
142         unsigned int retries;
143         /*! \brief Maximum number of retries permitted */
144         unsigned int max_retries;
145         /*! \brief Interval at which retries should occur for temporal responses */
146         unsigned int retry_interval;
147         /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
148         unsigned int auth_rejection_permanent;
149         /*! \brief Serializer for stuff and things */
150         struct ast_taskprocessor *serializer;
151         /*! \brief Configured authentication credentials */
152         struct ast_sip_auth_array outbound_auths;
153         /*! \brief Number of configured auths */
154         size_t num_outbound_auths;
155         /*! \brief Registration should be destroyed after completion of transaction */
156         unsigned int destroy:1;
157 };
158
159 /*! \brief Outbound registration state information (persists for lifetime that registration should exist) */
160 struct sip_outbound_registration_state {
161         /*! \brief Client state information */
162         struct sip_outbound_registration_client_state *client_state;
163 };
164
165 /*! \brief Outbound registration information */
166 struct sip_outbound_registration {
167         /*! \brief Sorcery object details */
168         SORCERY_OBJECT(details);
169         /*! \brief Stringfields */
170         AST_DECLARE_STRING_FIELDS(
171                 /*! \brief URI for the registrar */
172                 AST_STRING_FIELD(server_uri);
173                 /*! \brief URI for the AOR */
174                 AST_STRING_FIELD(client_uri);
175                 /*! \brief Optional user for contact header */
176                 AST_STRING_FIELD(contact_user);
177                 /*! \brief Explicit transport to use for registration */
178                 AST_STRING_FIELD(transport);
179                 /*! \brief Outbound proxy to use */
180                 AST_STRING_FIELD(outbound_proxy);
181         );
182         /*! \brief Requested expiration time */
183         unsigned int expiration;
184         /*! \brief Interval at which retries should occur for temporal responses */
185         unsigned int retry_interval;
186         /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
187         unsigned int auth_rejection_permanent;
188         /*! \brief Maximum number of retries permitted */
189         unsigned int max_retries;
190         /*! \brief Outbound registration state */
191         struct sip_outbound_registration_state *state;
192         /*! \brief Configured authentication credentials */
193         struct ast_sip_auth_array outbound_auths;
194         /*! \brief Number of configured auths */
195         size_t num_outbound_auths;
196 };
197
198 /*! \brief Helper function which cancels the timer on a client */
199 static void cancel_registration(struct sip_outbound_registration_client_state *client_state)
200 {
201         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &client_state->timer)) {
202                 /* The timer was successfully cancelled, drop the refcount of client_state */
203                 ao2_ref(client_state, -1);
204         }
205 }
206
207 /*! \brief Callback function for registering */
208 static int handle_client_registration(void *data)
209 {
210         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
211         pjsip_tx_data *tdata;
212
213         cancel_registration(client_state);
214
215         if ((client_state->status == SIP_REGISTRATION_STOPPED) ||
216                 (pjsip_regc_register(client_state->client, PJ_FALSE, &tdata) != PJ_SUCCESS)) {
217                 return 0;
218         }
219
220         /* Due to the registration the callback may now get called, so bump the ref count */
221         ao2_ref(client_state, +1);
222         if (pjsip_regc_send(client_state->client, tdata) != PJ_SUCCESS) {
223                 ao2_ref(client_state, -1);
224         }
225
226         return 0;
227 }
228
229 /*! \brief Timer callback function, used just for registrations */
230 static void sip_outbound_registration_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
231 {
232         struct sip_outbound_registration_client_state *client_state = entry->user_data;
233
234         ao2_ref(client_state, +1);
235         if (ast_sip_push_task(client_state->serializer, handle_client_registration, client_state)) {
236                 ast_log(LOG_WARNING, "Failed to pass outbound registration to threadpool\n");
237                 ao2_ref(client_state, -1);
238         }
239
240         entry->id = 0;
241 }
242
243 /*! \brief Helper function which sets up the timer to re-register in a specific amount of time */
244 static void schedule_registration(struct sip_outbound_registration_client_state *client_state, unsigned int seconds)
245 {
246         pj_time_val delay = { .sec = seconds, };
247
248         cancel_registration(client_state);
249
250         ao2_ref(client_state, +1);
251         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &client_state->timer, &delay) != PJ_SUCCESS) {
252                 ast_log(LOG_WARNING, "Failed to pass timed registration to scheduler\n");
253                 ao2_ref(client_state, -1);
254         }
255 }
256
257 /*! \brief Callback function for unregistering (potentially) and destroying state */
258 static int handle_client_state_destruction(void *data)
259 {
260         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
261         pjsip_regc_info info;
262
263         cancel_registration(client_state);
264
265         pjsip_regc_get_info(client_state->client, &info);
266
267         if (info.is_busy == PJ_TRUE) {
268                 /* If a client transaction is in progress we defer until it is complete */
269                 client_state->destroy = 1;
270                 return 0;
271         }
272
273         if (client_state->status != SIP_REGISTRATION_UNREGISTERED && client_state->status != SIP_REGISTRATION_REJECTED_PERMANENT) {
274                 pjsip_tx_data *tdata;
275
276                 if (pjsip_regc_unregister(client_state->client, &tdata) == PJ_SUCCESS) {
277                         pjsip_regc_send(client_state->client, tdata);
278                 }
279         }
280
281         pjsip_regc_destroy(client_state->client);
282
283         client_state->status = SIP_REGISTRATION_STOPPED;
284         ast_sip_auth_array_destroy(&client_state->outbound_auths);
285
286         return 0;
287 }
288
289 /*! \brief Structure for registration response */
290 struct registration_response {
291         /*! \brief Response code for the registration attempt */
292         int code;
293         /*! \brief Expiration time for registration */
294         int expiration;
295         /*! \brief Retry-After value */
296         int retry_after;
297         /*! \brief Outbound registration client state */
298         struct sip_outbound_registration_client_state *client_state;
299         /*! \brief The response message */
300         pjsip_rx_data *rdata;
301         /*! \brief The response transaction */
302         pjsip_transaction *tsx;
303 };
304
305 /*! \brief Registration response structure destructor */
306 static void registration_response_destroy(void *obj)
307 {
308         struct registration_response *response = obj;
309
310         if (response->rdata) {
311                 pjsip_rx_data_free_cloned(response->rdata);
312         }
313
314         ao2_cleanup(response->client_state);
315 }
316
317 /* \brief Helper funtion which determines if a response code is temporal or not */
318 static int sip_outbound_registration_is_temporal(unsigned int code,
319                 struct sip_outbound_registration_client_state *client_state)
320 {
321         /* Shamelessly taken from pjsua */
322         if (code == PJSIP_SC_REQUEST_TIMEOUT ||
323                 code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
324                 code == PJSIP_SC_BAD_GATEWAY ||
325                 code == PJSIP_SC_SERVICE_UNAVAILABLE ||
326                 code == PJSIP_SC_SERVER_TIMEOUT ||
327                 ((code == PJSIP_SC_UNAUTHORIZED ||
328                   code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED) &&
329                  !client_state->auth_rejection_permanent) ||
330                 PJSIP_IS_STATUS_IN_CLASS(code, 600)) {
331                 return 1;
332         } else {
333                 return 0;
334         }
335 }
336
337 /*! \brief Callback function for handling a response to a registration attempt */
338 static int handle_registration_response(void *data)
339 {
340         RAII_VAR(struct registration_response *, response, data, ao2_cleanup);
341         pjsip_regc_info info;
342         char server_uri[PJSIP_MAX_URL_SIZE], client_uri[PJSIP_MAX_URL_SIZE];
343
344         if (response->client_state->status == SIP_REGISTRATION_STOPPED) {
345                 return 0;
346         }
347
348         pjsip_regc_get_info(response->client_state->client, &info);
349         ast_copy_pj_str(server_uri, &info.server_uri, sizeof(server_uri));
350         ast_copy_pj_str(client_uri, &info.client_uri, sizeof(client_uri));
351
352         if (response->code == 401 || response->code == 407) {
353                 pjsip_tx_data *tdata;
354                 if (!ast_sip_create_request_with_auth(&response->client_state->outbound_auths,
355                                 response->rdata, response->tsx, &tdata)) {
356                         ao2_ref(response->client_state, +1);
357                         if (pjsip_regc_send(response->client_state->client, tdata) != PJ_SUCCESS) {
358                                 ao2_cleanup(response->client_state);
359                         }
360                         return 0;
361                 }
362                 /* Otherwise, fall through so the failure is processed appropriately */
363         }
364
365         if (PJSIP_IS_STATUS_IN_CLASS(response->code, 200)) {
366                 /* If the registration went fine simply reschedule registration for the future */
367                 response->client_state->status = SIP_REGISTRATION_REGISTERED;
368                 response->client_state->retries = 0;
369                 schedule_registration(response->client_state, response->expiration - REREGISTER_BUFFER_TIME);
370         } else if (response->retry_after) {
371                 /* If we have been instructed to retry after a period of time, schedule it as such */
372                 response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
373                 schedule_registration(response->client_state, response->retry_after);
374                 ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on registration attempt to '%s', instructed to retry in '%d'\n",
375                         response->code, server_uri, client_uri, response->retry_after);
376         } else if (response->client_state->retry_interval && sip_outbound_registration_is_temporal(response->code, response->client_state)) {
377                 if (response->client_state->retries == response->client_state->max_retries) {
378                         /* If we received enough temporal responses to exceed our maximum give up permanently */
379                         response->client_state->status = SIP_REGISTRATION_REJECTED_PERMANENT;
380                         ast_log(LOG_WARNING, "Maximum retries reached when attempting outbound registration to '%s' with client '%s', stopping registration attempt\n",
381                                 server_uri, client_uri);
382                 } else {
383                         /* On the other hand if we can still try some more do so */
384                         response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
385                         response->client_state->retries++;
386                         schedule_registration(response->client_state, response->client_state->retry_interval);
387                         ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on registration attempt to '%s', retrying in '%d' seconds\n",
388                                 response->code, server_uri, client_uri, response->client_state->retry_interval);
389                 }
390         } else {
391                 /* Finally if there's no hope of registering give up */
392                 response->client_state->status = SIP_REGISTRATION_REJECTED_PERMANENT;
393                 ast_log(LOG_WARNING, "Fatal response '%d' received from '%s' on registration attempt to '%s', stopping outbound registration\n",
394                         response->code, server_uri, client_uri);
395         }
396
397         ast_system_publish_registry("PJSIP", client_uri, server_uri, sip_outbound_registration_status_str[response->client_state->status], NULL);
398
399         /* If deferred destruction is in use see if we need to destroy now */
400         if (response->client_state->destroy) {
401                 handle_client_state_destruction(response->client_state);
402         }
403
404         return 0;
405 }
406
407 /*! \brief Callback function for outbound registration client */
408 static void sip_outbound_registration_response_cb(struct pjsip_regc_cbparam *param)
409 {
410         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, param->token, ao2_cleanup);
411         struct registration_response *response = ao2_alloc(sizeof(*response), registration_response_destroy);
412
413         response->code = param->code;
414         response->expiration = param->expiration;
415         response->client_state = client_state;
416         ao2_ref(response->client_state, +1);
417
418         if (param->rdata) {
419                 struct pjsip_retry_after_hdr *retry_after = pjsip_msg_find_hdr(param->rdata->msg_info.msg, PJSIP_H_RETRY_AFTER, NULL);
420
421                 response->retry_after = retry_after ? retry_after->ivalue : 0;
422                 response->tsx = pjsip_rdata_get_tsx(param->rdata);
423                 pjsip_rx_data_clone(param->rdata, 0, &response->rdata);
424         }
425
426         if (ast_sip_push_task(client_state->serializer, handle_registration_response, response)) {
427                 ast_log(LOG_WARNING, "Failed to pass incoming registration response to threadpool\n");
428                 ao2_cleanup(response);
429         }
430 }
431
432 /*! \brief Destructor function for registration state */
433 static void sip_outbound_registration_state_destroy(void *obj)
434 {
435         struct sip_outbound_registration_state *state = obj;
436
437         if (!state->client_state) {
438                 return;
439         }
440
441         if (state->client_state->serializer && ast_sip_push_task(state->client_state->serializer, handle_client_state_destruction, state->client_state)) {
442                 ast_log(LOG_WARNING, "Failed to pass outbound registration client destruction to threadpool\n");
443                 ao2_ref(state->client_state, -1);
444         }
445 }
446
447 /*! \brief Destructor function for client registration state */
448 static void sip_outbound_registration_client_state_destroy(void *obj)
449 {
450         struct sip_outbound_registration_client_state *client_state = obj;
451
452         ast_taskprocessor_unreference(client_state->serializer);
453 }
454
455 /*! \brief Allocator function for registration state */
456 static struct sip_outbound_registration_state *sip_outbound_registration_state_alloc(void)
457 {
458         struct sip_outbound_registration_state *state = ao2_alloc(sizeof(*state), sip_outbound_registration_state_destroy);
459
460         if (!state || !(state->client_state = ao2_alloc(sizeof(*state->client_state), sip_outbound_registration_client_state_destroy))) {
461                 ao2_cleanup(state);
462                 return NULL;
463         }
464
465         if ((pjsip_regc_create(ast_sip_get_pjsip_endpoint(), state->client_state, sip_outbound_registration_response_cb, &state->client_state->client) != PJ_SUCCESS) ||
466                 !(state->client_state->serializer = ast_sip_create_serializer())) {
467                 /* This is on purpose, normal operation will have it be deallocated within the serializer */
468                 pjsip_regc_destroy(state->client_state->client);
469                 ao2_cleanup(state->client_state);
470                 ao2_cleanup(state);
471                 return NULL;
472         }
473
474         state->client_state->status = SIP_REGISTRATION_UNREGISTERED;
475         state->client_state->timer.user_data = state->client_state;
476         state->client_state->timer.cb = sip_outbound_registration_timer_cb;
477
478         return state;
479 }
480
481 /*! \brief Destructor function for registration information */
482 static void sip_outbound_registration_destroy(void *obj)
483 {
484         struct sip_outbound_registration *registration = obj;
485
486         ao2_cleanup(registration->state);
487         ast_sip_auth_array_destroy(&registration->outbound_auths);
488
489         ast_string_field_free_memory(registration);
490 }
491
492 /*! \brief Allocator function for registration information */
493 static void *sip_outbound_registration_alloc(const char *name)
494 {
495         struct sip_outbound_registration *registration = ast_sorcery_generic_alloc(sizeof(*registration), sip_outbound_registration_destroy);
496
497         if (!registration || ast_string_field_init(registration, 256)) {
498                 ao2_cleanup(registration);
499                 return NULL;
500         }
501
502         return registration;
503 }
504
505 /*! \brief Helper function which populates a pj_str_t with a contact header */
506 static int sip_dialog_create_contact(pj_pool_t *pool, pj_str_t *contact, const char *user, const pj_str_t *target, pjsip_tpselector *selector)
507 {
508         pj_str_t tmp, local_addr;
509         pjsip_uri *uri;
510         pjsip_sip_uri *sip_uri;
511         pjsip_transport_type_e type = PJSIP_TRANSPORT_UNSPECIFIED;
512         int local_port;
513
514         pj_strdup_with_null(pool, &tmp, target);
515
516         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
517             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
518                 return -1;
519         }
520
521         sip_uri = pjsip_uri_get_uri(uri);
522
523         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
524                 type = PJSIP_TRANSPORT_TLS;
525         } else if (!sip_uri->transport_param.slen) {
526                 type = PJSIP_TRANSPORT_UDP;
527         } else {
528                 type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
529         }
530
531         if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
532                 return -1;
533         }
534
535         if (pj_strchr(&sip_uri->host, ':')) {
536                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
537         }
538
539         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()), pool, type, selector,
540                                                               &local_addr, &local_port) != PJ_SUCCESS) {
541                 return -1;
542         }
543
544         if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
545                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
546         }
547
548         contact->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
549         contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
550                                       "<%s:%s@%s%.*s%s:%d%s%s>",
551                                       (pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) ? "sips" : "sip",
552                                       user,
553                                       (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
554                                       (int)local_addr.slen,
555                                       local_addr.ptr,
556                                       (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
557                                       local_port,
558                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
559                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
560
561         return 0;
562 }
563
564 /*!
565  * \internal
566  * \brief Check if a registration can be reused
567  *
568  * This checks if the existing outbound registration's configuration differs from a newly-applied
569  * outbound registration to see if the applied one.
570  *
571  * \param existing The pre-existing outbound registration
572  * \param applied The newly-created registration
573  */
574 static int can_reuse_registration(struct sip_outbound_registration *existing, struct sip_outbound_registration *applied)
575 {
576         int i;
577
578         if (strcmp(existing->server_uri, applied->server_uri) || strcmp(existing->client_uri, applied->client_uri) ||
579                 strcmp(existing->transport, applied->transport) || strcmp(existing->contact_user, applied->contact_user) ||
580                 strcmp(existing->outbound_proxy, applied->outbound_proxy) || existing->num_outbound_auths != applied->num_outbound_auths ||
581                 existing->auth_rejection_permanent != applied->auth_rejection_permanent) {
582                 return 0;
583         }
584
585         for (i = 0; i < existing->num_outbound_auths; ++i) {
586                 if (strcmp(existing->outbound_auths.names[i], applied->outbound_auths.names[i])) {
587                         return 0;
588                 }
589         }
590
591         return 1;
592 }
593
594 /*! \brief Helper function that allocates a pjsip registration client and configures it */
595 static int sip_outbound_registration_regc_alloc(void *data)
596 {
597         struct sip_outbound_registration *registration = data;
598         pj_str_t server_uri, client_uri, contact_uri;
599         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
600
601         if (!ast_strlen_zero(registration->transport)) {
602                 RAII_VAR(struct ast_sip_transport *, transport, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", registration->transport), ao2_cleanup);
603
604                 if (!transport || !transport->state) {
605                         return -1;
606                 }
607
608                 if (transport->state->transport) {
609                         selector.type = PJSIP_TPSELECTOR_TRANSPORT;
610                         selector.u.transport = transport->state->transport;
611                 } else if (transport->state->factory) {
612                         selector.type = PJSIP_TPSELECTOR_LISTENER;
613                         selector.u.listener = transport->state->factory;
614                 } else {
615                         return -1;
616                 }
617         }
618
619         pjsip_regc_set_transport(registration->state->client_state->client, &selector);
620
621         if (!ast_strlen_zero(registration->outbound_proxy)) {
622                 pjsip_route_hdr route_set, *route;
623                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
624                 pj_str_t tmp;
625
626                 pj_list_init(&route_set);
627
628                 pj_strdup2_with_null(pjsip_regc_get_pool(registration->state->client_state->client), &tmp, registration->outbound_proxy);
629                 if (!(route = pjsip_parse_hdr(pjsip_regc_get_pool(registration->state->client_state->client), &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
630                         return -1;
631                 }
632                 pj_list_push_back(&route_set, route);
633
634                 pjsip_regc_set_route_set(registration->state->client_state->client, &route_set);
635         }
636
637         pj_cstr(&server_uri, registration->server_uri);
638
639         if (sip_dialog_create_contact(pjsip_regc_get_pool(registration->state->client_state->client), &contact_uri, S_OR(registration->contact_user, "s"), &server_uri, &selector)) {
640                 return -1;
641         }
642
643         pj_cstr(&client_uri, registration->client_uri);
644
645         if (pjsip_regc_init(registration->state->client_state->client, &server_uri, &client_uri, &client_uri, 1, &contact_uri, registration->expiration) != PJ_SUCCESS) {
646                 return -1;
647         }
648
649         return 0;
650 }
651
652 /*! \brief Apply function which finds or allocates a state structure */
653 static int sip_outbound_registration_apply(const struct ast_sorcery *sorcery, void *obj)
654 {
655         RAII_VAR(struct sip_outbound_registration *, existing, ast_sorcery_retrieve_by_id(sorcery, "registration", ast_sorcery_object_get_id(obj)), ao2_cleanup);
656         struct sip_outbound_registration *applied = obj;
657
658         if (!existing) {
659                 /* If no existing registration exists we can just start fresh easily */
660                 applied->state = sip_outbound_registration_state_alloc();
661         } else {
662                 /* If there is an existing registration things are more complicated, we can immediately reuse this state if most stuff remains unchanged */
663                 if (can_reuse_registration(existing, applied)) {
664                         applied->state = existing->state;
665                         ao2_ref(applied->state, +1);
666                         return 0;
667                 }
668                 applied->state = sip_outbound_registration_state_alloc();
669         }
670
671         if (!applied->state) {
672                 return -1;
673         }
674
675         return ast_sip_push_task_synchronous(NULL, sip_outbound_registration_regc_alloc, applied);
676 }
677
678 /*! \brief Helper function which performs a single registration */
679 static int sip_outbound_registration_perform(void *data)
680 {
681         RAII_VAR(struct sip_outbound_registration *, registration, data, ao2_cleanup);
682         size_t i;
683
684         /* Just in case the client state is being reused for this registration, free the auth information */
685         ast_sip_auth_array_destroy(&registration->state->client_state->outbound_auths);
686
687         registration->state->client_state->outbound_auths.names = ast_calloc(registration->outbound_auths.num, sizeof(char *));
688         for (i = 0; i < registration->outbound_auths.num; ++i) {
689                 registration->state->client_state->outbound_auths.names[i] = ast_strdup(registration->outbound_auths.names[i]);
690         }
691         registration->state->client_state->outbound_auths.num = registration->outbound_auths.num;
692         registration->state->client_state->retry_interval = registration->retry_interval;
693         registration->state->client_state->max_retries = registration->max_retries;
694         registration->state->client_state->retries = 0;
695
696         pjsip_regc_update_expires(registration->state->client_state->client, registration->expiration);
697
698         schedule_registration(registration->state->client_state, (ast_random() % 10) + 1);
699
700         return 0;
701 }
702
703 /*! \brief Helper function which performs all registrations */
704 static void sip_outbound_registration_perform_all(void)
705 {
706         RAII_VAR(struct ao2_container *, registrations, ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL), ao2_cleanup);
707         struct ao2_iterator i;
708         struct sip_outbound_registration *registration;
709
710         if (!registrations) {
711                 return;
712         }
713
714         i = ao2_iterator_init(registrations, 0);
715         while ((registration = ao2_iterator_next(&i))) {
716                 if (ast_sip_push_task(registration->state->client_state->serializer, sip_outbound_registration_perform, registration)) {
717                         ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n", ast_sorcery_object_get_id(registration));
718                         ao2_ref(registration, -1);
719                 }
720         }
721         ao2_iterator_destroy(&i);
722 }
723
724 static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
725 {
726         struct sip_outbound_registration *registration = obj;
727
728         return ast_sip_auth_array_init(&registration->outbound_auths, var->value);
729 }
730
731 static struct sip_outbound_registration *retrieve_registration(const char *registration_name)
732 {
733         return ast_sorcery_retrieve_by_id(
734                 ast_sip_get_sorcery(),
735                 "registration",
736                 registration_name);
737 }
738
739 static int unregister_task(void *obj)
740 {
741         RAII_VAR(struct sip_outbound_registration*, registration, obj, ao2_cleanup);
742         struct pjsip_regc *client = registration->state->client_state->client;
743         pjsip_tx_data *tdata;
744
745         if (pjsip_regc_unregister(client, &tdata) != PJ_SUCCESS) {
746                 return 0;
747         }
748
749         ao2_ref(registration->state->client_state, +1);
750         if (pjsip_regc_send(client, tdata) != PJ_SUCCESS) {
751                 ao2_cleanup(registration->state->client_state);
752         }
753
754         return 0;
755 }
756
757 static int queue_unregister(struct sip_outbound_registration *registration)
758 {
759         ao2_ref(registration, +1);
760         if (ast_sip_push_task(registration->state->client_state->serializer, unregister_task, registration)) {
761                 ao2_cleanup(registration);
762                 return -1;
763         }
764         return 0;
765 }
766
767 static char *cli_complete_registration(const char *line, const char *word,
768 int pos, int state)
769 {
770         char *result = NULL;
771         int wordlen;
772         int which = 0;
773         struct sip_outbound_registration *registration;
774         RAII_VAR(struct ao2_container *, registrations, NULL, ao2_cleanup);
775         struct ao2_iterator i;
776
777         if (pos != 3) {
778                 return NULL;
779         }
780
781         wordlen = strlen(word);
782         registrations = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
783                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
784         if (!registrations) {
785                 return NULL;
786         }
787
788         i = ao2_iterator_init(registrations, 0);
789         while ((registration = ao2_iterator_next(&i))) {
790                 const char *name = ast_sorcery_object_get_id(registration);
791                 if (!strncasecmp(word, name, wordlen) && ++which > state) {
792                         result = ast_strdup(name);
793                 }
794
795                 ao2_cleanup(registration);
796                 if (result) {
797                         break;
798                 }
799         }
800         ao2_iterator_destroy(&i);
801         return result;
802 }
803
804 static char *cli_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
805 {
806         RAII_VAR(struct sip_outbound_registration *, registration, NULL, ao2_cleanup);
807         const char *registration_name;
808
809         switch (cmd) {
810         case CLI_INIT:
811                 e->command = "pjsip send unregister";
812                 e->usage =
813                         "Usage: pjsip send unregister <registration>\n"
814                         "       Send a SIP REGISTER request to the specified outbound "
815                         "registration with an expiration of 0. This will cause the contact "
816                         "added by this registration to be removed on the remote system.\n";
817                 return NULL;
818         case CLI_GENERATE:
819                 return cli_complete_registration(a->line, a->word, a->pos, a->n);
820         }
821
822         if (a->argc != 4) {
823                 return CLI_SHOWUSAGE;
824         }
825
826         registration_name = a->argv[3];
827
828         registration = retrieve_registration(registration_name);
829         if (!registration) {
830                 ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
831                 return CLI_FAILURE;
832         }
833
834         if (queue_unregister(registration)) {
835                 ast_cli(a->fd, "Failed to queue unregistration");
836                 return 0;
837         }
838
839         return CLI_SUCCESS;
840 }
841
842 static int ami_unregister(struct mansession *s, const struct message *m)
843 {
844         const char *registration_name = astman_get_header(m, "Registration");
845         RAII_VAR(struct sip_outbound_registration *, registration, NULL, ao2_cleanup);
846
847         if (ast_strlen_zero(registration_name)) {
848                 astman_send_error(s, m, "Registration parameter missing.");
849                 return 0;
850         }
851
852         registration = retrieve_registration(registration_name);
853         if (!registration) {
854                 astman_send_error(s, m, "Unable to retrieve registration entry\n");
855                 return 0;
856         }
857
858
859         if (queue_unregister(registration)) {
860                 astman_send_ack(s, m, "Failed to queue unregistration");
861                 return 0;
862         }
863
864         astman_send_ack(s, m, "Unregistration sent");
865         return 0;
866 }
867
868 static struct ast_cli_entry cli_outbound_registration[] = {
869         AST_CLI_DEFINE(cli_unregister, "Send a REGISTER request to an outbound registration target with a expiration of 0")
870 };
871
872 static int load_module(void)
873 {
874         ast_sorcery_apply_default(ast_sip_get_sorcery(), "registration", "config", "pjsip.conf,criteria=type=registration");
875
876         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "registration", sip_outbound_registration_alloc, NULL, sip_outbound_registration_apply)) {
877                 return AST_MODULE_LOAD_DECLINE;
878         }
879
880         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "type", "", OPT_NOOP_T, 0, 0);
881         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "server_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, server_uri));
882         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "client_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, client_uri));
883         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "contact_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, contact_user));
884         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, transport));
885         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, outbound_proxy));
886         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "expiration", "3600", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, expiration));
887         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "retry_interval", "60", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, retry_interval));
888         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "max_retries", "10", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, max_retries));
889         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "auth_rejection_permanent", "yes", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, auth_rejection_permanent));
890         ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "registration", "outbound_auth", "", outbound_auth_handler, NULL, 0, 0);
891         ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
892         sip_outbound_registration_perform_all();
893
894         ast_cli_register_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
895         ast_manager_register_xml("PJSIPUnregister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_unregister);
896         return AST_MODULE_LOAD_SUCCESS;
897 }
898
899 static int reload_module(void)
900 {
901         ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
902         sip_outbound_registration_perform_all();
903         return 0;
904 }
905
906 static int unload_module(void)
907 {
908         ast_cli_unregister_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
909         ast_manager_unregister("PJSIPUnregister");
910         return 0;
911 }
912
913 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Outbound Registration Support",
914                 .load = load_module,
915                 .reload = reload_module,
916                 .unload = unload_module,
917                 .load_pri = AST_MODPRI_APP_DEPEND,
918                );