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