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