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