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