res_pjsip: improve realtime performance on CLI 'pjsip show contacts'
[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_if_active(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
516                 &client_state->timer, client_state->timer.id)) {
517                 /* The timer was successfully cancelled, drop the refcount of client_state */
518                 ao2_ref(client_state, -1);
519         }
520 }
521
522 static pj_str_t PATH_NAME = { "path", 4 };
523
524 /*! \brief Helper function which sends a message and cleans up, if needed, on failure */
525 static pj_status_t registration_client_send(struct sip_outbound_registration_client_state *client_state,
526         pjsip_tx_data *tdata)
527 {
528         pj_status_t status;
529         int *callback_invoked;
530         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
531
532         callback_invoked = ast_threadstorage_get(&register_callback_invoked, sizeof(int));
533         if (!callback_invoked) {
534                 pjsip_tx_data_dec_ref(tdata);
535                 return PJ_ENOMEM;
536         }
537         *callback_invoked = 0;
538
539         /* Due to the message going out the callback may now be invoked, so bump the count */
540         ao2_ref(client_state, +1);
541         /*
542          * Set the transport in case transports were reloaded.
543          * When pjproject removes the extraneous error messages produced,
544          * we can check status and only set the transport and resend if there was an error
545          */
546         ast_sip_set_tpselector_from_transport_name(client_state->transport_name, &selector);
547         pjsip_regc_set_transport(client_state->client, &selector);
548         status = pjsip_regc_send(client_state->client, tdata);
549
550         /* If the attempt to send the message failed and the callback was not invoked we need to
551          * drop the reference we just added
552          */
553         if ((status != PJ_SUCCESS) && !(*callback_invoked)) {
554                 ao2_ref(client_state, -1);
555         }
556
557         return status;
558 }
559
560 /*! \brief Callback function for registering */
561 static int handle_client_registration(void *data)
562 {
563         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
564         pjsip_tx_data *tdata;
565
566         if (client_state->status == SIP_REGISTRATION_STOPPED
567                 || pjsip_regc_register(client_state->client, PJ_FALSE, &tdata) != PJ_SUCCESS) {
568                 return 0;
569         }
570
571         if (DEBUG_ATLEAST(1)) {
572                 pjsip_regc_info info;
573
574                 pjsip_regc_get_info(client_state->client, &info);
575                 ast_log(LOG_DEBUG, "Outbound REGISTER attempt %u to '%.*s' with client '%.*s'\n",
576                         client_state->retries + 1,
577                         (int) info.server_uri.slen, info.server_uri.ptr,
578                         (int) info.client_uri.slen, info.client_uri.ptr);
579         }
580
581         if (client_state->support_path) {
582                 pjsip_supported_hdr *hdr;
583
584                 hdr = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_SUPPORTED, NULL);
585                 if (!hdr) {
586                         /* insert a new Supported header */
587                         hdr = pjsip_supported_hdr_create(tdata->pool);
588                         if (!hdr) {
589                                 pjsip_tx_data_dec_ref(tdata);
590                                 return -1;
591                         }
592
593                         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *)hdr);
594                 }
595
596                 /* add on to the existing Supported header */
597                 pj_strassign(&hdr->values[hdr->count++], &PATH_NAME);
598         }
599
600         registration_client_send(client_state, tdata);
601
602         return 0;
603 }
604
605 /*! \brief Timer callback function, used just for registrations */
606 static void sip_outbound_registration_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
607 {
608         struct sip_outbound_registration_client_state *client_state = entry->user_data;
609
610         entry->id = 0;
611
612         /*
613          * Transfer client_state reference to serializer task so the
614          * nominal path will not dec the client_state ref in this
615          * pjproject callback thread.
616          */
617         if (ast_sip_push_task(client_state->serializer, handle_client_registration, client_state)) {
618                 ast_log(LOG_WARNING, "Scheduled outbound registration could not be executed.\n");
619                 ao2_ref(client_state, -1);
620         }
621 }
622
623 /*! \brief Helper function which sets up the timer to re-register in a specific amount of time */
624 static void schedule_registration(struct sip_outbound_registration_client_state *client_state, unsigned int seconds)
625 {
626         pj_time_val delay = { .sec = seconds, };
627         pjsip_regc_info info;
628
629         cancel_registration(client_state);
630
631         pjsip_regc_get_info(client_state->client, &info);
632         ast_debug(1, "Scheduling outbound registration to server '%.*s' from client '%.*s' in %d seconds\n",
633                         (int) info.server_uri.slen, info.server_uri.ptr,
634                         (int) info.client_uri.slen, info.client_uri.ptr,
635                         seconds);
636
637         ao2_ref(client_state, +1);
638         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &client_state->timer, &delay) != PJ_SUCCESS) {
639                 ast_log(LOG_WARNING, "Failed to schedule registration to server '%.*s' from client '%.*s'\n",
640                                 (int) info.server_uri.slen, info.server_uri.ptr,
641                                 (int) info.client_uri.slen, info.client_uri.ptr);
642                 ao2_ref(client_state, -1);
643         }
644 }
645
646 static void update_client_state_status(struct sip_outbound_registration_client_state *client_state, enum sip_outbound_registration_status status)
647 {
648         const char *status_old;
649         const char *status_new;
650
651         if (client_state->status == status) {
652                 /* Status state did not change at all. */
653                 return;
654         }
655
656         status_old = sip_outbound_registration_status_str(client_state->status);
657         status_new = sip_outbound_registration_status_str(status);
658         client_state->status = status;
659
660         if (!strcmp(status_old, status_new)) {
661                 /*
662                  * The internal status state may have changed but the status
663                  * state we tell the world did not change at all.
664                  */
665                 return;
666         }
667
668         ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "-1", 1.0,
669                 status_old);
670         ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "+1", 1.0,
671                 status_new);
672 }
673
674 /*! \brief Callback function for unregistering (potentially) and destroying state */
675 static int handle_client_state_destruction(void *data)
676 {
677         struct sip_outbound_registration_client_state *client_state = data;
678
679         cancel_registration(client_state);
680
681         if (client_state->client) {
682                 pjsip_regc_info info;
683                 pjsip_tx_data *tdata;
684
685                 pjsip_regc_get_info(client_state->client, &info);
686
687                 if (info.is_busy == PJ_TRUE) {
688                         /* If a client transaction is in progress we defer until it is complete */
689                         ast_debug(1,
690                                 "Registration transaction is busy with server '%.*s' from client '%.*s'.\n",
691                                 (int) info.server_uri.slen, info.server_uri.ptr,
692                                 (int) info.client_uri.slen, info.client_uri.ptr);
693                         client_state->destroy = 1;
694                         ao2_ref(client_state, -1);
695                         return 0;
696                 }
697
698                 switch (client_state->status) {
699                 case SIP_REGISTRATION_UNREGISTERED:
700                         break;
701                 case SIP_REGISTRATION_REGISTERED:
702                         ast_debug(1,
703                                 "Trying to unregister with server '%.*s' from client '%.*s' before destruction.\n",
704                                 (int) info.server_uri.slen, info.server_uri.ptr,
705                                 (int) info.client_uri.slen, info.client_uri.ptr);
706
707                         update_client_state_status(client_state, SIP_REGISTRATION_STOPPING);
708                         client_state->destroy = 1;
709                         if (pjsip_regc_unregister(client_state->client, &tdata) == PJ_SUCCESS
710                                 && registration_client_send(client_state, tdata) == PJ_SUCCESS) {
711                                 ao2_ref(client_state, -1);
712                                 return 0;
713                         }
714                         break;
715                 case SIP_REGISTRATION_REJECTED_TEMPORARY:
716                 case SIP_REGISTRATION_REJECTED_PERMANENT:
717                 case SIP_REGISTRATION_STOPPING:
718                 case SIP_REGISTRATION_STOPPED:
719                         break;
720                 }
721
722                 pjsip_regc_destroy(client_state->client);
723                 client_state->client = NULL;
724         }
725
726         update_client_state_status(client_state, SIP_REGISTRATION_STOPPED);
727         ast_sip_auth_vector_destroy(&client_state->outbound_auths);
728         ao2_ref(client_state, -1);
729
730         return 0;
731 }
732
733 /*! \brief Structure for registration response */
734 struct registration_response {
735         /*! \brief Response code for the registration attempt */
736         int code;
737         /*! \brief Expiration time for registration */
738         int expiration;
739         /*! \brief Retry-After value */
740         int retry_after;
741         /*! \brief Outbound registration client state */
742         struct sip_outbound_registration_client_state *client_state;
743         /*! \brief The response message */
744         pjsip_rx_data *rdata;
745         /*! \brief Request for which the response was received */
746         pjsip_tx_data *old_request;
747 };
748
749 /*! \brief Registration response structure destructor */
750 static void registration_response_destroy(void *obj)
751 {
752         struct registration_response *response = obj;
753
754         if (response->rdata) {
755                 pjsip_rx_data_free_cloned(response->rdata);
756         }
757
758         if (response->old_request) {
759                 pjsip_tx_data_dec_ref(response->old_request);
760         }
761
762         ao2_cleanup(response->client_state);
763 }
764
765 /*! \brief Helper function which determines if a response code is temporal or not */
766 static int sip_outbound_registration_is_temporal(unsigned int code,
767                 struct sip_outbound_registration_client_state *client_state)
768 {
769         /* Shamelessly taken from pjsua */
770         if (code == PJSIP_SC_REQUEST_TIMEOUT ||
771                 code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
772                 code == PJSIP_SC_BAD_GATEWAY ||
773                 code == PJSIP_SC_SERVICE_UNAVAILABLE ||
774                 code == PJSIP_SC_SERVER_TIMEOUT ||
775                 ((code == PJSIP_SC_UNAUTHORIZED ||
776                   code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED) &&
777                  !client_state->auth_rejection_permanent) ||
778                 PJSIP_IS_STATUS_IN_CLASS(code, 600)) {
779                 return 1;
780         } else {
781                 return 0;
782         }
783 }
784
785 static void schedule_retry(struct registration_response *response, unsigned int interval,
786                            const char *server_uri, const char *client_uri)
787 {
788         update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_TEMPORARY);
789         schedule_registration(response->client_state, interval);
790
791         if (response->rdata) {
792                 ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on "
793                         "registration attempt to '%s', retrying in '%u'\n",
794                         response->code, server_uri, client_uri, interval);
795         } else {
796                 ast_log(LOG_WARNING, "No response received from '%s' on "
797                         "registration attempt to '%s', retrying in '%u'\n",
798                         server_uri, client_uri, interval);
799         }
800 }
801
802 static int reregister_immediately_cb(void *obj)
803 {
804         struct sip_outbound_registration_state *state = obj;
805
806         if (state->client_state->status != SIP_REGISTRATION_REGISTERED) {
807                 ao2_ref(state, -1);
808                 return 0;
809         }
810
811         if (DEBUG_ATLEAST(1)) {
812                 pjsip_regc_info info;
813
814                 pjsip_regc_get_info(state->client_state->client, &info);
815                 ast_log(LOG_DEBUG,
816                         "Outbound registration transport to server '%.*s' from client '%.*s' shutdown\n",
817                         (int) info.server_uri.slen, info.server_uri.ptr,
818                         (int) info.client_uri.slen, info.client_uri.ptr);
819         }
820
821         cancel_registration(state->client_state);
822
823         ao2_ref(state->client_state, +1);
824         handle_client_registration(state->client_state);
825
826         ao2_ref(state, -1);
827         return 0;
828 }
829
830 /*!
831  * \internal
832  * \brief The reliable transport we registered using has shutdown.
833  * \since 13.18.0
834  *
835  * \param obj What is needed to initiate a reregister attempt.
836  *
837  * \note Normally executed by the pjsip monitor thread.
838  *
839  * \return Nothing
840  */
841 static void registration_transport_shutdown_cb(void *obj)
842 {
843         const char *registration_name = obj;
844         struct sip_outbound_registration_state *state;
845
846         state = get_state(registration_name);
847         if (!state) {
848                 /* Registration no longer exists or shutting down. */
849                 return;
850         }
851         if (ast_sip_push_task(state->client_state->serializer, reregister_immediately_cb, state)) {
852                 ao2_ref(state, -1);
853         }
854 }
855
856 static int monitor_matcher(void *a, void *b)
857 {
858         char *ma = a;
859         char *mb = b;
860
861         return strcmp(ma, mb) == 0;
862 }
863
864 static void registration_transport_monitor_setup(pjsip_transport *transport, const char *registration_name)
865 {
866         char *monitor;
867
868         if (!PJSIP_TRANSPORT_IS_RELIABLE(transport)) {
869                 return;
870         }
871         monitor = ao2_alloc_options(strlen(registration_name) + 1, NULL,
872                 AO2_ALLOC_OPT_LOCK_NOLOCK);
873         if (!monitor) {
874                 return;
875         }
876         strcpy(monitor, registration_name);/* Safe */
877
878         /*
879          * We'll ignore if the transport has already been shutdown before we
880          * register the monitor.  We might get into a message spamming infinite
881          * loop of registration, shutdown, reregistration...
882          */
883         ast_sip_transport_monitor_register(transport, registration_transport_shutdown_cb,
884                 monitor);
885         ao2_ref(monitor, -1);
886 }
887
888 /*! \brief Callback function for handling a response to a registration attempt */
889 static int handle_registration_response(void *data)
890 {
891         struct registration_response *response = data;
892         pjsip_regc_info info;
893         char server_uri[PJSIP_MAX_URL_SIZE];
894         char client_uri[PJSIP_MAX_URL_SIZE];
895
896         if (response->client_state->status == SIP_REGISTRATION_STOPPED) {
897                 ao2_ref(response, -1);
898                 return 0;
899         }
900
901         pjsip_regc_get_info(response->client_state->client, &info);
902         ast_copy_pj_str(server_uri, &info.server_uri, sizeof(server_uri));
903         ast_copy_pj_str(client_uri, &info.client_uri, sizeof(client_uri));
904
905         ast_debug(1, "Processing REGISTER response %d from server '%s' for client '%s'\n",
906                         response->code, server_uri, client_uri);
907
908         if ((response->code == 401 || response->code == 407)
909                 && (!response->client_state->auth_attempted
910                         || response->rdata->msg_info.cseq->cseq != response->client_state->auth_cseq)) {
911                 int res;
912                 pjsip_cseq_hdr *cseq_hdr;
913                 pjsip_tx_data *tdata;
914
915                 if (!ast_sip_create_request_with_auth(&response->client_state->outbound_auths,
916                                 response->rdata, response->old_request, &tdata)) {
917                         response->client_state->auth_attempted = 1;
918                         ast_debug(1, "Sending authenticated REGISTER to server '%s' from client '%s'\n",
919                                         server_uri, client_uri);
920                         pjsip_tx_data_add_ref(tdata);
921                         res = registration_client_send(response->client_state, tdata);
922
923                         /* Save the cseq that actually got sent. */
924                         cseq_hdr = (pjsip_cseq_hdr *) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ,
925                                 NULL);
926                         response->client_state->auth_cseq = cseq_hdr->cseq;
927                         pjsip_tx_data_dec_ref(tdata);
928                         if (res == PJ_SUCCESS) {
929                                 ao2_ref(response, -1);
930                                 return 0;
931                         }
932                 } else {
933                         ast_log(LOG_WARNING, "Failed to create authenticated REGISTER request to server '%s' from client '%s'\n",
934                                         server_uri, client_uri);
935                 }
936                 /* Otherwise, fall through so the failure is processed appropriately */
937         }
938
939         response->client_state->auth_attempted = 0;
940
941         if (PJSIP_IS_STATUS_IN_CLASS(response->code, 200)) {
942                 /* Check if this is in regards to registering or unregistering */
943                 if (response->expiration) {
944                         int next_registration_round;
945
946                         /* If the registration went fine simply reschedule registration for the future */
947                         ast_debug(1, "Outbound registration to '%s' with client '%s' successful\n", server_uri, client_uri);
948                         update_client_state_status(response->client_state, SIP_REGISTRATION_REGISTERED);
949                         response->client_state->retries = 0;
950                         next_registration_round = response->expiration - REREGISTER_BUFFER_TIME;
951                         if (next_registration_round < 0) {
952                                 /* Re-register immediately. */
953                                 next_registration_round = 0;
954                         }
955                         schedule_registration(response->client_state, next_registration_round);
956
957                         /* See if we should monitor for transport shutdown */
958                         registration_transport_monitor_setup(response->rdata->tp_info.transport,
959                                 response->client_state->registration_name);
960                 } else {
961                         ast_debug(1, "Outbound unregistration to '%s' with client '%s' successful\n", server_uri, client_uri);
962                         update_client_state_status(response->client_state, SIP_REGISTRATION_UNREGISTERED);
963                         ast_sip_transport_monitor_unregister(response->rdata->tp_info.transport,
964                                 registration_transport_shutdown_cb, response->client_state->registration_name,
965                                 monitor_matcher);
966                 }
967         } else if (response->client_state->destroy) {
968                 /* We need to deal with the pending destruction instead. */
969         } else if (response->retry_after) {
970                 /* If we have been instructed to retry after a period of time, schedule it as such */
971                 schedule_retry(response, response->retry_after, server_uri, client_uri);
972         } else if (response->client_state->retry_interval
973                 && sip_outbound_registration_is_temporal(response->code, response->client_state)) {
974                 if (response->client_state->retries == response->client_state->max_retries) {
975                         /* If we received enough temporal responses to exceed our maximum give up permanently */
976                         update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_PERMANENT);
977                         ast_log(LOG_WARNING, "Maximum retries reached when attempting outbound registration to '%s' with client '%s', stopping registration attempt\n",
978                                 server_uri, client_uri);
979                 } else {
980                         /* On the other hand if we can still try some more do so */
981                         response->client_state->retries++;
982                         schedule_retry(response, response->client_state->retry_interval, server_uri, client_uri);
983                 }
984         } else {
985                 if (response->code == 403
986                         && response->client_state->forbidden_retry_interval
987                         && response->client_state->retries < response->client_state->max_retries) {
988                         /* A forbidden response retry interval is configured and there are retries remaining */
989                         update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_TEMPORARY);
990                         response->client_state->retries++;
991                         schedule_registration(response->client_state, response->client_state->forbidden_retry_interval);
992                         ast_log(LOG_WARNING, "403 Forbidden fatal response received from '%s' on registration attempt to '%s', retrying in '%u' seconds\n",
993                                 server_uri, client_uri, response->client_state->forbidden_retry_interval);
994                 } else if (response->client_state->fatal_retry_interval
995                            && response->client_state->retries < response->client_state->max_retries) {
996                         /* Some kind of fatal failure response received, so retry according to configured interval */
997                         update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_TEMPORARY);
998                         response->client_state->retries++;
999                         schedule_registration(response->client_state, response->client_state->fatal_retry_interval);
1000                         ast_log(LOG_WARNING, "'%d' fatal response received from '%s' on registration attempt to '%s', retrying in '%u' seconds\n",
1001                                 response->code, server_uri, client_uri, response->client_state->fatal_retry_interval);
1002                 } else {
1003                         /* Finally if there's no hope of registering give up */
1004                         update_client_state_status(response->client_state, SIP_REGISTRATION_REJECTED_PERMANENT);
1005                         if (response->rdata) {
1006                                 ast_log(LOG_WARNING, "Fatal response '%d' received from '%s' on registration attempt to '%s', stopping outbound registration\n",
1007                                         response->code, server_uri, client_uri);
1008                         } else {
1009                                 ast_log(LOG_WARNING, "Fatal registration attempt to '%s', stopping outbound registration\n", client_uri);
1010                         }
1011                 }
1012         }
1013
1014         ast_system_publish_registry("PJSIP", client_uri, server_uri,
1015                 sip_outbound_registration_status_str(response->client_state->status), NULL);
1016
1017         if (response->client_state->destroy) {
1018                 /* We have a pending deferred destruction to complete now. */
1019                 ao2_ref(response->client_state, +1);
1020                 handle_client_state_destruction(response->client_state);
1021         }
1022
1023         ao2_ref(response, -1);
1024         return 0;
1025 }
1026
1027 /*! \brief Callback function for outbound registration client */
1028 static void sip_outbound_registration_response_cb(struct pjsip_regc_cbparam *param)
1029 {
1030         struct sip_outbound_registration_client_state *client_state = param->token;
1031         struct registration_response *response;
1032         int *callback_invoked;
1033
1034         callback_invoked = ast_threadstorage_get(&register_callback_invoked, sizeof(int));
1035
1036         ast_assert(callback_invoked != NULL);
1037         ast_assert(client_state != NULL);
1038
1039         *callback_invoked = 1;
1040
1041         response = ao2_alloc(sizeof(*response), registration_response_destroy);
1042         if (!response) {
1043                 ao2_ref(client_state, -1);
1044                 return;
1045         }
1046         response->code = param->code;
1047         response->expiration = param->expiration;
1048         /*
1049          * Transfer client_state reference to response so the
1050          * nominal path will not dec the client_state ref in this
1051          * pjproject callback thread.
1052          */
1053         response->client_state = client_state;
1054
1055         ast_debug(1, "Received REGISTER response %d(%.*s)\n",
1056                 param->code, (int) param->reason.slen, param->reason.ptr);
1057
1058         if (param->rdata) {
1059                 struct pjsip_retry_after_hdr *retry_after;
1060                 pjsip_transaction *tsx;
1061
1062                 retry_after = pjsip_msg_find_hdr(param->rdata->msg_info.msg, PJSIP_H_RETRY_AFTER,
1063                         NULL);
1064                 response->retry_after = retry_after ? retry_after->ivalue : 0;
1065                 tsx = pjsip_rdata_get_tsx(param->rdata);
1066                 response->old_request = tsx->last_tx;
1067                 pjsip_tx_data_add_ref(response->old_request);
1068                 pjsip_rx_data_clone(param->rdata, 0, &response->rdata);
1069         }
1070
1071         /*
1072          * Transfer response reference to serializer task so the
1073          * nominal path will not dec the response ref in this
1074          * pjproject callback thread.
1075          */
1076         if (ast_sip_push_task(client_state->serializer, handle_registration_response, response)) {
1077                 ast_log(LOG_WARNING, "Failed to pass incoming registration response to threadpool\n");
1078                 ao2_cleanup(response);
1079         }
1080 }
1081
1082 /*! \brief Destructor function for registration state */
1083 static void sip_outbound_registration_state_destroy(void *obj)
1084 {
1085         struct sip_outbound_registration_state *state = obj;
1086
1087         ast_debug(3, "Destroying registration state for registration to server '%s' from client '%s'\n",
1088                 state->registration ? state->registration->server_uri : "",
1089                 state->registration ? state->registration->client_uri : "");
1090         ao2_cleanup(state->registration);
1091
1092         if (!state->client_state) {
1093                 /* Nothing to do */
1094         } else if (!state->client_state->serializer) {
1095                 ao2_ref(state->client_state, -1);
1096         } else if (ast_sip_push_task(state->client_state->serializer,
1097                 handle_client_state_destruction, state->client_state)) {
1098                 ast_log(LOG_WARNING, "Failed to pass outbound registration client destruction to threadpool\n");
1099                 ao2_ref(state->client_state, -1);
1100         }
1101 }
1102
1103 /*! \brief Destructor function for client registration state */
1104 static void sip_outbound_registration_client_state_destroy(void *obj)
1105 {
1106         struct sip_outbound_registration_client_state *client_state = obj;
1107
1108         ast_statsd_log_string("PJSIP.registrations.count", AST_STATSD_GAUGE, "-1", 1.0);
1109         ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "-1", 1.0,
1110                 sip_outbound_registration_status_str(client_state->status));
1111
1112         ast_taskprocessor_unreference(client_state->serializer);
1113         ast_free(client_state->transport_name);
1114         ast_free(client_state->registration_name);
1115 }
1116
1117 /*! \brief Allocator function for registration state */
1118 static struct sip_outbound_registration_state *sip_outbound_registration_state_alloc(struct sip_outbound_registration *registration)
1119 {
1120         struct sip_outbound_registration_state *state;
1121         char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
1122
1123         state = ao2_alloc(sizeof(*state), sip_outbound_registration_state_destroy);
1124         if (!state) {
1125                 return NULL;
1126         }
1127         state->client_state = ao2_alloc(sizeof(*state->client_state),
1128                 sip_outbound_registration_client_state_destroy);
1129         if (!state->client_state) {
1130                 ao2_cleanup(state);
1131                 return NULL;
1132         }
1133
1134         state->client_state->status = SIP_REGISTRATION_UNREGISTERED;
1135         pj_timer_entry_init(&state->client_state->timer, 0, state->client_state,
1136                 sip_outbound_registration_timer_cb);
1137         state->client_state->transport_name = ast_strdup(registration->transport);
1138         state->client_state->registration_name =
1139                 ast_strdup(ast_sorcery_object_get_id(registration));
1140
1141         ast_statsd_log_string("PJSIP.registrations.count", AST_STATSD_GAUGE, "+1", 1.0);
1142         ast_statsd_log_string_va("PJSIP.registrations.state.%s", AST_STATSD_GAUGE, "+1", 1.0,
1143                 sip_outbound_registration_status_str(state->client_state->status));
1144
1145         if (!state->client_state->transport_name
1146                 || !state->client_state->registration_name) {
1147                 ao2_cleanup(state);
1148                 return NULL;
1149         }
1150
1151         /* Create name with seq number appended. */
1152         ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outreg/%s",
1153                 ast_sorcery_object_get_id(registration));
1154
1155         state->client_state->serializer = ast_sip_create_serializer_group(tps_name,
1156                 shutdown_group);
1157         if (!state->client_state->serializer) {
1158                 ao2_cleanup(state);
1159                 return NULL;
1160         }
1161
1162         state->registration = ao2_bump(registration);
1163         return state;
1164 }
1165
1166 /*! \brief Destructor function for registration information */
1167 static void sip_outbound_registration_destroy(void *obj)
1168 {
1169         struct sip_outbound_registration *registration = obj;
1170
1171         ast_sip_auth_vector_destroy(&registration->outbound_auths);
1172
1173         ast_string_field_free_memory(registration);
1174 }
1175
1176 /*! \brief Allocator function for registration information */
1177 static void *sip_outbound_registration_alloc(const char *name)
1178 {
1179         struct sip_outbound_registration *registration;
1180
1181         registration = ast_sorcery_generic_alloc(sizeof(*registration),
1182                 sip_outbound_registration_destroy);
1183         if (!registration || ast_string_field_init(registration, 256)) {
1184                 ao2_cleanup(registration);
1185                 return NULL;
1186         }
1187
1188         return registration;
1189 }
1190
1191 /*! \brief Helper function which populates a pj_str_t with a contact header */
1192 static int sip_dialog_create_contact(pj_pool_t *pool, pj_str_t *contact, const char *user,
1193         const pj_str_t *target, pjsip_tpselector *selector, const char *line)
1194 {
1195         pj_str_t tmp, local_addr;
1196         pjsip_uri *uri;
1197         pjsip_sip_uri *sip_uri;
1198         pjsip_transport_type_e type;
1199         int local_port;
1200
1201         pj_strdup_with_null(pool, &tmp, target);
1202
1203         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
1204             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
1205                 return -1;
1206         }
1207
1208         sip_uri = pjsip_uri_get_uri(uri);
1209
1210         type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
1211         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
1212                 if (type == PJSIP_TRANSPORT_UNSPECIFIED
1213                         || !(pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE)) {
1214                         type = PJSIP_TRANSPORT_TLS;
1215                 }
1216         } else if (!sip_uri->transport_param.slen) {
1217                 type = PJSIP_TRANSPORT_UDP;
1218         } else if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
1219                 return -1;
1220         }
1221
1222         if (pj_strchr(&sip_uri->host, ':')) {
1223                 type |= PJSIP_TRANSPORT_IPV6;
1224         }
1225
1226         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()),
1227                 pool, type, selector, &local_addr, &local_port) != PJ_SUCCESS) {
1228                 return -1;
1229         }
1230
1231         if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
1232                 type |= PJSIP_TRANSPORT_IPV6;
1233         }
1234
1235         contact->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
1236         contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
1237                 "<%s:%s@%s%.*s%s:%d%s%s%s%s>",
1238                 ((pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) && PJSIP_URI_SCHEME_IS_SIPS(uri)) ? "sips" : "sip",
1239                 user,
1240                 (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
1241                 (int)local_addr.slen,
1242                 local_addr.ptr,
1243                 (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
1244                 local_port,
1245                 (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
1246                 (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "",
1247                 !ast_strlen_zero(line) ? ";line=" : "",
1248                 S_OR(line, ""));
1249
1250         return 0;
1251 }
1252
1253 /*!
1254  * \internal
1255  * \brief Check if a registration can be reused
1256  *
1257  * This checks if the existing outbound registration's configuration differs from a newly-applied
1258  * outbound registration to see if the applied one.
1259  *
1260  * \param existing The pre-existing outbound registration
1261  * \param applied The newly-created registration
1262  */
1263 static int can_reuse_registration(struct sip_outbound_registration *existing,
1264         struct sip_outbound_registration *applied)
1265 {
1266         int rc = 1;
1267         struct ast_sorcery *sorcery = ast_sip_get_sorcery();
1268         struct ast_variable *ve = ast_sorcery_objectset_create(sorcery, existing);
1269         struct ast_variable *va = ast_sorcery_objectset_create(sorcery, applied);
1270         struct ast_variable *vc = NULL;
1271
1272         if (ast_sorcery_changeset_create(ve, va, &vc) || vc != NULL) {
1273                 rc = 0;
1274                 ast_debug(4, "Registration '%s' changed.  Can't re-use.\n", ast_sorcery_object_get_id(existing));
1275         } else {
1276                 ast_debug(4, "Registration '%s' didn't change.  Can re-use\n", ast_sorcery_object_get_id(existing));
1277         }
1278
1279         ast_variables_destroy(ve);
1280         ast_variables_destroy(va);
1281         ast_variables_destroy(vc);
1282
1283         return rc;
1284 }
1285
1286 /*! \brief Helper function that allocates a pjsip registration client and configures it */
1287 static int sip_outbound_registration_regc_alloc(void *data)
1288 {
1289         struct sip_outbound_registration_state *state = data;
1290         RAII_VAR(struct sip_outbound_registration *, registration,
1291                  ao2_bump(state->registration), ao2_cleanup);
1292         pj_pool_t *pool;
1293         pj_str_t tmp;
1294         pjsip_uri *uri;
1295         pj_str_t server_uri, client_uri, contact_uri;
1296         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
1297
1298         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "URI Validation", 256, 256);
1299         if (!pool) {
1300                 ast_log(LOG_ERROR, "Could not create pool for URI validation on outbound registration '%s'\n",
1301                         ast_sorcery_object_get_id(registration));
1302                 return -1;
1303         }
1304
1305         pj_strdup2_with_null(pool, &tmp, registration->server_uri);
1306         uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
1307         if (!uri) {
1308                 ast_log(LOG_ERROR, "Invalid server URI '%s' specified on outbound registration '%s'\n",
1309                         registration->server_uri, ast_sorcery_object_get_id(registration));
1310                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1311                 return -1;
1312         }
1313
1314         pj_strdup2_with_null(pool, &tmp, registration->client_uri);
1315         uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
1316         if (!uri) {
1317                 ast_log(LOG_ERROR, "Invalid client URI '%s' specified on outbound registration '%s'\n",
1318                         registration->client_uri, ast_sorcery_object_get_id(registration));
1319                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1320                 return -1;
1321         }
1322
1323         if (!ast_strlen_zero(registration->outbound_proxy)) {
1324                 pj_strdup2_with_null(pool, &tmp, registration->outbound_proxy);
1325                 uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
1326                 if (!uri) {
1327                         ast_log(LOG_ERROR, "Invalid outbound proxy URI '%s' specified on outbound registration '%s'\n",
1328                                 registration->outbound_proxy, ast_sorcery_object_get_id(registration));
1329                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1330                         return -1;
1331                 }
1332         }
1333
1334         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
1335
1336
1337         ast_assert(state->client_state->client == NULL);
1338         if (pjsip_regc_create(ast_sip_get_pjsip_endpoint(), state->client_state,
1339                         sip_outbound_registration_response_cb,
1340                         &state->client_state->client) != PJ_SUCCESS) {
1341                 return -1;
1342         }
1343
1344         ast_sip_set_tpselector_from_transport_name(registration->transport, &selector);
1345         pjsip_regc_set_transport(state->client_state->client, &selector);
1346
1347         if (!ast_strlen_zero(registration->outbound_proxy)) {
1348                 pjsip_route_hdr route_set, *route;
1349                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
1350                 pj_str_t tmp;
1351
1352                 pj_list_init(&route_set);
1353
1354                 pj_strdup2_with_null(pjsip_regc_get_pool(state->client_state->client), &tmp,
1355                         registration->outbound_proxy);
1356                 route = pjsip_parse_hdr(pjsip_regc_get_pool(state->client_state->client),
1357                         &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL);
1358                 if (!route) {
1359                         return -1;
1360                 }
1361                 pj_list_insert_nodes_before(&route_set, route);
1362
1363                 pjsip_regc_set_route_set(state->client_state->client, &route_set);
1364         }
1365
1366         if (state->registration->line) {
1367                 ast_generate_random_string(state->client_state->line, sizeof(state->client_state->line));
1368         }
1369
1370         pj_cstr(&server_uri, registration->server_uri);
1371
1372
1373         if (sip_dialog_create_contact(pjsip_regc_get_pool(state->client_state->client),
1374                 &contact_uri, S_OR(registration->contact_user, "s"), &server_uri, &selector,
1375                 state->client_state->line)) {
1376                 return -1;
1377         }
1378
1379         pj_cstr(&client_uri, registration->client_uri);
1380         if (pjsip_regc_init(state->client_state->client, &server_uri, &client_uri,
1381                 &client_uri, 1, &contact_uri, registration->expiration) != PJ_SUCCESS) {
1382                 return -1;
1383         }
1384
1385         return 0;
1386 }
1387
1388 /*! \brief Helper function which performs a single registration */
1389 static int sip_outbound_registration_perform(void *data)
1390 {
1391         struct sip_outbound_registration_state *state = data;
1392         struct sip_outbound_registration *registration = ao2_bump(state->registration);
1393         size_t i;
1394
1395         /* Just in case the client state is being reused for this registration, free the auth information */
1396         ast_sip_auth_vector_destroy(&state->client_state->outbound_auths);
1397
1398         AST_VECTOR_INIT(&state->client_state->outbound_auths, AST_VECTOR_SIZE(&registration->outbound_auths));
1399         for (i = 0; i < AST_VECTOR_SIZE(&registration->outbound_auths); ++i) {
1400                 char *name = ast_strdup(AST_VECTOR_GET(&registration->outbound_auths, i));
1401
1402                 if (name && AST_VECTOR_APPEND(&state->client_state->outbound_auths, name)) {
1403                         ast_free(name);
1404                 }
1405         }
1406         state->client_state->retry_interval = registration->retry_interval;
1407         state->client_state->forbidden_retry_interval = registration->forbidden_retry_interval;
1408         state->client_state->fatal_retry_interval = registration->fatal_retry_interval;
1409         state->client_state->max_retries = registration->max_retries;
1410         state->client_state->retries = 0;
1411         state->client_state->support_path = registration->support_path;
1412         state->client_state->auth_rejection_permanent = registration->auth_rejection_permanent;
1413
1414         pjsip_regc_update_expires(state->client_state->client, registration->expiration);
1415
1416         schedule_registration(state->client_state, (ast_random() % 10) + 1);
1417
1418         ao2_ref(registration, -1);
1419         ao2_ref(state, -1);
1420         return 0;
1421 }
1422
1423 /*! \brief Apply function which finds or allocates a state structure */
1424 static int sip_outbound_registration_apply(const struct ast_sorcery *sorcery, void *obj)
1425 {
1426         RAII_VAR(struct ao2_container *, states, ao2_global_obj_ref(current_states), ao2_cleanup);
1427         RAII_VAR(struct sip_outbound_registration_state *, state, NULL, ao2_cleanup);
1428         RAII_VAR(struct sip_outbound_registration_state *, new_state, NULL, ao2_cleanup);
1429         struct sip_outbound_registration *applied = obj;
1430
1431         if (!states) {
1432                 /* Global container has gone.  Likely shutting down. */
1433                 return -1;
1434         }
1435         state = ao2_find(states, ast_sorcery_object_get_id(applied), OBJ_SEARCH_KEY);
1436
1437         ast_debug(4, "Applying configuration to outbound registration '%s'\n", ast_sorcery_object_get_id(applied));
1438
1439         if (ast_strlen_zero(applied->server_uri)) {
1440                 ast_log(LOG_ERROR, "No server URI specified on outbound registration '%s'\n",
1441                         ast_sorcery_object_get_id(applied));
1442                 return -1;
1443         } else if (ast_sip_validate_uri_length(applied->server_uri)) {
1444                         ast_log(LOG_ERROR, "Server URI or hostname length exceeds pjproject limit or is not a sip(s) uri: '%s'\n",
1445                                 ast_sorcery_object_get_id(applied));
1446                         return -1;
1447         } else if (ast_strlen_zero(applied->client_uri)) {
1448                 ast_log(LOG_ERROR, "No client URI specified on outbound registration '%s'\n",
1449                         ast_sorcery_object_get_id(applied));
1450                 return -1;
1451         } else if (ast_sip_validate_uri_length(applied->client_uri)) {
1452                         ast_log(LOG_ERROR, "Client URI or hostname length exceeds pjproject limit or is not a sip(s) uri: '%s'\n",
1453                                 ast_sorcery_object_get_id(applied));
1454                         return -1;
1455         } else if (applied->line && ast_strlen_zero(applied->endpoint)) {
1456                 ast_log(LOG_ERROR, "Line support has been enabled on outbound registration '%s' without providing an endpoint\n",
1457                         ast_sorcery_object_get_id(applied));
1458                 return -1;
1459         } else if (!ast_strlen_zero(applied->endpoint) && !applied->line) {
1460                 ast_log(LOG_ERROR, "An endpoint has been specified on outbound registration '%s' without enabling line support\n",
1461                         ast_sorcery_object_get_id(applied));
1462                 return -1;
1463         }
1464
1465         if (state && can_reuse_registration(state->registration, applied)) {
1466                 ast_debug(4,
1467                         "No change between old configuration and new configuration on outbound registration '%s'. Using previous state\n",
1468                         ast_sorcery_object_get_id(applied));
1469
1470                 /*
1471                  * This is OK to replace without relinking the state in the
1472                  * current_states container since state->registration and
1473                  * applied have the same key.
1474                  */
1475                 ao2_lock(states);
1476                 ao2_replace(state->registration, applied);
1477                 ao2_unlock(states);
1478                 return 0;
1479         }
1480
1481         if (!(new_state = sip_outbound_registration_state_alloc(applied))) {
1482                 return -1;
1483         }
1484
1485         if (ast_sip_push_task_wait_serializer(new_state->client_state->serializer,
1486                 sip_outbound_registration_regc_alloc, new_state)) {
1487                 return -1;
1488         }
1489
1490         if (ast_sip_push_task(new_state->client_state->serializer,
1491                               sip_outbound_registration_perform, ao2_bump(new_state))) {
1492                 ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n",
1493                         ast_sorcery_object_get_id(new_state->registration));
1494                 ao2_ref(new_state, -1);
1495                 return -1;
1496         }
1497
1498         ao2_lock(states);
1499         if (state) {
1500                 ao2_unlink(states, state);
1501         }
1502         ao2_link(states, new_state);
1503         ao2_unlock(states);
1504
1505         return 0;
1506 }
1507
1508 static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1509 {
1510         struct sip_outbound_registration *registration = obj;
1511
1512         return ast_sip_auth_vector_init(&registration->outbound_auths, var->value);
1513 }
1514
1515 static int outbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
1516 {
1517         const struct sip_outbound_registration *registration = obj;
1518
1519         return ast_sip_auths_to_str(&registration->outbound_auths, buf);
1520 }
1521
1522 static int outbound_auths_to_var_list(const void *obj, struct ast_variable **fields)
1523 {
1524         const struct sip_outbound_registration *registration = obj;
1525         int i;
1526         struct ast_variable *head = NULL;
1527
1528         for (i = 0; i < AST_VECTOR_SIZE(&registration->outbound_auths) ; i++) {
1529                 ast_variable_list_append(&head, ast_variable_new("outbound_auth",
1530                         AST_VECTOR_GET(&registration->outbound_auths, i), ""));
1531         }
1532
1533         if (head) {
1534                 *fields = head;
1535         }
1536
1537         return 0;
1538 }
1539
1540 static int unregister_task(void *obj)
1541 {
1542         struct sip_outbound_registration_state *state = obj;
1543         struct pjsip_regc *client = state->client_state->client;
1544         pjsip_tx_data *tdata;
1545         pjsip_regc_info info;
1546
1547         pjsip_regc_get_info(client, &info);
1548         ast_debug(1, "Unregistering contacts with server '%s' from client '%s'\n",
1549                 state->registration->server_uri, state->registration->client_uri);
1550
1551         cancel_registration(state->client_state);
1552
1553         if (pjsip_regc_unregister(client, &tdata) == PJ_SUCCESS) {
1554                 registration_client_send(state->client_state, tdata);
1555         }
1556
1557         ao2_ref(state, -1);
1558         return 0;
1559 }
1560
1561 static int queue_unregister(struct sip_outbound_registration_state *state)
1562 {
1563         ao2_ref(state, +1);
1564         if (ast_sip_push_task(state->client_state->serializer, unregister_task, state)) {
1565                 ao2_ref(state, -1);
1566                 return -1;
1567         }
1568
1569         return 0;
1570 }
1571
1572 static int queue_register(struct sip_outbound_registration_state *state)
1573 {
1574         ao2_ref(state, +1);
1575         if (ast_sip_push_task(state->client_state->serializer, sip_outbound_registration_perform, state)) {
1576                 ao2_ref(state, -1);
1577                 return -1;
1578         }
1579
1580         return 0;
1581 }
1582
1583 static void unregister_all(void)
1584 {
1585         struct ao2_container *states;
1586
1587         states = ao2_global_obj_ref(current_states);
1588         if (!states) {
1589                 return;
1590         }
1591
1592         /* Clean out all the states and let sorcery handle recreating the registrations */
1593         ao2_callback(states, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL);
1594         ao2_ref(states, -1);
1595 }
1596
1597 static void reregister_all(void)
1598 {
1599         unregister_all();
1600         ast_sorcery_load_object(ast_sip_get_sorcery(), "registration");
1601 }
1602
1603 static char *cli_complete_registration(const char *line, const char *word,
1604                                        int pos, int state)
1605 {
1606         char *result = NULL;
1607         int wordlen;
1608         int which = 0;
1609         struct sip_outbound_registration *registration;
1610         struct ao2_container *registrations;
1611         struct ao2_iterator i;
1612
1613         if (pos != 3) {
1614                 return NULL;
1615         }
1616
1617         wordlen = strlen(word);
1618         if (wordlen == 0 && ++which > state) {
1619                 return ast_strdup("*all");
1620         }
1621
1622         registrations = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
1623                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1624         if (!registrations) {
1625                 return NULL;
1626         }
1627
1628         i = ao2_iterator_init(registrations, 0);
1629         while ((registration = ao2_iterator_next(&i))) {
1630                 const char *name = ast_sorcery_object_get_id(registration);
1631
1632                 if (!strncasecmp(word, name, wordlen) && ++which > state) {
1633                         result = ast_strdup(name);
1634                 }
1635
1636                 ao2_ref(registration, -1);
1637                 if (result) {
1638                         break;
1639                 }
1640         }
1641         ao2_iterator_destroy(&i);
1642
1643         ao2_ref(registrations, -1);
1644         return result;
1645 }
1646
1647 static char *cli_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1648 {
1649         struct sip_outbound_registration_state *state;
1650         const char *registration_name;
1651
1652         switch (cmd) {
1653         case CLI_INIT:
1654                 e->command = "pjsip send unregister";
1655                 e->usage =
1656                         "Usage: pjsip send unregister <registration> | *all\n"
1657                         "       Unregisters the specified (or all) outbound registration(s) "
1658                         "and stops future registration attempts.\n";
1659                 return NULL;
1660         case CLI_GENERATE:
1661                 return cli_complete_registration(a->line, a->word, a->pos, a->n);
1662         }
1663
1664         if (a->argc != 4) {
1665                 return CLI_SHOWUSAGE;
1666         }
1667
1668         registration_name = a->argv[3];
1669
1670         if (strcmp(registration_name, "*all") == 0) {
1671                 unregister_all();
1672                 ast_cli(a->fd, "Unregister all queued\n");
1673                 return CLI_SUCCESS;
1674         }
1675
1676         state = get_state(registration_name);
1677         if (!state) {
1678                 ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
1679                 return CLI_FAILURE;
1680         }
1681
1682         if (queue_unregister(state)) {
1683                 ast_cli(a->fd, "Failed to queue unregistration\n");
1684         }
1685
1686         ao2_ref(state, -1);
1687         return CLI_SUCCESS;
1688 }
1689
1690 static char *cli_register(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1691 {
1692         struct sip_outbound_registration_state *state;
1693         const char *registration_name;
1694
1695         switch (cmd) {
1696         case CLI_INIT:
1697                 e->command = "pjsip send register";
1698                 e->usage =
1699                         "Usage: pjsip send register <registration> | *all \n"
1700                         "       Unregisters the specified (or all) outbound "
1701                         "registration(s) then starts registration(s) and schedules re-registrations.\n";
1702                 return NULL;
1703         case CLI_GENERATE:
1704                 return cli_complete_registration(a->line, a->word, a->pos, a->n);
1705         }
1706
1707         if (a->argc != 4) {
1708                 return CLI_SHOWUSAGE;
1709         }
1710
1711         registration_name = a->argv[3];
1712
1713         if (strcmp(registration_name, "*all") == 0) {
1714                 reregister_all();
1715                 ast_cli(a->fd, "Re-register all queued\n");
1716                 return CLI_SUCCESS;
1717         }
1718
1719         state = get_state(registration_name);
1720         if (!state) {
1721                 ast_cli(a->fd, "Unable to retrieve registration %s\n", registration_name);
1722                 return CLI_FAILURE;
1723         }
1724
1725         /* We need to serialize the unregister and register so they need
1726          * to be queued as separate tasks.
1727          */
1728         if (queue_unregister(state)) {
1729                 ast_cli(a->fd, "Failed to queue unregistration\n");
1730         } else if (queue_register(state)) {
1731                 ast_cli(a->fd, "Failed to queue registration\n");
1732         }
1733
1734         ao2_ref(state, -1);
1735         return CLI_SUCCESS;
1736 }
1737
1738 static int ami_unregister(struct mansession *s, const struct message *m)
1739 {
1740         const char *registration_name = astman_get_header(m, "Registration");
1741         struct sip_outbound_registration_state *state;
1742
1743         if (ast_strlen_zero(registration_name)) {
1744                 astman_send_error(s, m, "Registration parameter missing.");
1745                 return 0;
1746         }
1747
1748         if (strcmp(registration_name, "*all") == 0) {
1749                 unregister_all();
1750                 astman_send_ack(s, m, "Unregistrations queued.");
1751                 return 0;
1752         }
1753
1754         state = get_state(registration_name);
1755         if (!state) {
1756                 astman_send_error(s, m, "Unable to retrieve registration entry\n");
1757                 return 0;
1758         }
1759
1760         if (queue_unregister(state)) {
1761                 astman_send_ack(s, m, "Failed to queue unregistration");
1762         } else {
1763                 astman_send_ack(s, m, "Unregistration sent");
1764         }
1765
1766         ao2_ref(state, -1);
1767         return 0;
1768 }
1769
1770 static int ami_register(struct mansession *s, const struct message *m)
1771 {
1772         const char *registration_name = astman_get_header(m, "Registration");
1773         struct sip_outbound_registration_state *state;
1774
1775         if (ast_strlen_zero(registration_name)) {
1776                 astman_send_error(s, m, "Registration parameter missing.");
1777                 return 0;
1778         }
1779
1780         if (strcmp(registration_name, "*all") == 0) {
1781                 reregister_all();
1782                 astman_send_ack(s, m, "Reregistrations queued.");
1783                 return 0;
1784         }
1785
1786         state = get_state(registration_name);
1787         if (!state) {
1788                 astman_send_error(s, m, "Unable to retrieve registration entry\n");
1789                 return 0;
1790         }
1791
1792         /* We need to serialize the unregister and register so they need
1793          * to be queued as separate tasks.
1794          */
1795         if (queue_unregister(state)) {
1796                 astman_send_ack(s, m, "Failed to queue unregistration");
1797         } else if (queue_register(state)) {
1798                 astman_send_ack(s, m, "Failed to queue unregistration");
1799         } else {
1800                 astman_send_ack(s, m, "Reregistration sent");
1801         }
1802
1803         ao2_ref(state, -1);
1804         return 0;
1805 }
1806
1807 struct sip_ami_outbound {
1808         struct ast_sip_ami *ami;
1809         int registered;
1810         int not_registered;
1811         struct sip_outbound_registration *registration;
1812 };
1813
1814 static int ami_outbound_registration_task(void *obj)
1815 {
1816         struct sip_ami_outbound *ami = obj;
1817         struct ast_str *buf;
1818         struct sip_outbound_registration_state *state;
1819
1820         buf = ast_sip_create_ami_event("OutboundRegistrationDetail", ami->ami);
1821         if (!buf) {
1822                 return -1;
1823         }
1824
1825         ast_sip_sorcery_object_to_ami(ami->registration, &buf);
1826
1827         if ((state = get_state(ast_sorcery_object_get_id(ami->registration)))) {
1828                 pjsip_regc_info info;
1829
1830                 if (state->client_state->status == SIP_REGISTRATION_REGISTERED) {
1831                         ++ami->registered;
1832                 } else {
1833                         ++ami->not_registered;
1834                 }
1835
1836                 ast_str_append(&buf, 0, "Status: %s\r\n",
1837                         sip_outbound_registration_status_str(state->client_state->status));
1838
1839                 pjsip_regc_get_info(state->client_state->client, &info);
1840                 ast_str_append(&buf, 0, "NextReg: %d\r\n", info.next_reg);
1841                 ao2_ref(state, -1);
1842         }
1843
1844         astman_append(ami->ami->s, "%s\r\n", ast_str_buffer(buf));
1845         ast_free(buf);
1846
1847         return ast_sip_format_auths_ami(&ami->registration->outbound_auths, ami->ami);
1848 }
1849
1850 static int ami_outbound_registration_detail(void *obj, void *arg, int flags)
1851 {
1852         struct sip_ami_outbound *ami = arg;
1853
1854         ami->registration = obj;
1855         return ast_sip_push_task_wait_servant(NULL, ami_outbound_registration_task, ami);
1856 }
1857
1858 static int ami_show_outbound_registrations(struct mansession *s,
1859                                            const struct message *m)
1860 {
1861         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
1862         struct sip_ami_outbound ami_outbound = { .ami = &ami };
1863         struct ao2_container *regs;
1864
1865         regs = get_registrations();
1866         if (!regs) {
1867                 astman_send_error(s, m, "Unable to retrieve "
1868                                   "outbound registrations\n");
1869                 return -1;
1870         }
1871
1872         astman_send_listack(s, m, "Following are Events for each Outbound registration",
1873                 "start");
1874
1875         ao2_callback(regs, OBJ_NODATA, ami_outbound_registration_detail, &ami_outbound);
1876
1877         astman_send_list_complete_start(s, m, "OutboundRegistrationDetailComplete",
1878                 ami_outbound.registered + ami_outbound.not_registered);
1879         astman_append(s,
1880                 "Registered: %d\r\n"
1881                 "NotRegistered: %d\r\n",
1882                 ami_outbound.registered,
1883                 ami_outbound.not_registered);
1884         astman_send_list_complete_end(s);
1885
1886         ao2_ref(regs, -1);
1887         return 0;
1888 }
1889
1890 static struct ao2_container *cli_get_container(const char *regex)
1891 {
1892         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
1893         struct ao2_container *s_container;
1894
1895         container = ast_sorcery_retrieve_by_regex(ast_sip_get_sorcery(), "registration", regex);
1896         if (!container) {
1897                 return NULL;
1898         }
1899
1900         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
1901                 ast_sorcery_object_id_sort, ast_sorcery_object_id_compare);
1902         if (!s_container) {
1903                 return NULL;
1904         }
1905
1906         if (ao2_container_dup(s_container, container, 0)) {
1907                 ao2_ref(s_container, -1);
1908                 return NULL;
1909         }
1910
1911         return s_container;
1912 }
1913
1914 static int cli_iterator(void *container, ao2_callback_fn callback, void *args)
1915 {
1916         ao2_callback(container, OBJ_NODATA, callback, args);
1917
1918         return 0;
1919 }
1920
1921 static void *cli_retrieve_by_id(const char *id)
1922 {
1923         struct ao2_container *states;
1924         void *obj = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "registration", id);
1925
1926         if (!obj) {
1927                 /* if the object no longer exists then remove its state  */
1928                 states = ao2_global_obj_ref(current_states);
1929                 if (states) {
1930                         ao2_find(states, id, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
1931                         ao2_ref(states, -1);
1932                 }
1933         }
1934
1935         return obj;
1936 }
1937
1938 static int cli_print_header(void *obj, void *arg, int flags)
1939 {
1940         struct ast_sip_cli_context *context = arg;
1941
1942         ast_assert(context->output_buffer != NULL);
1943
1944         ast_str_append(&context->output_buffer, 0,
1945                 " <Registration/ServerURI..............................>  <Auth..........>  <Status.......>\n");
1946
1947         return 0;
1948 }
1949
1950 static int cli_print_body(void *obj, void *arg, int flags)
1951 {
1952         struct sip_outbound_registration *registration = obj;
1953         struct ast_sip_cli_context *context = arg;
1954         const char *id = ast_sorcery_object_get_id(registration);
1955         struct sip_outbound_registration_state *state = get_state(id);
1956 #define REGISTRATION_URI_FIELD_LEN      53
1957
1958         ast_assert(context->output_buffer != NULL);
1959
1960         ast_str_append(&context->output_buffer, 0, " %-s/%-*.*s  %-16s  %-16s\n",
1961                 id,
1962                 (int) (REGISTRATION_URI_FIELD_LEN - strlen(id)),
1963                 (int) (REGISTRATION_URI_FIELD_LEN - strlen(id)),
1964                 registration->server_uri,
1965                 AST_VECTOR_SIZE(&registration->outbound_auths)
1966                         ? AST_VECTOR_GET(&registration->outbound_auths, 0)
1967                         : "n/a",
1968                 (state ? sip_outbound_registration_status_str(state->client_state->status) : "Unregistered"));
1969         ao2_cleanup(state);
1970
1971         if (context->show_details
1972                 || (context->show_details_only_level_0 && context->indent_level == 0)) {
1973                 ast_str_append(&context->output_buffer, 0, "\n");
1974                 ast_sip_cli_print_sorcery_objectset(registration, context, 0);
1975         }
1976
1977         return 0;
1978 }
1979
1980 /*
1981  * A function pointer to callback needs to be within the
1982  * module in order to avoid problems with an undefined
1983  * symbol when the module is loaded.
1984  */
1985 static char *my_cli_traverse_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1986 {
1987         return ast_sip_cli_traverse_objects(e, cmd, a);
1988 }
1989
1990 static struct ast_cli_entry cli_outbound_registration[] = {
1991         AST_CLI_DEFINE(cli_unregister, "Unregisters outbound registration target"),
1992         AST_CLI_DEFINE(cli_register, "Registers an outbound registration target"),
1993         AST_CLI_DEFINE(my_cli_traverse_objects, "List PJSIP Registrations",
1994                 .command = "pjsip list registrations",
1995                 .usage = "Usage: pjsip list registrations [ like <pattern> ]\n"
1996                                 "       List the configured PJSIP Registrations\n"
1997                                 "       Optional regular expression pattern is used to filter the list.\n"),
1998         AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Registrations",
1999                 .command = "pjsip show registrations",
2000                 .usage = "Usage: pjsip show registrations [ like <pattern> ]\n"
2001                                 "       Show the configured PJSIP Registrations\n"
2002                                 "       Optional regular expression pattern is used to filter the list.\n"),
2003         AST_CLI_DEFINE(my_cli_traverse_objects, "Show PJSIP Registration",
2004                 .command = "pjsip show registration",
2005                 .usage = "Usage: pjsip show registration <id>\n"
2006                                  "       Show the configured PJSIP Registration\n"),
2007 };
2008
2009 static struct ast_sip_cli_formatter_entry *cli_formatter;
2010
2011 static void auth_observer(const char *type)
2012 {
2013         struct sip_outbound_registration *registration;
2014         struct sip_outbound_registration_state *state;
2015         struct ao2_container *regs;
2016         const char *registration_id;
2017         struct ao2_iterator i;
2018
2019         ast_debug(4, "Auths updated. Checking for any outbound registrations that are in permanent rejected state so they can be retried\n");
2020
2021         regs = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration",
2022                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
2023         if (!regs || ao2_container_count(regs) == 0) {
2024                 ao2_cleanup(regs);
2025                 return;
2026         }
2027
2028         i = ao2_iterator_init(regs, 0);
2029         for (; (registration = ao2_iterator_next(&i)); ao2_ref(registration, -1)) {
2030                 registration_id = ast_sorcery_object_get_id(registration);
2031                 state = get_state(registration_id);
2032                 if (state && state->client_state->status == SIP_REGISTRATION_REJECTED_PERMANENT) {
2033                         ast_debug(4, "Trying outbound registration '%s' again\n", registration_id);
2034
2035                         if (ast_sip_push_task(state->client_state->serializer,
2036                                               sip_outbound_registration_perform, ao2_bump(state))) {
2037                                 ast_log(LOG_ERROR, "Failed to perform outbound registration on '%s'\n", registration_id);
2038                                 ao2_ref(state, -1);
2039                         }
2040                 }
2041                 ao2_cleanup(state);
2042         }
2043         ao2_iterator_destroy(&i);
2044         ao2_cleanup(regs);
2045 }
2046
2047 static const struct ast_sorcery_observer observer_callbacks_auth = {
2048         .loaded = auth_observer,
2049 };
2050
2051 static int check_state(void *obj, void *arg, int flags)
2052 {
2053         struct sip_outbound_registration_state *state = obj;
2054         struct sip_outbound_registration *registration;
2055
2056         registration = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "registration",
2057                 ast_sorcery_object_get_id(state->registration));
2058         if (!registration) {
2059                 /* This is a dead registration */
2060                 return CMP_MATCH;
2061         }
2062
2063         ao2_ref(registration, -1);
2064         return 0;
2065 }
2066
2067 /*!
2068  * \internal
2069  * \brief Observer to purge dead registration states.
2070  *
2071  * \param name Module name owning the sorcery instance.
2072  * \param sorcery Instance being observed.
2073  * \param object_type Name of object being observed.
2074  * \param reloaded Non-zero if the object is being reloaded.
2075  *
2076  * \return Nothing
2077  */
2078 static void registration_loaded_observer(const char *name, const struct ast_sorcery *sorcery, const char *object_type, int reloaded)
2079 {
2080         struct ao2_container *states;
2081
2082         if (strcmp(object_type, "registration")) {
2083                 /* Not interested */
2084                 return;
2085         }
2086
2087         states = ao2_global_obj_ref(current_states);
2088         if (!states) {
2089                 /* Global container has gone.  Likely shutting down. */
2090                 return;
2091         }
2092
2093         /*
2094          * Refresh the current configured registrations. We don't need to hold
2095          * onto the objects, as the apply handler will cause their states to
2096          * be created appropriately.
2097          */
2098         ao2_cleanup(get_registrations());
2099
2100         /* Now to purge dead registrations. */
2101         ao2_callback(states, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, check_state, NULL);
2102         ao2_ref(states, -1);
2103 }
2104
2105 static const struct ast_sorcery_instance_observer observer_callbacks_registrations = {
2106         .object_type_loaded = registration_loaded_observer,
2107 };
2108
2109 static void registration_deleted_observer(const void *obj)
2110 {
2111         const struct sip_outbound_registration *registration = obj;
2112         struct ao2_container *states;
2113
2114         states = ao2_global_obj_ref(current_states);
2115         if (!states) {
2116                 /* Global container has gone.  Likely shutting down. */
2117                 return;
2118         }
2119
2120         ao2_find(states, ast_sorcery_object_get_id(registration), OBJ_UNLINK | OBJ_NODATA | OBJ_SEARCH_KEY);
2121
2122         ao2_ref(states, -1);
2123 }
2124
2125 static const struct ast_sorcery_observer registration_observer = {
2126         .deleted = registration_deleted_observer,
2127 };
2128
2129 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2130 {
2131         /* This callback is only concerned with network change messages from the system topic. */
2132         if (stasis_message_type(message) != ast_network_change_type()) {
2133                 return;
2134         }
2135         ast_debug(3, "Received network change event\n");
2136
2137         reregister_all();
2138 }
2139
2140 static int unload_module(void)
2141 {
2142         int remaining;
2143
2144         network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
2145
2146         ast_manager_unregister("PJSIPShowRegistrationsOutbound");
2147         ast_manager_unregister("PJSIPUnregister");
2148         ast_manager_unregister("PJSIPRegister");
2149
2150         ast_cli_unregister_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
2151         ast_sip_unregister_cli_formatter(cli_formatter);
2152         cli_formatter = NULL;
2153
2154         ast_sip_unregister_endpoint_identifier(&line_identifier);
2155
2156         ast_sorcery_observer_remove(ast_sip_get_sorcery(), "auth", &observer_callbacks_auth);
2157         ast_sorcery_instance_observer_remove(ast_sip_get_sorcery(), &observer_callbacks_registrations);
2158
2159         ast_sorcery_object_unregister(ast_sip_get_sorcery(), "registration");
2160
2161         ao2_global_obj_release(current_states);
2162
2163         ast_sip_transport_monitor_unregister_all(registration_transport_shutdown_cb, NULL, NULL);
2164
2165         /* Wait for registration serializers to get destroyed. */
2166         ast_debug(2, "Waiting for registration transactions to complete for unload.\n");
2167         remaining = ast_serializer_shutdown_group_join(shutdown_group, MAX_UNLOAD_TIMEOUT_TIME);
2168         if (remaining) {
2169                 /*
2170                  * NOTE: We probably have a sip_outbound_registration_client_state
2171                  * ref leak if the remaining count cannot reach zero after a few
2172                  * minutes of trying to unload.
2173                  */
2174                 ast_log(LOG_WARNING, "Unload incomplete.  Could not stop %d outbound registrations.  Try again later.\n",
2175                         remaining);
2176                 return -1;
2177         }
2178
2179         ast_debug(2, "Successful shutdown.\n");
2180
2181         ao2_cleanup(shutdown_group);
2182         shutdown_group = NULL;
2183
2184         return 0;
2185 }
2186
2187 static int load_module(void)
2188 {
2189         struct ao2_container *new_states;
2190
2191         shutdown_group = ast_serializer_shutdown_group_alloc();
2192         if (!shutdown_group) {
2193                 return AST_MODULE_LOAD_DECLINE;
2194         }
2195
2196         /* Create outbound registration states container. */
2197         new_states = ao2_container_alloc(DEFAULT_STATE_BUCKETS,
2198                 registration_state_hash, registration_state_cmp);
2199         if (!new_states) {
2200                 ast_log(LOG_ERROR, "Unable to allocate registration states container\n");
2201                 unload_module();
2202                 return AST_MODULE_LOAD_DECLINE;
2203         }
2204         ao2_global_obj_replace_unref(current_states, new_states);
2205         ao2_ref(new_states, -1);
2206
2207         /*
2208          * Register sorcery object descriptions.
2209          */
2210         ast_sorcery_apply_config(ast_sip_get_sorcery(), "res_pjsip_outbound_registration");
2211         ast_sorcery_apply_default(ast_sip_get_sorcery(), "registration", "config", "pjsip.conf,criteria=type=registration");
2212
2213         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "registration", sip_outbound_registration_alloc, NULL, sip_outbound_registration_apply)) {
2214                 unload_module();
2215                 return AST_MODULE_LOAD_DECLINE;
2216         }
2217
2218         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "type", "", OPT_NOOP_T, 0, 0);
2219         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "server_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, server_uri));
2220         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "client_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, client_uri));
2221         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "contact_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, contact_user));
2222         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, transport));
2223         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, outbound_proxy));
2224         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "expiration", "3600", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, expiration));
2225         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "retry_interval", "60", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, retry_interval));
2226         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));
2227         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));
2228         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "max_retries", "10", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, max_retries));
2229         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));
2230         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);
2231         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "support_path", "no", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, support_path));
2232         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "line", "no", OPT_BOOL_T, 1, FLDSET(struct sip_outbound_registration, line));
2233         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "endpoint", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, endpoint));
2234
2235         /*
2236          * Register sorcery observers.
2237          */
2238         if (ast_sorcery_instance_observer_add(ast_sip_get_sorcery(),
2239                 &observer_callbacks_registrations)
2240                 || ast_sorcery_observer_add(ast_sip_get_sorcery(), "auth",
2241                         &observer_callbacks_auth)
2242                 || ast_sorcery_observer_add(ast_sip_get_sorcery(), "registration",
2243                         &registration_observer)) {
2244                 ast_log(LOG_ERROR, "Unable to register observers.\n");
2245                 unload_module();
2246                 return AST_MODULE_LOAD_DECLINE;
2247         }
2248
2249         /* Register how this module identifies endpoints. */
2250         ast_sip_register_endpoint_identifier(&line_identifier);
2251
2252         /* Register CLI commands. */
2253         cli_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
2254         if (!cli_formatter) {
2255                 ast_log(LOG_ERROR, "Unable to allocate memory for cli formatter\n");
2256                 unload_module();
2257                 return AST_MODULE_LOAD_DECLINE;
2258         }
2259         cli_formatter->name = "registration";
2260         cli_formatter->print_header = cli_print_header;
2261         cli_formatter->print_body = cli_print_body;
2262         cli_formatter->get_container = cli_get_container;
2263         cli_formatter->iterate = cli_iterator;
2264         cli_formatter->get_id = ast_sorcery_object_get_id;
2265         cli_formatter->retrieve_by_id = cli_retrieve_by_id;
2266         ast_sip_register_cli_formatter(cli_formatter);
2267         ast_cli_register_multiple(cli_outbound_registration, ARRAY_LEN(cli_outbound_registration));
2268
2269         /* Register AMI actions. */
2270         ast_manager_register_xml("PJSIPUnregister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_unregister);
2271         ast_manager_register_xml("PJSIPRegister", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_register);
2272         ast_manager_register_xml("PJSIPShowRegistrationsOutbound", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_show_outbound_registrations);
2273
2274         /* Clear any previous statsd gauges in case we weren't shutdown cleanly */
2275         ast_statsd_log("PJSIP.registrations.count", AST_STATSD_GAUGE, 0);
2276         ast_statsd_log("PJSIP.registrations.state.Registered", AST_STATSD_GAUGE, 0);
2277         ast_statsd_log("PJSIP.registrations.state.Unregistered", AST_STATSD_GAUGE, 0);
2278         ast_statsd_log("PJSIP.registrations.state.Rejected", AST_STATSD_GAUGE, 0);
2279
2280         /* Load configuration objects */
2281         ast_sorcery_load_object(ast_sip_get_sorcery(), "registration");
2282
2283         network_change_sub = stasis_subscribe(ast_system_topic(),
2284                 network_change_stasis_cb, NULL);
2285
2286         return AST_MODULE_LOAD_SUCCESS;
2287 }
2288
2289 static int reload_module(void)
2290 {
2291         ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
2292         return 0;
2293 }
2294
2295 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Outbound Registration Support",
2296         .support_level = AST_MODULE_SUPPORT_CORE,
2297         .load = load_module,
2298         .reload = reload_module,
2299         .unload = unload_module,
2300         .load_pri = AST_MODPRI_APP_DEPEND,
2301         .requires = "res_pjsip",
2302         .optional_modules = "res_statsd",
2303 );