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