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