res/res_pjsip_outbound_registration: Apply configuration on object type load
[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/res_pjsip_cli.h"
32 #include "asterisk/module.h"
33 #include "asterisk/taskprocessor.h"
34 #include "asterisk/cli.h"
35 #include "asterisk/stasis_system.h"
36 #include "asterisk/threadstorage.h"
37 #include "asterisk/threadpool.h"
38 #include "res_pjsip/include/res_pjsip_private.h"
39
40 /*** DOCUMENTATION
41         <configInfo name="res_pjsip_outbound_registration" language="en_US">
42                 <synopsis>SIP resource for outbound registrations</synopsis>
43                 <description><para>
44                         <emphasis>Outbound Registration</emphasis>
45                         </para>
46                         <para>This module allows <literal>res_pjsip</literal> to register to other SIP servers.</para>
47                 </description>
48                 <configFile name="pjsip.conf">
49                         <configObject name="registration">
50                                 <synopsis>The configuration for outbound registration</synopsis>
51                                 <description><para>
52                                         Registration is <emphasis>COMPLETELY</emphasis> separate from the rest of
53                                         <literal>pjsip.conf</literal>. A minimal configuration consists of
54                                         setting a <literal>server_uri</literal> and a <literal>client_uri</literal>.
55                                 </para></description>
56                                 <configOption name="auth_rejection_permanent" default="yes">
57                                         <synopsis>Determines whether failed authentication challenges are treated
58                                         as permanent failures.</synopsis>
59                                         <description><para>If this option is enabled and an authentication challenge fails,
60                                         registration will not be attempted again until the configuration is reloaded.</para></description>
61                                 </configOption>
62                                 <configOption name="client_uri">
63                                         <synopsis>Client SIP URI used when attemping outbound registration</synopsis>
64                                         <description><para>
65                                                 This is the address-of-record for the outbound registration (i.e. the URI in
66                                                 the To header of the REGISTER).</para>
67                                                 <para>For registration with an ITSP, the client SIP URI may need to consist of
68                                                 an account name or number and the provider's hostname for their registrar, e.g.
69                                                 client_uri=1234567890@example.com. This may differ between providers.</para>
70                                                 <para>For registration to generic registrars, the client SIP URI will depend
71                                                 on networking specifics and configuration of the registrar.
72                                         </para></description>
73                                 </configOption>
74                                 <configOption name="contact_user">
75                                         <synopsis>Contact User to use in request</synopsis>
76                                 </configOption>
77                                 <configOption name="expiration" default="3600">
78                                         <synopsis>Expiration time for registrations in seconds</synopsis>
79                                 </configOption>
80                                 <configOption name="max_retries" default="10">
81                                         <synopsis>Maximum number of registration attempts.</synopsis>
82                                 </configOption>
83                                 <configOption name="outbound_auth" default="">
84                                         <synopsis>Authentication object to be used for outbound registrations.</synopsis>
85                                 </configOption>
86                                 <configOption name="outbound_proxy" default="">
87                                         <synopsis>Outbound Proxy used to send registrations</synopsis>
88                                 </configOption>
89                                 <configOption name="retry_interval" default="60">
90                                         <synopsis>Interval in seconds between retries if outbound registration is unsuccessful</synopsis>
91                                 </configOption>
92                                 <configOption name="forbidden_retry_interval" default="0">
93                                         <synopsis>Interval used when receiving a 403 Forbidden response.</synopsis>
94                                         <description><para>
95                                                 If a 403 Forbidden is received, chan_pjsip will wait
96                                                 <replaceable>forbidden_retry_interval</replaceable> seconds before
97                                                 attempting registration again. If 0 is specified, chan_pjsip will not
98                                                 retry after receiving a 403 Forbidden response. Setting this to a non-zero
99                                                 value goes against a "SHOULD NOT" in RFC3261, but can be used to work around
100                                                 buggy registrars.
101                                         </para></description>
102                                 </configOption>
103                                 <configOption name="fatal_retry_interval" default="0">
104                                         <synopsis>Interval used when receiving a Fatal response.</synopsis>
105                                         <description><para>
106                                                 If a fatal response is received, chan_pjsip will wait
107                                                 <replaceable>fatal_retry_interval</replaceable> seconds before
108                                                 attempting registration again. If 0 is specified, chan_pjsip will not
109                                                 retry after receiving a fatal (non-temporary 4xx, 5xx, 6xx) response.
110                                                 Setting this to a non-zero value may go against a "SHOULD NOT" in RFC3261,
111                                                 but can be used to work around buggy registrars.</para>
112                                                 <note><para>if also set the <replaceable>forbidden_retry_interval</replaceable>
113                                                 takes precedence over this one when a 403 is received.
114                                                 Also, if <replaceable>auth_rejection_permanent</replaceable> equals 'yes' then
115                                                 a 401 and 407 become subject to this retry interval.</para></note>
116                                         </description>
117                                 </configOption>
118                                 <configOption name="server_uri">
119                                         <synopsis>SIP URI of the server to register against</synopsis>
120                                         <description><para>
121                                                 This is the URI at which to find the registrar to send the outbound REGISTER. This URI
122                                                 is used as the request URI of the outbound REGISTER request from Asterisk.</para>
123                                                 <para>For registration with an ITSP, the setting may often be just the domain of
124                                                 the registrar, e.g. sip:sip.example.com.
125                                         </para></description>
126                                 </configOption>
127                                 <configOption name="transport">
128                                         <synopsis>Transport used for outbound authentication</synopsis>
129                                         <description>
130                                                 <note><para>A <replaceable>transport</replaceable> configured in
131                                                 <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>
132                                         </description>
133                                 </configOption>
134                                 <configOption name="line">
135                                         <synopsis>Whether to add a 'line' parameter to the Contact for inbound call matching</synopsis>
136                                         <description><para>
137                                                 When enabled this option will cause a 'line' parameter to be added to the Contact
138                                                 header placed into the outgoing registration request. If the remote server sends a call
139                                                 this line parameter will be used to establish a relationship to the outbound registration,
140                                                 ultimately causing the configured endpoint to be used.
141                                         </para></description>
142                                 </configOption>
143                                 <configOption name="endpoint">
144                                         <synopsis>Endpoint to use for incoming related calls</synopsis>
145                                         <description><para>
146                                                 When line support is enabled this configured endpoint name is used for incoming calls
147                                                 that are related to the outbound registration.
148                                         </para></description>
149                                 </configOption>
150                                 <configOption name="type">
151                                         <synopsis>Must be of type 'registration'.</synopsis>
152                                 </configOption>
153                                 <configOption name="support_path">
154                                         <synopsis>Enables Path support for outbound REGISTER requests.</synopsis>
155                                         <description><para>
156                                                 When this option is enabled, outbound REGISTER requests will advertise
157                                                 support for Path headers so that intervening proxies can add to the Path
158                                                 header as necessary.
159                                         </para></description>
160                                 </configOption>
161                         </configObject>
162                 </configFile>
163         </configInfo>
164         <manager name="PJSIPUnregister" language="en_US">
165                 <synopsis>
166                         Unregister an outbound registration.
167                 </synopsis>
168                 <syntax>
169                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
170                         <parameter name="Registration" required="true">
171                                 <para>The outbound registration to unregister.</para>
172                         </parameter>
173                 </syntax>
174                 <description>
175                         <para>
176                         Unregisters the specified outbound registration and stops future registration attempts.
177                         Call PJSIPRegister to start registration and schedule re-registrations according to configuration.
178             </para>
179                 </description>
180         </manager>
181         <manager name="PJSIPRegister" language="en_US">
182                 <synopsis>
183                         Register an outbound registration.
184                 </synopsis>
185                 <syntax>
186                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
187                         <parameter name="Registration" required="true">
188                                 <para>The outbound registration to register.</para>
189                         </parameter>
190                 </syntax>
191                 <description>
192                         <para>
193                         Unregisters the specified outbound registration then starts registration and schedules re-registrations
194                         according to configuration.
195                         future registrations.
196             </para>
197                 </description>
198         </manager>
199         <manager name="PJSIPShowRegistrationsOutbound" language="en_US">
200                 <synopsis>
201                         Lists PJSIP outbound registrations.
202                 </synopsis>
203                 <syntax />
204                 <description>
205                         <para>
206                         In response <literal>OutboundRegistrationDetail</literal> events showing configuration and status
207                         information are raised for each outbound registration object. <literal>AuthDetail</literal>
208                         events are raised for each associated auth object as well.  Once all events are completed an
209                         <literal>OutboundRegistrationDetailComplete</literal> is issued.
210                         </para>
211                 </description>
212         </manager>
213  ***/
214
215 /*! \brief Some thread local storage used to determine if the running thread invoked the callback */
216 AST_THREADSTORAGE(register_callback_invoked);
217
218 /*! \brief Amount of buffer time (in seconds) before expiration that we re-register at */
219 #define REREGISTER_BUFFER_TIME 10
220
221 /*! \brief Size of the buffer for creating a unique string for the line */
222 #define LINE_PARAMETER_SIZE 8
223
224 /*! \brief Various states that an outbound registration may be in */
225 enum sip_outbound_registration_status {
226         /*! \brief Currently unregistered */
227         SIP_REGISTRATION_UNREGISTERED = 0,
228         /*! \brief Registered, yay! */
229         SIP_REGISTRATION_REGISTERED,
230         /*! \brief Registration was rejected, but response was temporal */
231         SIP_REGISTRATION_REJECTED_TEMPORARY,
232         /*! \brief Registration was rejected, permanently */
233         SIP_REGISTRATION_REJECTED_PERMANENT,
234         /*! \brief Registration is stopping. */
235         SIP_REGISTRATION_STOPPING,
236         /*! \brief Registration has been stopped */
237         SIP_REGISTRATION_STOPPED,
238 };
239
240 /*!
241  * \internal
242  * \brief Convert the internal registration state to an external status string.
243  * \since 13.5.0
244  *
245  * \param state Current outbound registration state.
246  *
247  * \return External registration status string.
248  */
249 static const char *sip_outbound_registration_status_str(enum sip_outbound_registration_status state)
250 {
251         const char *str;
252
253         str = "Unregistered";
254         switch (state) {
255         case SIP_REGISTRATION_STOPPING:
256         case SIP_REGISTRATION_STOPPED:
257         case SIP_REGISTRATION_UNREGISTERED:
258                 break;
259         case SIP_REGISTRATION_REGISTERED:
260                 str = "Registered";
261                 break;
262         case SIP_REGISTRATION_REJECTED_TEMPORARY:
263         case SIP_REGISTRATION_REJECTED_PERMANENT:
264                 str = "Rejected";
265                 break;
266         }
267         return str;
268 }
269
270 /*! \brief Outbound registration information */
271 struct sip_outbound_registration {
272         /*! \brief Sorcery object details */
273         SORCERY_OBJECT(details);
274         /*! \brief Stringfields */
275         AST_DECLARE_STRING_FIELDS(
276                 /*! \brief URI for the registrar */
277                 AST_STRING_FIELD(server_uri);
278                 /*! \brief URI for the AOR */
279                 AST_STRING_FIELD(client_uri);
280                 /*! \brief Optional user for contact header */
281                 AST_STRING_FIELD(contact_user);
282                 /*! \brief Explicit transport to use for registration */
283                 AST_STRING_FIELD(transport);
284                 /*! \brief Outbound proxy to use */
285                 AST_STRING_FIELD(outbound_proxy);
286                 /*! \brief Endpoint to use for related incoming calls */
287                 AST_STRING_FIELD(endpoint);
288         );
289         /*! \brief Requested expiration time */
290         unsigned int expiration;
291         /*! \brief Interval at which retries should occur for temporal responses */
292         unsigned int retry_interval;
293         /*! \brief Interval at which retries should occur for permanent responses */
294         unsigned int forbidden_retry_interval;
295         /*! \brief Interval at which retries should occur for all permanent responses */
296         unsigned int fatal_retry_interval;
297         /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
298         unsigned int auth_rejection_permanent;
299         /*! \brief Maximum number of retries permitted */
300         unsigned int max_retries;
301         /*! \brief Whether to add a line parameter to the outbound Contact or not */
302         unsigned int line;
303         /*! \brief Configured authentication credentials */
304         struct ast_sip_auth_vector outbound_auths;
305         /*! \brief Whether Path support is enabled */
306         unsigned int support_path;
307 };
308
309 /*! \brief Outbound registration client state information (persists for lifetime of regc) */
310 struct sip_outbound_registration_client_state {
311         /*! \brief Current state of this registration */
312         enum sip_outbound_registration_status status;
313         /*!
314          * \brief Outbound registration client
315          * \note May only be accessed within the serializer thread
316          * because it might get destroyed and set to NULL for
317          * module unload.
318          */
319         pjsip_regc *client;
320         /*! \brief Timer entry for retrying on temporal responses */
321         pj_timer_entry timer;
322         /*! \brief Optional line parameter placed into Contact */
323         char line[LINE_PARAMETER_SIZE];
324         /*! \brief Current number of retries */
325         unsigned int retries;
326         /*! \brief Maximum number of retries permitted */
327         unsigned int max_retries;
328         /*! \brief Interval at which retries should occur for temporal responses */
329         unsigned int retry_interval;
330         /*! \brief Interval at which retries should occur for permanent responses */
331         unsigned int forbidden_retry_interval;
332         /*! \brief Interval at which retries should occur for all permanent responses */
333         unsigned int fatal_retry_interval;
334         /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
335         unsigned int auth_rejection_permanent;
336         /*! \brief Determines whether SIP Path support should be advertised */
337         unsigned int support_path;
338         /*! \brief Serializer for stuff and things */
339         struct ast_taskprocessor *serializer;
340         /*! \brief Configured authentication credentials */
341         struct ast_sip_auth_vector outbound_auths;
342         /*! \brief Registration should be destroyed after completion of transaction */
343         unsigned int destroy:1;
344         /*! \brief Non-zero if we have attempted sending a REGISTER with authentication */
345         unsigned int auth_attempted:1;
346 };
347
348 /*! \brief Outbound registration state information (persists for lifetime that registration should exist) */
349 struct sip_outbound_registration_state {
350         /*! \brief Outbound registration configuration object */
351         struct sip_outbound_registration *registration;
352         /*! \brief Client state information */
353         struct sip_outbound_registration_client_state *client_state;
354 };
355
356 /*! Time needs to be long enough for a transaction to timeout if nothing replies. */
357 #define MAX_UNLOAD_TIMEOUT_TIME         35      /* Seconds */
358
359 /*! Shutdown group to monitor sip_outbound_registration_client_state serializers. */
360 static struct ast_serializer_shutdown_group *shutdown_group;
361
362 /*! \brief Default number of state container buckets */
363 #define DEFAULT_STATE_BUCKETS 53
364 static AO2_GLOBAL_OBJ_STATIC(current_states);
365
366 /*! \brief hashing function for state objects */
367 static int registration_state_hash(const void *obj, const int flags)
368 {
369         const struct sip_outbound_registration_state *object;
370         const char *key;
371
372         switch (flags & OBJ_SEARCH_MASK) {
373         case OBJ_SEARCH_KEY:
374                 key = obj;
375                 break;
376         case OBJ_SEARCH_OBJECT:
377                 object = obj;
378                 key = ast_sorcery_object_get_id(object->registration);
379                 break;
380         default:
381                 ast_assert(0);
382                 return 0;
383         }
384         return ast_str_hash(key);
385 }
386
387 /*! \brief comparator function for state objects */
388 static int registration_state_cmp(void *obj, void *arg, int flags)
389 {
390         const struct sip_outbound_registration_state *object_left = obj;
391         const struct sip_outbound_registration_state *object_right = arg;
392         const char *right_key = arg;
393         int cmp;
394
395         switch (flags & OBJ_SEARCH_MASK) {
396         case OBJ_SEARCH_OBJECT:
397                 right_key = ast_sorcery_object_get_id(object_right->registration);
398                 /* Fall through */
399         case OBJ_SEARCH_KEY:
400                 cmp = strcmp(ast_sorcery_object_get_id(object_left->registration), right_key);
401                 break;
402         case OBJ_SEARCH_PARTIAL_KEY:
403                 /* Not supported by container. */
404                 ast_assert(0);
405                 return 0;
406         default:
407                 cmp = 0;
408                 break;
409         }
410         if (cmp) {
411                 return 0;
412         }
413         return CMP_MATCH;
414 }
415
416 static struct sip_outbound_registration_state *get_state(const char *id)
417 {
418         struct sip_outbound_registration_state *state = NULL;
419         struct ao2_container *states;
420
421         states = ao2_global_obj_ref(current_states);
422         if (states) {
423                 state = ao2_find(states, id, OBJ_SEARCH_KEY);
424                 ao2_ref(states, -1);
425         }
426         return state;
427 }
428
429 static struct ao2_container *get_registrations(void)
430 {
431         struct ao2_container *registrations = ast_sorcery_retrieve_by_fields(
432                 ast_sip_get_sorcery(), "registration",
433                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
434
435         return registrations;
436 }
437
438 /*! \brief Callback function for matching an outbound registration based on line */
439 static int line_identify_relationship(void *obj, void *arg, int flags)
440 {
441         struct sip_outbound_registration_state *state = obj;
442         pjsip_param *line = arg;
443
444         return !pj_strcmp2(&line->value, state->client_state->line) ? CMP_MATCH | CMP_STOP : 0;
445 }
446
447 static struct pjsip_param *get_uri_option_line(const void *uri)
448 {
449         pjsip_sip_uri *pjuri;
450         static const pj_str_t LINE_STR = { "line", 4 };
451
452         if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri)) {
453                 return NULL;
454         }
455         pjuri = pjsip_uri_get_uri(uri);
456         return pjsip_param_find(&pjuri->other_param, &LINE_STR);
457 }
458
459 /*! \brief Endpoint identifier which uses the 'line' parameter to establish a relationship to an outgoing registration */
460 static struct ast_sip_endpoint *line_identify(pjsip_rx_data *rdata)
461 {
462         pjsip_param *line;
463         RAII_VAR(struct ao2_container *, states, NULL, ao2_cleanup);
464         RAII_VAR(struct sip_outbound_registration_state *, state, NULL, ao2_cleanup);
465
466         if (!(line = get_uri_option_line(rdata->msg_info.to->uri))
467                 && !(line = get_uri_option_line(rdata->msg_info.msg->line.req.uri))) {
468                 return NULL;
469         }
470
471         states = ao2_global_obj_ref(current_states);
472         if (!states) {
473                 return NULL;
474         }
475
476         state = ao2_callback(states, 0, line_identify_relationship, line);
477         if (!state || ast_strlen_zero(state->registration->endpoint)) {
478                 return NULL;
479         }
480
481         ast_debug(3, "Determined relationship to outbound registration '%s' based on line '%s', using configured endpoint '%s'\n",
482                 ast_sorcery_object_get_id(state->registration), state->client_state->line, state->registration->endpoint);
483
484         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", state->registration->endpoint);
485 }
486
487 static struct ast_sip_endpoint_identifier line_identifier = {
488         .identify_endpoint = line_identify,
489 };
490
491 /*! \brief Helper function which cancels the timer on a client */
492 static void cancel_registration(struct sip_outbound_registration_client_state *client_state)
493 {
494         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &client_state->timer)) {
495                 /* The timer was successfully cancelled, drop the refcount of client_state */
496                 ao2_ref(client_state, -1);
497         }
498 }
499
500 static pj_str_t PATH_NAME = { "path", 4 };
501
502 /*! \brief Helper function which sends a message and cleans up, if needed, on failure */
503 static pj_status_t registration_client_send(struct sip_outbound_registration_client_state *client_state,
504         pjsip_tx_data *tdata)
505 {
506         pj_status_t status;
507         int *callback_invoked;
508
509         callback_invoked = ast_threadstorage_get(&register_callback_invoked, sizeof(int));
510         if (!callback_invoked) {
511                 return PJ_ENOMEM;
512         }
513         *callback_invoked = 0;
514
515         /* Due to the message going out the callback may now be invoked, so bump the count */
516         ao2_ref(client_state, +1);
517         status = pjsip_regc_send(client_state->client, tdata);
518
519         /* If the attempt to send the message failed and the callback was not invoked we need to
520          * drop the reference we just added
521          */
522         if ((status != PJ_SUCCESS) && !(*callback_invoked)) {
523                 ao2_ref(client_state, -1);
524         }
525
526         return status;
527 }
528
529 /*! \brief Callback function for registering */
530 static int handle_client_registration(void *data)
531 {
532         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
533         pjsip_tx_data *tdata;
534         pjsip_regc_info info;
535         char server_uri[PJSIP_MAX_URL_SIZE];
536         char client_uri[PJSIP_MAX_URL_SIZE];
537
538         if (client_state->status == SIP_REGISTRATION_STOPPED
539                 || pjsip_regc_register(client_state->client, PJ_FALSE, &tdata) != PJ_SUCCESS) {
540                 return 0;
541         }
542
543         pjsip_regc_get_info(client_state->client, &info);
544         ast_copy_pj_str(server_uri, &info.server_uri, sizeof(server_uri));
545         ast_copy_pj_str(client_uri, &info.client_uri, sizeof(client_uri));
546         ast_debug(1, "Outbound REGISTER attempt %u to '%s' with client '%s'\n",
547                 client_state->retries + 1, server_uri, client_uri);
548
549         if (client_state->support_path) {
550                 pjsip_supported_hdr *hdr;
551
552                 hdr = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_SUPPORTED, NULL);
553                 if (!hdr) {
554                         /* insert a new Supported header */
555                         hdr = pjsip_supported_hdr_create(tdata->pool);
556                         if (!hdr) {
557                                 return -1;
558                         }
559
560                         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *)hdr);
561                 }
562
563                 /* add on to the existing Supported header */
564                 pj_strassign(&hdr->values[hdr->count++], &PATH_NAME);
565         }
566
567         registration_client_send(client_state, tdata);
568
569         return 0;
570 }
571
572 /*! \brief Timer callback function, used just for registrations */
573 static void sip_outbound_registration_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
574 {
575         struct sip_outbound_registration_client_state *client_state = entry->user_data;
576
577         entry->id = 0;
578
579         /*
580          * Transfer client_state reference to serializer task so the
581          * nominal path will not dec the client_state ref in this
582          * pjproject callback thread.
583          */
584         if (ast_sip_push_task(client_state->serializer, handle_client_registration, client_state)) {
585                 ast_log(LOG_WARNING, "Scheduled outbound registration could not be executed.\n");
586                 ao2_ref(client_state, -1);
587         }
588 }
589
590 /*! \brief Helper function which sets up the timer to re-register in a specific amount of time */
591 static void schedule_registration(struct sip_outbound_registration_client_state *client_state, unsigned int seconds)
592 {
593         pj_time_val delay = { .sec = seconds, };
594         pjsip_regc_info info;
595
596         cancel_registration(client_state);
597
598         pjsip_regc_get_info(client_state->client, &info);
599         ast_debug(1, "Scheduling outbound registration to server '%.*s' from client '%.*s' in %d seconds\n",
600                         (int) info.server_uri.slen, info.server_uri.ptr,
601                         (int) info.client_uri.slen, info.client_uri.ptr,
602                         seconds);
603
604         ao2_ref(client_state, +1);
605         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &client_state->timer, &delay) != PJ_SUCCESS) {
606                 ast_log(LOG_WARNING, "Failed to schedule registration to server '%.*s' from client '%.*s'\n",
607                                 (int) info.server_uri.slen, info.server_uri.ptr,
608                                 (int) info.client_uri.slen, info.client_uri.ptr);
609                 ao2_ref(client_state, -1);
610         }
611 }
612
613 /*! \brief Callback function for unregistering (potentially) and destroying state */
614 static int handle_client_state_destruction(void *data)
615 {
616         struct sip_outbound_registration_client_state *client_state = data;
617
618         cancel_registration(client_state);
619
620         if (client_state->client) {
621                 pjsip_regc_info info;
622                 pjsip_tx_data *tdata;
623
624                 pjsip_regc_get_info(client_state->client, &info);
625
626                 if (info.is_busy == PJ_TRUE) {
627                         /* If a client transaction is in progress we defer until it is complete */
628                         ast_debug(1,
629                                 "Registration transaction is busy with server '%.*s' from client '%.*s'.\n",
630                                 (int) info.server_uri.slen, info.server_uri.ptr,
631                                 (int) info.client_uri.slen, info.client_uri.ptr);
632                         client_state->destroy = 1;
633                         ao2_ref(client_state, -1);
634                         return 0;
635                 }
636
637                 switch (client_state->status) {
638                 case SIP_REGISTRATION_UNREGISTERED:
639                         break;
640                 case SIP_REGISTRATION_REGISTERED:
641                         ast_debug(1,
642                                 "Trying to unregister with server '%.*s' from client '%.*s' before destruction.\n",
643                                 (int) info.server_uri.slen, info.server_uri.ptr,
644                                 (int) info.client_uri.slen, info.client_uri.ptr);
645
646                         client_state->status = SIP_REGISTRATION_STOPPING;
647                         client_state->destroy = 1;
648                         if (pjsip_regc_unregister(client_state->client, &tdata) == PJ_SUCCESS
649                                 && registration_client_send(client_state, tdata) == PJ_SUCCESS) {
650                                 ao2_ref(client_state, -1);
651                                 return 0;
652                         }
653                         break;
654                 case SIP_REGISTRATION_REJECTED_TEMPORARY:
655                 case SIP_REGISTRATION_REJECTED_PERMANENT:
656                 case SIP_REGISTRATION_STOPPING:
657                 case SIP_REGISTRATION_STOPPED:
658                         break;
659                 }
660
661                 pjsip_regc_destroy(client_state->client);
662                 client_state->client = NULL;
663         }
664
665         client_state->status = SIP_REGISTRATION_STOPPED;
666         ast_sip_auth_vector_destroy(&client_state->outbound_auths);
667         ao2_ref(client_state, -1);
668
669         return 0;
670 }
671
672 /*! \brief Structure for registration response */
673 struct registration_response {
674         /*! \brief Response code for the registration attempt */
675         int code;
676         /*! \brief Expiration time for registration */
677         int expiration;
678         /*! \brief Retry-After value */
679         int retry_after;
680         /*! \brief Outbound registration client state */
681         struct sip_outbound_registration_client_state *client_state;
682         /*! \brief The response message */
683         pjsip_rx_data *rdata;
684         /*! \brief Request for which the response was received */
685         pjsip_tx_data *old_request;
686 };
687
688 /*! \brief Registration response structure destructor */
689 static void registration_response_destroy(void *obj)
690 {
691         struct registration_response *response = obj;
692
693         if (response->rdata) {
694                 pjsip_rx_data_free_cloned(response->rdata);
695         }
696
697         if (response->old_request) {
698                 pjsip_tx_data_dec_ref(response->old_request);
699         }
700
701         ao2_cleanup(response->client_state);
702 }
703
704 /*! \brief Helper function which determines if a response code is temporal or not */
705 static int sip_outbound_registration_is_temporal(unsigned int code,
706                 struct sip_outbound_registration_client_state *client_state)
707 {
708         /* Shamelessly taken from pjsua */
709         if (code == PJSIP_SC_REQUEST_TIMEOUT ||
710                 code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
711                 code == PJSIP_SC_BAD_GATEWAY ||
712                 code == PJSIP_SC_SERVICE_UNAVAILABLE ||
713                 code == PJSIP_SC_SERVER_TIMEOUT ||
714                 ((code == PJSIP_SC_UNAUTHORIZED ||
715                   code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED) &&
716                  !client_state->auth_rejection_permanent) ||
717                 PJSIP_IS_STATUS_IN_CLASS(code, 600)) {
718                 return 1;
719         } else {
720                 return 0;
721         }
722 }
723
724 static void schedule_retry(struct registration_response *response, unsigned int interval,
725                            const char *server_uri, const char *client_uri)
726 {
727         response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
728         schedule_registration(response->client_state, interval);
729
730         if (response->rdata) {
731                 ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on "
732                         "registration attempt to '%s', retrying in '%u'\n",
733                         response->code, server_uri, client_uri, interval);
734         } else {
735                 ast_log(LOG_WARNING, "No response received from '%s' on "
736                         "registration attempt to '%s', retrying in '%u'\n",
737                         server_uri, client_uri, interval);
738         }
739 }
740
741 /*! \brief Callback function for handling a response to a registration attempt */
742 static int handle_registration_response(void *data)
743 {
744         struct registration_response *response = data;
745         pjsip_regc_info info;
746         char server_uri[PJSIP_MAX_URL_SIZE];
747         char client_uri[PJSIP_MAX_URL_SIZE];
748
749         if (response->client_state->status == SIP_REGISTRATION_STOPPED) {
750                 ao2_ref(response, -1);
751                 return 0;
752         }
753
754         pjsip_regc_get_info(response->client_state->client, &info);
755         ast_copy_pj_str(server_uri, &info.server_uri, sizeof(server_uri));
756         ast_copy_pj_str(client_uri, &info.client_uri, sizeof(client_uri));
757
758         ast_debug(1, "Processing REGISTER response %d from server '%s' for client '%s'\n",
759                         response->code, server_uri, client_uri);
760
761         if (!response->client_state->auth_attempted &&
762                         (response->code == 401 || response->code == 407)) {
763                 pjsip_tx_data *tdata;
764                 if (!ast_sip_create_request_with_auth(&response->client_state->outbound_auths,
765                                 response->rdata, response->old_request, &tdata)) {
766                         response->client_state->auth_attempted = 1;
767                         ast_debug(1, "Sending authenticated REGISTER to server '%s' from client '%s'\n",
768                                         server_uri, client_uri);
769                         if (registration_client_send(response->client_state, tdata) == PJ_SUCCESS) {
770                                 ao2_ref(response, -1);
771                                 return 0;
772                         }
773                 } else {
774                         ast_log(LOG_WARNING, "Failed to create authenticated REGISTER request to server '%s' from client '%s'\n",
775                                         server_uri, client_uri);
776                 }
777                 /* Otherwise, fall through so the failure is processed appropriately */
778         }
779
780         response->client_state->auth_attempted = 0;
781
782         if (PJSIP_IS_STATUS_IN_CLASS(response->code, 200)) {
783                 /* Check if this is in regards to registering or unregistering */
784                 if (response->expiration) {
785                         /* If the registration went fine simply reschedule registration for the future */
786                         ast_debug(1, "Outbound registration to '%s' with client '%s' successful\n", server_uri, client_uri);
787                         response->client_state->status = SIP_REGISTRATION_REGISTERED;
788                         response->client_state->retries = 0;
789                         schedule_registration(response->client_state, response->expiration - REREGISTER_BUFFER_TIME);
790                 } else {
791                         ast_debug(1, "Outbound unregistration to '%s' with client '%s' successful\n", server_uri, client_uri);
792                         response->client_state->status = SIP_REGISTRATION_UNREGISTERED;
793                 }
794         } else if (response->client_state->destroy) {
795                 /* We need to deal with the pending destruction instead. */
796         } else if (response->retry_after) {
797                 /* If we have been instructed to retry after a period of time, schedule it as such */
798                 schedule_retry(response, response->retry_after, server_uri, client_uri);
799         } else if (response->client_state->retry_interval
800                 && sip_outbound_registration_is_temporal(response->code, response->client_state)) {
801                 if (response->client_state->retries == response->client_state->max_retries) {
802                         /* If we received enough temporal responses to exceed our maximum give up permanently */
803                         response->client_state->status = SIP_REGISTRATION_REJECTED_PERMANENT;
804                         ast_log(LOG_WARNING, "Maximum retries reached when attempting outbound registration to '%s' with client '%s', stopping registration attempt\n",
805                                 server_uri, client_uri);
806                 } else {
807                         /* On the other hand if we can still try some more do so */
808                         response->client_state->retries++;
809                         schedule_retry(response, response->client_state->retry_interval, server_uri, client_uri);
810                 }
811         } else {
812                 if (response->code == 403
813                         && response->client_state->forbidden_retry_interval
814                         && response->client_state->retries < response->client_state->max_retries) {
815                         /* A forbidden response retry interval is configured and there are retries remaining */
816                         response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
817                         response->client_state->retries++;
818                         schedule_registration(response->client_state, response->client_state->forbidden_retry_interval);
819                         ast_log(LOG_WARNING, "403 Forbidden fatal response received from '%s' on registration attempt to '%s', retrying in '%u' seconds\n",
820                                 server_uri, client_uri, response->client_state->forbidden_retry_interval);
821                 } else if (response->client_state->fatal_retry_interval
822                            && response->client_state->retries < response->client_state->max_retries) {
823                         /* Some kind of fatal failure response received, so retry according to configured interval */
824                         response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
825                         response->client_state->retries++;
826                         schedule_registration(response->client_state, response->client_state->fatal_retry_interval);
827                         ast_log(LOG_WARNING, "'%d' fatal response received from '%s' on registration attempt to '%s', retrying in '%u' seconds\n",
828                                 response->code, server_uri, client_uri, response->client_state->fatal_retry_interval);
829                 } else {
830                         /* Finally if there's no hope of registering give up */
831                         response->client_state->status = SIP_REGISTRATION_REJECTED_PERMANENT;
832                         if (response->rdata) {
833                                 ast_log(LOG_WARNING, "Fatal response '%d' received from '%s' on registration attempt to '%s', stopping outbound registration\n",
834                                         response->code, server_uri, client_uri);
835                         } else {
836                                 ast_log(LOG_WARNING, "Fatal registration attempt to '%s', stopping outbound registration\n", client_uri);
837                         }
838                 }
839         }
840
841         ast_system_publish_registry("PJSIP", client_uri, server_uri,
842                 sip_outbound_registration_status_str(response->client_state->status), NULL);
843
844         if (response->client_state->destroy) {
845                 /* We have a pending deferred destruction to complete now. */
846                 ao2_ref(response->client_state, +1);
847                 handle_client_state_destruction(response->client_state);
848         }
849
850         ao2_ref(response, -1);
851         return 0;
852 }
853
854 /*! \brief Callback function for outbound registration client */
855 static void sip_outbound_registration_response_cb(struct pjsip_regc_cbparam *param)
856 {
857         struct sip_outbound_registration_client_state *client_state = param->token;
858         struct registration_response *response;
859         int *callback_invoked;
860
861         callback_invoked = ast_threadstorage_get(&register_callback_invoked, sizeof(int));
862
863         ast_assert(callback_invoked != NULL);
864         ast_assert(client_state != NULL);
865
866         *callback_invoked = 1;
867
868         response = ao2_alloc(sizeof(*response), registration_response_destroy);
869         if (!response) {
870                 ao2_ref(client_state, -1);
871                 return;
872         }
873         response->code = param->code;
874         response->expiration = param->expiration;
875         /*
876          * Transfer client_state reference to response so the
877          * nominal path will not dec the client_state ref in this
878          * pjproject callback thread.
879          */
880         response->client_state = client_state;
881
882         ast_debug(1, "Received REGISTER response %d(%.*s)\n",
883                 param->code, (int) param->reason.slen, param->reason.ptr);
884
885         if (param->rdata) {
886                 struct pjsip_retry_after_hdr *retry_after;
887                 pjsip_transaction *tsx;
888
889                 retry_after = pjsip_msg_find_hdr(param->rdata->msg_info.msg, PJSIP_H_RETRY_AFTER,
890                         NULL);
891                 response->retry_after = retry_after ? retry_after->ivalue : 0;
892                 tsx = pjsip_rdata_get_tsx(param->rdata);
893                 response->old_request = tsx->last_tx;
894                 pjsip_tx_data_add_ref(response->old_request);
895                 pjsip_rx_data_clone(param->rdata, 0, &response->rdata);
896         }
897
898         /*
899          * Transfer response reference to serializer task so the
900          * nominal path will not dec the response ref in this
901          * pjproject callback thread.
902          */
903         if (ast_sip_push_task(client_state->serializer, handle_registration_response, response)) {
904                 ast_log(LOG_WARNING, "Failed to pass incoming registration response to threadpool\n");
905                 ao2_cleanup(response);
906         }
907 }
908
909 /*! \brief Destructor function for registration state */
910 static void sip_outbound_registration_state_destroy(void *obj)
911 {
912         struct sip_outbound_registration_state *state = obj;
913
914         ast_debug(3, "Destroying registration state for registration to server '%s' from client '%s'\n",
915                         state->registration->server_uri, state->registration->client_uri);
916
917         ao2_cleanup(state->registration);
918
919         if (!state->client_state) {
920                 /* Nothing to do */
921         } else if (!state->client_state->serializer) {
922                 ao2_ref(state->client_state, -1);
923         } else if (ast_sip_push_task(state->client_state->serializer,
924                 handle_client_state_destruction, state->client_state)) {
925                 ast_log(LOG_WARNING, "Failed to pass outbound registration client destruction to threadpool\n");
926                 ao2_ref(state->client_state, -1);
927         }
928 }
929
930 /*! \brief Destructor function for client registration state */
931 static void sip_outbound_registration_client_state_destroy(void *obj)
932 {
933         struct sip_outbound_registration_client_state *client_state = obj;
934
935         ast_taskprocessor_unreference(client_state->serializer);
936 }
937
938 /*! \brief Allocator function for registration state */
939 static struct sip_outbound_registration_state *sip_outbound_registration_state_alloc(struct sip_outbound_registration *registration)
940 {
941         struct sip_outbound_registration_state *state;
942
943         state = ao2_alloc(sizeof(*state), sip_outbound_registration_state_destroy);
944         if (!state) {
945                 return NULL;
946         }
947         state->client_state = ao2_alloc(sizeof(*state->client_state),
948                 sip_outbound_registration_client_state_destroy);
949         if (!state->client_state) {
950                 ao2_cleanup(state);
951                 return NULL;
952         }
953
954         state->client_state->serializer = ast_sip_create_serializer_group(shutdown_group);
955         if (!state->client_state->serializer) {
956                 ao2_cleanup(state);
957                 return NULL;
958         }
959         state->client_state->status = SIP_REGISTRATION_UNREGISTERED;
960         state->client_state->timer.user_data = state->client_state;
961         state->client_state->timer.cb = sip_outbound_registration_timer_cb;
962
963         state->registration = ao2_bump(registration);
964         return state;
965 }
966
967 /*! \brief Destructor function for registration information */
968 static void sip_outbound_registration_destroy(void *obj)
969 {
970         struct sip_outbound_registration *registration = obj;
971
972         ast_sip_auth_vector_destroy(&registration->outbound_auths);
973
974         ast_string_field_free_memory(registration);
975 }
976
977 /*! \brief Allocator function for registration information */
978 static void *sip_outbound_registration_alloc(const char *name)
979 {
980         struct sip_outbound_registration *registration;
981
982         registration = ast_sorcery_generic_alloc(sizeof(*registration),
983                 sip_outbound_registration_destroy);
984         if (!registration || ast_string_field_init(registration, 256)) {
985                 ao2_cleanup(registration);
986                 return NULL;
987         }
988
989         return registration;
990 }
991
992 /*! \brief Helper function which populates a pj_str_t with a contact header */
993 static int sip_dialog_create_contact(pj_pool_t *pool, pj_str_t *contact, const char *user,
994         const pj_str_t *target, pjsip_tpselector *selector, const char *line)
995 {
996         pj_str_t tmp, local_addr;
997         pjsip_uri *uri;
998         pjsip_sip_uri *sip_uri;
999         pjsip_transport_type_e type = PJSIP_TRANSPORT_UNSPECIFIED;
1000         int local_port;
1001
1002         pj_strdup_with_null(pool, &tmp, target);
1003
1004         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
1005             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
1006                 return -1;
1007         }
1008
1009         sip_uri = pjsip_uri_get_uri(uri);
1010
1011         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
1012                 type = PJSIP_TRANSPORT_TLS;
1013         } else if (!sip_uri->transport_param.slen) {
1014                 type = PJSIP_TRANSPORT_UDP;
1015         } else {
1016                 type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
1017         }
1018
1019         if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
1020                 return -1;
1021         }
1022
1023         if (pj_strchr(&sip_uri->host, ':')) {
1024                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
1025         }
1026
1027         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()),
1028                 pool, type, selector, &local_addr, &local_port) != PJ_SUCCESS) {
1029                 return -1;
1030         }
1031
1032         if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
1033                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
1034         }
1035
1036         contact->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
1037         contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
1038                 "<%s:%s@%s%.*s%s:%d%s%s%s%s>",
1039                 (pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) ? "sips" : "sip",
1040                 user,
1041                 (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
1042                 (int)local_addr.slen,
1043                 local_addr.ptr,
1044                 (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
1045                 local_port,
1046                 (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
1047                 (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "",
1048                 !ast_strlen_zero(line) ? ";line=" : "",
1049                 S_OR(line, ""));
1050
1051         return 0;
1052 }
1053
1054 /*!
1055  * \internal
1056  * \brief Check if a registration can be reused
1057  *
1058  * This checks if the existing outbound registration's configuration differs from a newly-applied
1059  * outbound registration to see if the applied one.
1060  *
1061  * \param existing The pre-existing outbound registration
1062  * \param applied The newly-created registration
1063  */
1064 static int can_reuse_registration(struct sip_outbound_registration *existing,
1065         struct sip_outbound_registration *applied)
1066 {
1067         int rc = 1;
1068         struct ast_sorcery *sorcery = ast_sip_get_sorcery();
1069         struct ast_variable *ve = ast_sorcery_objectset_create(sorcery, existing);
1070         struct ast_variable *va = ast_sorcery_objectset_create(sorcery, applied);
1071         struct ast_variable *vc = NULL;
1072
1073         if (ast_sorcery_changeset_create(ve, va, &vc) || vc != NULL) {
1074                 rc = 0;
1075                 ast_debug(4, "Registration '%s' changed.  Can't re-use.\n", ast_sorcery_object_get_id(existing));
1076         } else {
1077                 ast_debug(4, "Registration '%s' didn't change.  Can re-use\n", ast_sorcery_object_get_id(existing));
1078         }
1079
1080         ast_variables_destroy(ve);
1081         ast_variables_destroy(va);
1082         ast_variables_destroy(vc);
1083
1084         return rc;
1085 }
1086
1087 /*! \brief Helper function that allocates a pjsip registration client and configures it */
1088 static int sip_outbound_registration_regc_alloc(void *data)
1089 {
1090         struct sip_outbound_registration_state *state = data;
1091         RAII_VAR(struct sip_outbound_registration *, registration,
1092                  ao2_bump(state->registration), ao2_cleanup);
1093         pj_pool_t *pool;
1094         pj_str_t tmp;
1095         pjsip_uri *uri;
1096         pj_str_t server_uri, client_uri, contact_uri;
1097         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
1098
1099         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "URI Validation", 256, 256);
1100         if (!pool) {
1101                 ast_log(LOG_ERROR, "Could not create pool for URI validation on outbound registration '%s'\n",
1102                         ast_sorcery_object_get_id(registration));
1103                 return -1;
1104         }
1105
1106         pj_strdup2_with_null(pool, &tmp, registration->server_uri);
1107         uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
1108         if (!uri) {
1109                 ast_log(LOG_ERROR, "Invalid server URI '%s' specified on outbound registration '%s'\n",
1110                         registration->server_uri, ast_sorcery_object_get_id(registration));
1111                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1112                 return -1;
1113         }
1114
1115         pj_strdup2_with_null(pool, &tmp, registration->client_uri);
1116         uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
1117         if (!uri) {
1118                 ast_log(LOG_ERROR, "Invalid client URI '%s' specified on outbound registration '%s'\n",
1119                         registration->client_uri, ast_sorcery_object_get_id(registration));
1120                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1121                 return -1;
1122         }
1123
1124         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1125
1126         if (!ast_strlen_zero(registration->transport)) {
1127                 RAII_VAR(struct ast_sip_transport *, transport, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", registration->transport), ao2_cleanup);
1128
1129                 if (!transport || !transport->state) {
1130                         ast_log(LOG_ERROR, "Unable to retrieve PJSIP transport '%s' "
1131                                 " for outbound registration", registration->transport);
1132                         return -1;
1133                 }
1134
1135                 if (transport->state->transport) {
1136                         selector.type = PJSIP_TPSELECTOR_TRANSPORT;
1137                         selector.u.transport = transport->state->transport;
1138                 } else if (transport->state->factory) {
1139                         selector.type = PJSIP_TPSELECTOR_LISTENER;
1140                         selector.u.listener = transport->state->factory;
1141                 } else {
1142                         return -1;
1143                 }
1144         }
1145
1146         ast_assert(state->client_state->client == NULL);
1147         if (pjsip_regc_create(ast_sip_get_pjsip_endpoint(), state->client_state,
1148                         sip_outbound_registration_response_cb,
1149                         &state->client_state->client) != PJ_SUCCESS) {
1150                 return -1;
1151         }
1152
1153         pjsip_regc_set_transport(state->client_state->client, &selector);
1154
1155         if (!ast_strlen_zero(registration->outbound_proxy)) {
1156                 pjsip_route_hdr route_set, *route;
1157                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
1158                 pj_str_t tmp;
1159
1160                 pj_list_init(&route_set);
1161
1162                 pj_strdup2_with_null(pjsip_regc_get_pool(state->client_state->client), &tmp,
1163                         registration->outbound_proxy);
1164                 route = pjsip_parse_hdr(pjsip_regc_get_pool(state->client_state->client),
1165                         &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL);
1166                 if (!route) {
1167                         return -1;
1168                 }
1169                 pj_list_insert_nodes_before(&route_set, route);
1170
1171                 pjsip_regc_set_route_set(state->client_state->client, &route_set);
1172         }
1173
1174         if (state->registration->line) {
1175                 ast_generate_random_string(state->client_state->line, sizeof(state->client_state->line));
1176         }
1177
1178         pj_cstr(&server_uri, registration->server_uri);
1179
1180
1181         if (sip_dialog_create_contact(pjsip_regc_get_pool(state->client_state->client),
1182                 &contact_uri, S_OR(registration->contact_user, "s"), &server_uri, &selector,
1183                 state->client_state->line)) {
1184                 return -1;
1185         }
1186
1187         pj_cstr(&client_uri, registration->client_uri);
1188         if (pjsip_regc_init(state->client_state->client, &server_uri, &client_uri,
1189                 &client_uri, 1, &contact_uri, registration->expiration) != PJ_SUCCESS) {
1190                 return -1;
1191         }
1192
1193         return 0;
1194 }
1195
1196 /*! \brief Helper function which performs a single registration */
1197 static int sip_outbound_registration_perform(void *data)
1198 {
1199         struct sip_outbound_registration_state *state = data;
1200         struct sip_outbound_registration *registration = ao2_bump(state->registration);
1201         size_t i;
1202
1203         /* Just in case the client state is being reused for this registration, free the auth information */
1204         ast_sip_auth_vector_destroy(&state->client_state->outbound_auths);
1205
1206         AST_VECTOR_INIT(&state->client_state->outbound_auths, AST_VECTOR_SIZE(&registration->outbound_auths));
1207         for (i = 0; i < AST_VECTOR_SIZE(&registration->outbound_auths); ++i) {
1208                 const char *name = ast_strdup(AST_VECTOR_GET(&registration->outbound_auths, i));
1209
1210                 if (name) {
1211                         AST_VECTOR_APPEND(&state->client_state->outbound_auths, name);
1212                 }
1213         }
1214         state->client_state->retry_interval = registration->retry_interval;
1215         state->client_state->forbidden_retry_interval = registration->forbidden_retry_interval;
1216         state->client_state->fatal_retry_interval = registration->fatal_retry_interval;
1217         state->client_state->max_retries = registration->max_retries;
1218         state->client_state->retries = 0;
1219         state->client_state->support_path = registration->support_path;
1220         state->client_state->auth_rejection_permanent = registration->auth_rejection_permanent;
1221
1222         pjsip_regc_update_expires(state->client_state->client, registration->expiration);
1223
1224         schedule_registration(state->client_state, (ast_random() % 10) + 1);
1225
1226         ao2_ref(registration, -1);
1227         ao2_ref(state, -1);
1228         return 0;
1229 }
1230
1231 /*! \brief Apply function which finds or allocates a state structure */
1232 static int sip_outbound_registration_apply(const struct ast_sorcery *sorcery, void *obj)
1233 {
1234         RAII_VAR(struct ao2_container *, states, ao2_global_obj_ref(current_states), ao2_cleanup);
1235         RAII_VAR(struct sip_outbound_registration_state *, state, NULL, ao2_cleanup);
1236         RAII_VAR(struct sip_outbound_registration_state *, new_state, NULL, ao2_cleanup);
1237         struct sip_outbound_registration *applied = obj;
1238
1239         if (!states) {
1240                 /* Global container has gone.  Likely shutting down. */
1241                 return -1;
1242         }
1243         state = ao2_find(states, ast_sorcery_object_get_id(applied), OBJ_SEARCH_KEY);
1244
1245         ast_debug(4, "Applying configuration to outbound registration '%s'\n", ast_sorcery_object_get_id(applied));
1246
1247         if (ast_strlen_zero(applied->server_uri)) {
1248                 ast_log(LOG_ERROR, "No server URI specified on outbound registration '%s'\n",
1249                         ast_sorcery_object_get_id(applied));
1250                 return -1;
1251         } else if (ast_strlen_zero(applied->client_uri)) {
1252                 ast_log(LOG_ERROR, "No client URI specified on outbound registration '%s'\n",
1253                         ast_sorcery_object_get_id(applied));
1254                 return -1;
1255         } else if (applied->line && ast_strlen_zero(applied->endpoint)) {
1256                 ast_log(LOG_ERROR, "Line support has been enabled on outbound registration '%s' without providing an endpoint\n",
1257                         ast_sorcery_object_get_id(applied));
1258                 return -1;
1259         } else if (!ast_strlen_zero(applied->endpoint) && !applied->line) {
1260                 ast_log(LOG_ERROR, "An endpoint has been specified on outbound registration '%s' without enabling line support\n",
1261                         ast_sorcery_object_get_id(applied));
1262                 return -1;
1263         }
1264
1265         if (state && can_reuse_registration(state->registration, applied)) {
1266                 ast_debug(4,
1267                         "No change between old configuration and new configuration on outbound registration '%s'. Using previous state\n",
1268                         ast_sorcery_object_get_id(applied));
1269
1270                 /*
1271                  * This is OK to replace without relinking the state in the
1272                  * current_states container since state->registration and
1273                  * applied have the same key.
1274                  */
1275                 ao2_lock(states);
1276                 ao2_replace(state->registration, applied);
1277                 ao2_unlock(states);
1278                 return 0;
1279         }
1280
1281         if (!(new_state = sip_outbound_registration_state_alloc(applied))) {
1282                 return -1;
1283         }
1284
1285         if (ast_sip_push_task_synchronous(new_state->client_state->serializer,
1286                 sip_outbound_registration_regc_alloc, new_state)) {
1287                 return -1;
1288         }
1289
1290         if (ast_sip_push_task(new_state->client_state->serializer,
1291                               sip_outbound_registration_perform, ao2_bump(new_state))) {
1292                 ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n",
1293                         ast_sorcery_object_get_id(new_state->registration));
1294                 ao2_ref(new_state, -1);
1295                 return -1;
1296         }
1297
1298         ao2_lock(states);
1299         if (state) {
1300                 ao2_unlink(states, state);
1301         }
1302         ao2_link(states, new_state);
1303         ao2_unlock(states);
1304
1305         return 0;
1306 }
1307
1308 static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1309 {
1310         struct sip_outbound_registration *registration = obj;
1311
1312         return ast_sip_auth_vector_init(&registration->outbound_auths, var->value);
1313 }
1314
1315 static int outbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
1316 {
1317         const struct sip_outbound_registration *registration = obj;
1318
1319         return ast_sip_auths_to_str(&registration->outbound_auths, buf);
1320 }
1321
1322 static int outbound_auths_to_var_list(const void *obj, struct ast_variable **fields)
1323 {
1324         const struct sip_outbound_registration *registration = obj;
1325         int i;
1326         struct ast_variable *head = NULL;
1327
1328         for (i = 0; i < AST_VECTOR_SIZE(&registration->outbound_auths) ; i++) {
1329                 ast_variable_list_append(&head, ast_variable_new("outbound_auth",
1330                         AST_VECTOR_GET(&registration->outbound_auths, i), ""));
1331         }
1332
1333         if (head) {
1334                 *fields = head;
1335         }
1336
1337         return 0;
1338 }
1339
1340 static int unregister_task(void *obj)
1341 {
1342         struct sip_outbound_registration_state *state = obj;
1343         struct pjsip_regc *client = state->client_state->client;
1344         pjsip_tx_data *tdata;
1345         pjsip_regc_info info;
1346
1347         pjsip_regc_get_info(client, &info);
1348         ast_debug(1, "Unregistering contacts with server '%s' from client '%s'\n",
1349                 state->registration->server_uri, state->registration->client_uri);
1350
1351         cancel_registration(state->client_state);
1352
1353         if (pjsip_regc_unregister(client, &tdata) == PJ_SUCCESS) {
1354                 registration_client_send(state->client_state, tdata);
1355         }
1356
1357         ao2_ref(state, -1);
1358         return 0;
1359 }
1360
1361 static int queue_unregister(struct sip_outbound_registration_state *state)
1362 {
1363         ao2_ref(state, +1);
1364         if (ast_sip_push_task(state->client_state->serializer, unregister_task, state)) {
1365                 ao2_ref(state, -1);
1366                 return -1;
1367         }
1368
1369         return 0;
1370 }
1371
1372 static int queue_register(struct sip_outbound_registration_state *state)
1373 {
1374         ao2_ref(state, +1);
1375         if (ast_sip_push_task(state->client_state->serializer, sip_outbound_registration_perform, state)) {
1376                 ao2_ref(state, -1);
1377                 return -1;
1378         }
1379
1380         return 0;
1381 }
1382
1383 static char *cli_complete_registration(const char *line, const char *word,
1384                                        int pos, int state)
1385 {
1386         char *result = NULL;
1387         int wordlen;
1388         int which = 0;
1389         struct sip_outbound_registration *registration;
1390         struct ao2_container *registrations;
1391         struct ao2_iterator i;
1392
1393         if (pos != 3) {
1394                 return NULL;
1395         }
1396
1397         wordlen = strlen(word);
1398         registrations = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
1399                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1400         if (!registrations) {
1401                 return NULL;
1402         }
1403
1404         i = ao2_iterator_init(registrations, 0);
1405         while ((registration = ao2_iterator_next(&i))) {
1406                 const char *name = ast_sorcery_object_get_id(registration);
1407
1408                 if (!strncasecmp(word, name, wordlen) && ++which > state) {
1409                         result = ast_strdup(name);
1410                 }
1411
1412                 ao2_ref(registration, -1);
1413                 if (result) {
1414                         break;
1415                 }
1416         }
1417         ao2_iterator_destroy(&i);
1418
1419         ao2_ref(registrations, -1);
1420         return result;
1421 }
1422
1423 static char *cli_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1424 {
1425         struct sip_outbound_registration_state *state;
1426         const char *registration_name;
1427
1428         switch (cmd) {
1429         case CLI_INIT:
1430                 e->command = "pjsip send unregister";
1431                 e->usage =
1432                         "Usage: pjsip send unregister <registration>\n"
1433                         "       Unregisters the specified outbound registration and stops future registration attempts.\n";
1434                 return NULL;
1435         case CLI_GENERATE:
1436                 return cli_complete_registration(a->line, a->word, a->pos, a->n);
1437         }
1438
1439         if (a->argc != 4) {
1440                 return CLI_SHOWUSAGE;
1441         }
1442
1443         registration_name = a->argv[3];
1444
1445         state = get_state(registration_name);
1446         if (!state) {
1447                 ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
1448                 return CLI_FAILURE;
1449         }
1450
1451         if (queue_unregister(state)) {
1452                 ast_cli(a->fd, "Failed to queue unregistration\n");
1453         }
1454
1455         ao2_ref(state, -1);
1456         return CLI_SUCCESS;
1457 }
1458
1459 static char *cli_register(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1460 {
1461         struct sip_outbound_registration_state *state;
1462         const char *registration_name;
1463
1464         switch (cmd) {
1465         case CLI_INIT:
1466                 e->command = "pjsip send register";
1467                 e->usage =
1468                         "Usage: pjsip send register <registration>\n"
1469                         "       Unregisters the specified outbound "
1470                         "registration then re-registers and re-schedules it.\n";
1471                 return NULL;
1472         case CLI_GENERATE:
1473                 return cli_complete_registration(a->line, a->word, a->pos, a->n);
1474         }
1475
1476         if (a->argc != 4) {
1477                 return CLI_SHOWUSAGE;
1478         }
1479
1480         registration_name = a->argv[3];
1481
1482         state = get_state(registration_name);
1483         if (!state) {
1484                 ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
1485                 return CLI_FAILURE;
1486         }
1487
1488         /* We need to serialize the unregister and register so they need
1489          * to be queued as separate tasks.
1490          */
1491         if (queue_unregister(state)) {
1492                 ast_cli(a->fd, "Failed to queue unregistration\n");
1493         } else if (queue_register(state)) {
1494                 ast_cli(a->fd, "Failed to queue registration\n");
1495         }
1496
1497         ao2_ref(state, -1);
1498         return CLI_SUCCESS;
1499 }
1500
1501 static int ami_unregister(struct mansession *s, const struct message *m)
1502 {
1503         const char *registration_name = astman_get_header(m, "Registration");
1504         struct sip_outbound_registration_state *state;
1505
1506         if (ast_strlen_zero(registration_name)) {
1507                 astman_send_error(s, m, "Registration parameter missing.");
1508                 return 0;
1509         }
1510
1511         state = get_state(registration_name);
1512         if (!state) {
1513                 astman_send_error(s, m, "Unable to retrieve registration entry\n");
1514                 return 0;
1515         }
1516
1517         if (queue_unregister(state)) {
1518                 astman_send_ack(s, m, "Failed to queue unregistration");
1519         } else {
1520                 astman_send_ack(s, m, "Unregistration sent");
1521         }
1522
1523         ao2_ref(state, -1);
1524         return 0;
1525 }
1526
1527 static int ami_register(struct mansession *s, const struct message *m)
1528 {
1529         const char *registration_name = astman_get_header(m, "Registration");
1530         struct sip_outbound_registration_state *state;
1531
1532         if (ast_strlen_zero(registration_name)) {
1533                 astman_send_error(s, m, "Registration parameter missing.");
1534                 return 0;
1535         }
1536
1537         state = get_state(registration_name);
1538         if (!state) {
1539                 astman_send_error(s, m, "Unable to retrieve registration entry\n");
1540                 return 0;
1541         }
1542
1543         /* We need to serialize the unregister and register so they need
1544          * to be queued as separate tasks.
1545          */
1546         if (queue_unregister(state)) {
1547                 astman_send_ack(s, m, "Failed to queue unregistration");
1548         } else if (queue_register(state)) {
1549                 astman_send_ack(s, m, "Failed to queue unregistration");
1550         } else {
1551                 astman_send_ack(s, m, "Reregistration sent");
1552         }
1553
1554         ao2_ref(state, -1);
1555         return 0;
1556 }
1557
1558 struct sip_ami_outbound {
1559         struct ast_sip_ami *ami;
1560         int registered;
1561         int not_registered;
1562         struct sip_outbound_registration *registration;
1563 };
1564
1565 static int ami_outbound_registration_task(void *obj)
1566 {
1567         struct sip_ami_outbound *ami = obj;
1568         struct ast_str *buf;
1569         struct sip_outbound_registration_state *state;
1570
1571         buf = ast_sip_create_ami_event("OutboundRegistrationDetail", ami->ami);
1572         if (!buf) {
1573                 return -1;
1574         }
1575
1576         ast_sip_sorcery_object_to_ami(ami->registration, &buf);
1577
1578         if ((state = get_state(ast_sorcery_object_get_id(ami->registration)))) {
1579                 pjsip_regc_info info;
1580
1581                 if (state->client_state->status == SIP_REGISTRATION_REGISTERED) {
1582                         ++ami->registered;
1583                 } else {
1584                         ++ami->not_registered;
1585                 }
1586
1587                 ast_str_append(&buf, 0, "Status: %s\r\n",
1588                         sip_outbound_registration_status_str(state->client_state->status));
1589
1590                 pjsip_regc_get_info(state->client_state->client, &info);
1591                 ast_str_append(&buf, 0, "NextReg: %d\r\n", info.next_reg);
1592                 ao2_ref(state, -1);
1593         }
1594
1595         astman_append(ami->ami->s, "%s\r\n", ast_str_buffer(buf));
1596         ast_free(buf);
1597
1598         return ast_sip_format_auths_ami(&ami->registration->outbound_auths, ami->ami);
1599 }
1600
1601 static int ami_outbound_registration_detail(void *obj, void *arg, int flags)
1602 {
1603         struct sip_ami_outbound *ami = arg;
1604
1605         ami->registration = obj;
1606         return ast_sip_push_task_synchronous(
1607                 NULL, ami_outbound_registration_task, ami);
1608 }
1609
1610 static int ami_show_outbound_registrations(struct mansession *s,
1611                                            const struct message *m)
1612 {
1613         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
1614         struct sip_ami_outbound ami_outbound = { .ami = &ami };
1615         struct ao2_container *regs;
1616
1617         regs = get_registrations();
1618         if (!regs) {
1619                 astman_send_error(s, m, "Unable to retrieve "
1620                                   "outbound registrations\n");
1621                 return -1;
1622         }
1623
1624         astman_send_listack(s, m, "Following are Events for each Outbound registration",
1625                 "start");
1626
1627         ao2_callback(regs, OBJ_NODATA, ami_outbound_registration_detail, &ami_outbound);
1628
1629         astman_send_list_complete_start(s, m, "OutboundRegistrationDetailComplete",
1630                 ami_outbound.registered + ami_outbound.not_registered);
1631         astman_append(s,
1632                 "Registered: %d\r\n"
1633                 "NotRegistered: %d\r\n",
1634                 ami_outbound.registered,
1635                 ami_outbound.not_registered);
1636         astman_send_list_complete_end(s);
1637
1638         ao2_ref(regs, -1);
1639         return 0;
1640 }
1641
1642 static struct ao2_container *cli_get_container(const char *regex)
1643 {
1644         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
1645         struct ao2_container *s_container;
1646
1647         container = ast_sorcery_retrieve_by_regex(ast_sip_get_sorcery(), "registration", regex);
1648         if (!container) {
1649                 return NULL;
1650         }
1651
1652         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
1653                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
1654         if (!s_container) {
1655                 return NULL;
1656         }
1657
1658         if (ao2_container_dup(s_container, container, 0)) {
1659                 ao2_ref(s_container, -1);
1660                 return NULL;
1661         }
1662
1663         return s_container;
1664 }
1665
1666 static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
1667 {
1668         ao2_callback(container, OBJ_NODATA, callback, args);
1669
1670         return 0;
1671 }
1672
1673 static void *cli_retrieve_by_id(const char *id)
1674 {
1675         struct ao2_container *states;
1676         void *obj = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "registration", id);
1677
1678         if (!obj) {
1679                 /* if the object no longer exists then remove its state  */
1680                 states = ao2_global_obj_ref(current_states);
1681                 if (states) {
1682                         ao2_find(states, id, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
1683                         ao2_ref(states, -1);
1684                 }
1685         }
1686
1687         return obj;
1688 }
1689
1690 static int cli_print_header(void *obj, void *arg, int flags)
1691 {
1692         struct ast_sip_cli_context *context = arg;
1693
1694         ast_assert(context->output_buffer != NULL);
1695
1696         ast_str_append(&context->output_buffer, 0,
1697                 " <Registration/ServerURI..............................>  <Auth..........>  <Status.......>\n");
1698
1699         return 0;
1700 }
1701
1702 static int cli_print_body(void *obj, void *arg, int flags)
1703 {
1704         struct sip_outbound_registration *registration = obj;
1705         struct ast_sip_cli_context *context = arg;
1706         const char *id = ast_sorcery_object_get_id(registration);
1707         struct sip_outbound_registration_state *state = get_state(id);
1708 #define REGISTRATION_URI_FIELD_LEN      53
1709
1710         ast_assert(context->output_buffer != NULL);
1711
1712         if (!state) {
1713                 return 0;
1714         }
1715
1716         ast_str_append(&context->output_buffer, 0, " %-s/%-*.*s  %-16s  %-16s\n",
1717                 id,
1718                 (int) (REGISTRATION_URI_FIELD_LEN - strlen(id)),
1719                 (int) (REGISTRATION_URI_FIELD_LEN - strlen(id)),
1720                 registration->server_uri,
1721                 AST_VECTOR_SIZE(&registration->outbound_auths)
1722                         ? AST_VECTOR_GET(&registration->outbound_auths, 0)
1723                         : "n/a",
1724                 sip_outbound_registration_status_str(state->client_state->status));
1725         ao2_ref(state, -1);
1726
1727         if (context->show_details
1728                 || (context->show_details_only_level_0 && context->indent_level == 0)) {
1729                 ast_str_append(&context->output_buffer, 0, "\n");
1730                 ast_sip_cli_print_sorcery_objectset(registration, context, 0);
1731         }
1732
1733         return 0;
1734 }
1735
1736 /*
1737  * A function pointer to callback needs to be within the
1738  * module in order to avoid problems with an undefined
1739  * symbol when the module is loaded.
1740  */
1741 static char *my_cli_traverse_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1742 {
1743         return ast_sip_cli_traverse_objects(e, cmd, a);
1744 }
1745
1746 static struct ast_cli_entry cli_outbound_registration[] = {
1747         AST_CLI_DEFINE(cli_unregister, "Unregisters outbound registration target"),
1748         AST_CLI_DEFINE(cli_register, "Registers an outbound registration target"),
1749         AST_CLI_DEFINE(my_cli_traverse_objects, "List PJSIP Registrations",
1750                 .command = "pjsip list registrations",
1751                 .usage = "Usage: pjsip list registrations [ like <pattern> ]\n"
1752                                 "       List the configured PJSIP Registrations\n"
1753                                 "       Optional regular expression pattern is used to filter the list.\n"),
1754         AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Registrations",
1755                 .command = "pjsip show registrations",
1756                 .usage = "Usage: pjsip show registrations [ like <pattern> ]\n"
1757                                 "       Show the configured PJSIP Registrations\n"
1758                                 "       Optional regular expression pattern is used to filter the list.\n"),
1759         AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Registration",
1760                 .command = "pjsip show registration",
1761                 .usage = "Usage: pjsip show registration <id>\n"
1762                                  "       Show the configured PJSIP Registration\n"),
1763 };
1764
1765 static struct ast_sip_cli_formatter_entry *cli_formatter;
1766
1767 static void auth_observer(const char *type)
1768 {
1769         struct sip_outbound_registration *registration;
1770         struct sip_outbound_registration_state *state;
1771         struct ao2_container *regs;
1772         const char *registration_id;
1773         struct ao2_iterator i;
1774
1775         ast_debug(4, "Auths updated. Checking for any outbound registrations that are in permanent rejected state so they can be retried\n");
1776
1777         regs = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
1778                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1779         if (!regs || ao2_container_count(regs) == 0) {
1780                 ao2_cleanup(regs);
1781                 return;
1782         }
1783
1784         i = ao2_iterator_init(regs, 0);
1785         for (; (registration = ao2_iterator_next(&i)); ao2_ref(registration, -1)) {
1786                 registration_id = ast_sorcery_object_get_id(registration);
1787                 state = get_state(registration_id);
1788                 if (state && state->client_state->status == SIP_REGISTRATION_REJECTED_PERMANENT) {
1789                         ast_debug(4, "Trying outbound registration '%s' again\n", registration_id);
1790
1791                         if (ast_sip_push_task(state->client_state->serializer,
1792                                               sip_outbound_registration_perform, ao2_bump(state))) {
1793                                 ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n", registration_id);
1794                                 ao2_ref(state, -1);
1795                         }
1796                 }
1797                 ao2_cleanup(state);
1798         }
1799         ao2_iterator_destroy(&i);
1800         ao2_cleanup(regs);
1801 }
1802
1803 static const struct ast_sorcery_observer observer_callbacks_auth = {
1804         .loaded = auth_observer,
1805 };
1806
1807 static int check_state(void *obj, void *arg, int flags)
1808 {
1809         struct sip_outbound_registration_state *state = obj;
1810         struct sip_outbound_registration *registration;
1811
1812         registration = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "registration",
1813                 ast_sorcery_object_get_id(state->registration));
1814         if (!registration) {
1815                 /* This is a dead registration */
1816                 return CMP_MATCH;
1817         }
1818
1819         ao2_ref(registration, -1);
1820         return 0;
1821 }
1822
1823 /*!
1824  * \internal
1825  * \brief Observer to purge dead registration states.
1826  *
1827  * \param name Module name owning the sorcery instance.
1828  * \param sorcery Instance being observed.
1829  * \param object_type Name of object being observed.
1830  * \param reloaded Non-zero if the object is being reloaded.
1831  *
1832  * \return Nothing
1833  */
1834 static void registration_loaded_observer(const char *name, const struct ast_sorcery *sorcery, const char *object_type, int reloaded)
1835 {
1836         struct ao2_container *states;
1837
1838         if (strcmp(object_type, "registration")) {
1839                 /* Not interested */
1840                 return;
1841         }
1842
1843         states = ao2_global_obj_ref(current_states);
1844         if (!states) {
1845                 /* Global container has gone.  Likely shutting down. */
1846                 return;
1847         }
1848
1849         /*
1850          * Refresh the current configured registrations. We don't need to hold
1851          * onto the objects, as the apply handler will cause their states to
1852          * be created appropriately.
1853          */
1854         ao2_cleanup(get_registrations());
1855
1856         /* Now to purge dead registrations. */
1857         ao2_callback(states, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, check_state, NULL);
1858         ao2_ref(states, -1);
1859 }
1860
1861 static const struct ast_sorcery_instance_observer observer_callbacks_registrations = {
1862         .object_type_loaded = registration_loaded_observer,
1863 };
1864
1865 static int unload_module(void)
1866 {
1867         int remaining;
1868
1869         ast_manager_unregister("PJSIPShowRegistrationsOutbound");
1870         ast_manager_unregister("PJSIPUnregister");
1871         ast_manager_unregister("PJSIPRegister");
1872
1873         ast_cli_unregister_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
1874         ast_sip_unregister_cli_formatter(cli_formatter);
1875         cli_formatter = NULL;
1876
1877         ast_sip_unregister_endpoint_identifier(&line_identifier);
1878
1879         ast_sorcery_observer_remove(ast_sip_get_sorcery(), "auth", &observer_callbacks_auth);
1880         ast_sorcery_instance_observer_remove(ast_sip_get_sorcery(), &observer_callbacks_registrations);
1881
1882         ast_sorcery_object_unregister(ast_sip_get_sorcery(), "registration");
1883
1884         ao2_global_obj_release(current_states);
1885
1886         /* Wait for registration serializers to get destroyed. */
1887         ast_debug(2, "Waiting for registration transactions to complete for unload.\n");
1888         remaining = ast_serializer_shutdown_group_join(shutdown_group, MAX_UNLOAD_TIMEOUT_TIME);
1889         if (remaining) {
1890                 /*
1891                  * NOTE: We probably have a sip_outbound_registration_client_state
1892                  * ref leak if the remaining count cannot reach zero after a few
1893                  * minutes of trying to unload.
1894                  */
1895                 ast_log(LOG_WARNING, "Unload incomplete.  Could not stop %d outbound registrations.  Try again later.\n",
1896                         remaining);
1897                 return -1;
1898         }
1899
1900         ast_debug(2, "Successful shutdown.\n");
1901
1902         ao2_cleanup(shutdown_group);
1903         shutdown_group = NULL;
1904
1905         return 0;
1906 }
1907
1908 static int load_module(void)
1909 {
1910         struct ao2_container *new_states;
1911
1912         CHECK_PJSIP_MODULE_LOADED();
1913
1914         shutdown_group = ast_serializer_shutdown_group_alloc();
1915         if (!shutdown_group) {
1916                 return AST_MODULE_LOAD_FAILURE;
1917         }
1918
1919         /* Create outbound registration states container. */
1920         new_states = ao2_container_alloc(DEFAULT_STATE_BUCKETS,
1921                 registration_state_hash, registration_state_cmp);
1922         if (!new_states) {
1923                 ast_log(LOG_ERROR, "Unable to allocate registration states container\n");
1924                 unload_module();
1925                 return AST_MODULE_LOAD_FAILURE;
1926         }
1927         ao2_global_obj_replace_unref(current_states, new_states);
1928         ao2_ref(new_states, -1);
1929
1930         /*
1931          * Register sorcery object descriptions.
1932          */
1933         ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_outbound_registration");
1934         ast_sorcery_apply_default(ast_sip_get_sorcery(), "registration", "config", "pjsip.conf,criteria=type=registration");
1935
1936         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "registration", sip_outbound_registration_alloc, NULL, sip_outbound_registration_apply)) {
1937                 unload_module();
1938                 return AST_MODULE_LOAD_DECLINE;
1939         }
1940
1941         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "type", "", OPT_NOOP_T, 0, 0);
1942         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "server_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, server_uri));
1943         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "client_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, client_uri));
1944         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "contact_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, contact_user));
1945         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, transport));
1946         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, outbound_proxy));
1947         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "expiration", "3600", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, expiration));
1948         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "retry_interval", "60", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, retry_interval));
1949         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "forbidden_retry_interval", "0", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, forbidden_retry_interval));
1950         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "fatal_retry_interval", "0", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, fatal_retry_interval));
1951         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "max_retries", "10", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, max_retries));
1952         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));
1953         ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "registration", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, outbound_auths_to_var_list, 0, 0);
1954         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "support_path", "no", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, support_path));
1955         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "line", "no", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, line));
1956         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, endpoint));
1957
1958         /*
1959          * Register sorcery observers.
1960          */
1961         if (ast_sorcery_instance_observer_add(ast_sip_get_sorcery(),
1962                 &observer_callbacks_registrations)
1963                 || ast_sorcery_observer_add(ast_sip_get_sorcery(), "auth",
1964                         &observer_callbacks_auth)) {
1965                 ast_log(LOG_ERROR, "Unable to register observers.\n");
1966                 unload_module();
1967                 return AST_MODULE_LOAD_FAILURE;
1968         }
1969
1970         /* Register how this module identifies endpoints. */
1971         ast_sip_register_endpoint_identifier(&line_identifier);
1972
1973         /* Register CLI commands. */
1974         cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
1975         if (!cli_formatter) {
1976                 ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
1977                 unload_module();
1978                 return AST_MODULE_LOAD_FAILURE;
1979         }
1980         cli_formatter->name = "registration";
1981         cli_formatter->print_header = cli_print_header;
1982         cli_formatter->print_body = cli_print_body;
1983         cli_formatter->get_container = cli_get_container;
1984         cli_formatter->iterate = cli_iterator;
1985         cli_formatter->get_id = ast_sorcery_object_get_id;
1986         cli_formatter->retrieve_by_id = cli_retrieve_by_id;
1987         ast_sip_register_cli_formatter(cli_formatter);
1988         ast_cli_register_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
1989
1990         /* Register AMI actions. */
1991         ast_manager_register_xml("PJSIPUnregister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_unregister);
1992         ast_manager_register_xml("PJSIPRegister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_register);
1993         ast_manager_register_xml("PJSIPShowRegistrationsOutbound", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_show_outbound_registrations);
1994
1995         /* Load configuration objects */
1996         ast_sorcery_load_object(ast_sip_get_sorcery(), "registration");
1997
1998         return AST_MODULE_LOAD_SUCCESS;
1999 }
2000
2001 static int reload_module(void)
2002 {
2003         ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
2004         return 0;
2005 }
2006
2007 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Outbound Registration Support",
2008         .support_level = AST_MODULE_SUPPORT_CORE,
2009         .load = load_module,
2010         .reload = reload_module,
2011         .unload = unload_module,
2012         .load_pri = AST_MODPRI_APP_DEPEND,
2013 );