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