Add base XML documentation for res_sip
[asterisk/asterisk.git] / res / res_sip_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_sip</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_sip.h"
31 #include "asterisk/module.h"
32 #include "asterisk/taskprocessor.h"
33
34 /*** DOCUMENTATION
35         <configInfo name="res_sip_outbound_registration" language="en_US">
36                 <synopsis>SIP resource for outbound registrations</synopsis>
37                 <description><para>
38                         <emphasis>Outbound Registration</emphasis>
39                         </para>
40                         <para>This module allows <literal>res_sip</literal> to register to other SIP servers.</para>
41                 </description>
42                 <configFile name="res_sip.conf">
43                         <configObject name="registration">
44                                 <synopsis>The configuration for outbound registration</synopsis>
45                                 <description><para>
46                                         Registration is <emphasis>COMPLETELY</emphasis> separate from the rest of
47                                         <literal>res_sip.conf</literal>. A minimal configuration consists of
48                                         setting a <literal>server_uri</literal> and a <literal>client_uri</literal>.
49                                 </para></description>
50                                 <configOption name="auth_rejection_permanent" default="yes">
51                                         <synopsis>Determines whether failed authentication challenges are treated
52                                         as permanent failures.</synopsis>
53                                         <description><para>If this option is enabled and an authentication challenge fails,
54                                         registration will not be attempted again until the configuration is reloaded.</para></description>
55                                 </configOption>
56                                 <configOption name="client_uri">
57                                         <synopsis>Client SIP URI used when attemping outbound registration</synopsis>
58                                 </configOption>
59                                 <configOption name="contact_user">
60                                         <synopsis>Contact User to use in request</synopsis>
61                                 </configOption>
62                                 <configOption name="expiration" default="3600">
63                                         <synopsis>Expiration time for registrations in seconds</synopsis>
64                                 </configOption>
65                                 <configOption name="max_retries" default="10">
66                                         <synopsis>Maximum number of registration attempts.</synopsis>
67                                 </configOption>
68                                 <configOption name="outbound_auth" default="">
69                                         <synopsis>Authentication object to be used for outbound registrations.</synopsis>
70                                 </configOption>
71                                 <configOption name="outbound_proxy" default="">
72                                         <synopsis>Outbound Proxy used to send registrations</synopsis>
73                                 </configOption>
74                                 <configOption name="retry_interval" default="60">
75                                         <synopsis>Interval in seconds between retries if outbound registration is unsuccessful</synopsis>
76                                 </configOption>
77                                 <configOption name="server_uri">
78                                         <synopsis>SIP URI of the server to register against</synopsis>
79                                 </configOption>
80                                 <configOption name="transport">
81                                         <synopsis>Transport used for outbound authentication</synopsis>
82                                         <description>
83                                                 <note><para>A <replaceable>transport</replaceable> configured in
84                                                 <literal>res_sip.conf</literal>. As with other <literal>res_sip</literal> modules, this will use the first available transport of the appropriate type if unconfigured.</para></note>
85                                         </description>
86                                 </configOption>
87                                 <configOption name="type">
88                                         <synopsis>Must be of type 'registration'.</synopsis>
89                                 </configOption>
90                         </configObject>
91                 </configFile>
92         </configInfo>
93  ***/
94
95 /*! \brief Amount of buffer time (in seconds) before expiration that we re-register at */
96 #define REREGISTER_BUFFER_TIME 10
97
98 /*! \brief Various states that an outbound registration may be in */
99 enum sip_outbound_registration_status {
100         /*! \brief Currently unregistered */
101         SIP_REGISTRATION_UNREGISTERED = 0,
102         /*! \brief Registered, yay! */
103         SIP_REGISTRATION_REGISTERED,
104         /*! \brief Registration was rejected, but response was temporal */
105         SIP_REGISTRATION_REJECTED_TEMPORARY,
106         /*! \brief Registration was rejected, permanently */
107         SIP_REGISTRATION_REJECTED_PERMANENT,
108         /*! \brief Registration has been stopped */
109         SIP_REGISTRATION_STOPPED,
110 };
111
112 /*! \brief Outbound registration client state information (persists for lifetime of regc) */
113 struct sip_outbound_registration_client_state {
114         /*! \brief Current status of this registration */
115         enum sip_outbound_registration_status status;
116         /*! \brief Outbound registration client */
117         pjsip_regc *client;
118         /*! \brief Timer entry for retrying on temporal responses */
119         pj_timer_entry timer;
120         /*! \brief Current number of retries */
121         unsigned int retries;
122         /*! \brief Maximum number of retries permitted */
123         unsigned int max_retries;
124         /*! \brief Interval at which retries should occur for temporal responses */
125         unsigned int retry_interval;
126         /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
127         unsigned int auth_rejection_permanent;
128         /*! \brief Serializer for stuff and things */
129         struct ast_taskprocessor *serializer;
130         /*! \brief Configured authentication credentials */
131         const char **sip_outbound_auths;
132         /*! \brief Number of configured auths */
133         size_t num_outbound_auths;
134         /*! \brief Registration should be destroyed after completion of transaction */
135         unsigned int destroy:1;
136 };
137
138 /*! \brief Outbound registration state information (persists for lifetime that registration should exist) */
139 struct sip_outbound_registration_state {
140         /*! \brief Client state information */
141         struct sip_outbound_registration_client_state *client_state;
142 };
143
144 /*! \brief Outbound registration information */
145 struct sip_outbound_registration {
146         /*! \brief Sorcery object details */
147         SORCERY_OBJECT(details);
148         /*! \brief Stringfields */
149         AST_DECLARE_STRING_FIELDS(
150                 /*! \brief URI for the registrar */
151                 AST_STRING_FIELD(server_uri);
152                 /*! \brief URI for the AOR */
153                 AST_STRING_FIELD(client_uri);
154                 /*! \brief Optional user for contact header */
155                 AST_STRING_FIELD(contact_user);
156                 /*! \brief Explicit transport to use for registration */
157                 AST_STRING_FIELD(transport);
158                 /*! \brief Outbound proxy to use */
159                 AST_STRING_FIELD(outbound_proxy);
160         );
161         /*! \brief Requested expiration time */
162         unsigned int expiration;
163         /*! \brief Interval at which retries should occur for temporal responses */
164         unsigned int retry_interval;
165         /*! \brief Treat authentication challenges that we cannot handle as permanent failures */
166         unsigned int auth_rejection_permanent;
167         /*! \brief Maximum number of retries permitted */
168         unsigned int max_retries;
169         /*! \brief Outbound registration state */
170         struct sip_outbound_registration_state *state;
171         /*! \brief Configured authentication credentials */
172         const char **sip_outbound_auths;
173         /*! \brief Number of configured auths */
174         size_t num_outbound_auths;
175 };
176
177 static void destroy_auths(const char **auths, size_t num_auths)
178 {
179         int i;
180         for (i = 0; i < num_auths; ++i) {
181                 ast_free((char *) auths[i]);
182         }
183         ast_free(auths);
184 }
185
186 /*! \brief Helper function which cancels the timer on a client */
187 static void cancel_registration(struct sip_outbound_registration_client_state *client_state)
188 {
189         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &client_state->timer)) {
190                 /* The timer was successfully cancelled, drop the refcount of client_state */
191                 ao2_ref(client_state, -1);
192         }
193 }
194
195 /*! \brief Callback function for registering */
196 static int handle_client_registration(void *data)
197 {
198         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
199         pjsip_tx_data *tdata;
200
201         cancel_registration(client_state);
202
203         if ((client_state->status == SIP_REGISTRATION_STOPPED) ||
204                 (pjsip_regc_register(client_state->client, PJ_FALSE, &tdata) != PJ_SUCCESS)) {
205                 return 0;
206         }
207
208         /* Due to the registration the callback may now get called, so bump the ref count */
209         ao2_ref(client_state, +1);
210         if (pjsip_regc_send(client_state->client, tdata) != PJ_SUCCESS) {
211                 ao2_ref(client_state, -1);
212                 pjsip_tx_data_dec_ref(tdata);
213         }
214
215         return 0;
216 }
217
218 /*! \brief Timer callback function, used just for registrations */
219 static void sip_outbound_registration_timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
220 {
221         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, entry->user_data, ao2_cleanup);
222
223         ao2_ref(client_state, +1);
224         if (ast_sip_push_task(client_state->serializer, handle_client_registration, client_state)) {
225                 ast_log(LOG_WARNING, "Failed to pass outbound registration to threadpool\n");
226                 ao2_ref(client_state, -1);
227         }
228
229         entry->id = 0;
230 }
231
232 /*! \brief Helper function which sets up the timer to re-register in a specific amount of time */
233 static void schedule_registration(struct sip_outbound_registration_client_state *client_state, unsigned int seconds)
234 {
235         pj_time_val delay = { .sec = seconds, };
236
237         cancel_registration(client_state);
238
239         ao2_ref(client_state, +1);
240         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &client_state->timer, &delay) != PJ_SUCCESS) {
241                 ast_log(LOG_WARNING, "Failed to pass timed registration to scheduler\n");
242                 ao2_ref(client_state, -1);
243         }
244 }
245
246 /*! \brief Callback function for unregistering (potentially) and destroying state */
247 static int handle_client_state_destruction(void *data)
248 {
249         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, data, ao2_cleanup);
250         pjsip_regc_info info;
251
252         cancel_registration(client_state);
253
254         pjsip_regc_get_info(client_state->client, &info);
255
256         if (info.is_busy == PJ_TRUE) {
257                 /* If a client transaction is in progress we defer until it is complete */
258                 client_state->destroy = 1;
259                 return 0;
260         }
261
262         if (client_state->status != SIP_REGISTRATION_UNREGISTERED && client_state->status != SIP_REGISTRATION_REJECTED_PERMANENT) {
263                 pjsip_tx_data *tdata;
264
265                 if (pjsip_regc_unregister(client_state->client, &tdata) == PJ_SUCCESS) {
266                         pjsip_regc_send(client_state->client, tdata);
267                 }
268         }
269
270         pjsip_regc_destroy(client_state->client);
271
272         client_state->status = SIP_REGISTRATION_STOPPED;
273         destroy_auths(client_state->sip_outbound_auths, client_state->num_outbound_auths);
274
275         return 0;
276 }
277
278 /*! \brief Structure for registration response */
279 struct registration_response {
280         /*! \brief Response code for the registration attempt */
281         int code;
282         /*! \brief Expiration time for registration */
283         int expiration;
284         /*! \brief Retry-After value */
285         int retry_after;
286         /*! \brief Outbound registration client state */
287         struct sip_outbound_registration_client_state *client_state;
288         /*! \brief The response message */
289         pjsip_rx_data *rdata;
290         /*! \brief The response transaction */
291         pjsip_transaction *tsx;
292 };
293
294 /*! \brief Registration response structure destructor */
295 static void registration_response_destroy(void *obj)
296 {
297         struct registration_response *response = obj;
298
299         pjsip_rx_data_free_cloned(response->rdata);
300         ao2_cleanup(response->client_state);
301 }
302
303 /* \brief Helper funtion which determines if a response code is temporal or not */
304 static int sip_outbound_registration_is_temporal(unsigned int code,
305                 struct sip_outbound_registration_client_state *client_state)
306 {
307         /* Shamelessly taken from pjsua */
308         if (code == PJSIP_SC_REQUEST_TIMEOUT ||
309                 code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
310                 code == PJSIP_SC_BAD_GATEWAY ||
311                 code == PJSIP_SC_SERVICE_UNAVAILABLE ||
312                 code == PJSIP_SC_SERVER_TIMEOUT ||
313                 ((code == PJSIP_SC_UNAUTHORIZED ||
314                   code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED) &&
315                  !client_state->auth_rejection_permanent) ||
316                 PJSIP_IS_STATUS_IN_CLASS(code, 600)) {
317                 return 1;
318         } else {
319                 return 0;
320         }
321 }
322
323 /*! \brief Callback function for handling a response to a registration attempt */
324 static int handle_registration_response(void *data)
325 {
326         RAII_VAR(struct registration_response *, response, data, ao2_cleanup);
327         pjsip_regc_info info;
328         char server_uri[PJSIP_MAX_URL_SIZE], client_uri[PJSIP_MAX_URL_SIZE];
329
330         if (response->client_state->status == SIP_REGISTRATION_STOPPED) {
331                 return 0;
332         }
333
334         pjsip_regc_get_info(response->client_state->client, &info);
335         ast_copy_pj_str(server_uri, &info.server_uri, sizeof(server_uri));
336         ast_copy_pj_str(client_uri, &info.client_uri, sizeof(client_uri));
337
338         if (response->code == 401 || response->code == 407) {
339                 pjsip_tx_data *tdata;
340                 if (!ast_sip_create_request_with_auth(response->client_state->sip_outbound_auths, response->client_state->num_outbound_auths,
341                                 response->rdata, response->tsx, &tdata)) {
342                         pjsip_regc_send(response->client_state->client, tdata);
343                         return 0;
344                 }
345                 /* Otherwise, fall through so the failure is processed appropriately */
346         }
347
348         if (PJSIP_IS_STATUS_IN_CLASS(response->code, 200)) {
349                 /* If the registration went fine simply reschedule registration for the future */
350                 response->client_state->status = SIP_REGISTRATION_REGISTERED;
351                 response->client_state->retries = 0;
352                 schedule_registration(response->client_state, response->expiration - REREGISTER_BUFFER_TIME);
353         } else if (response->retry_after) {
354                 /* If we have been instructed to retry after a period of time, schedule it as such */
355                 response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
356                 schedule_registration(response->client_state, response->retry_after);
357                 ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on registration attempt to '%s', instructed to retry in '%d'\n",
358                         response->code, server_uri, client_uri, response->retry_after);
359         } else if (response->client_state->retry_interval && sip_outbound_registration_is_temporal(response->code, response->client_state)) {
360                 if (response->client_state->retries == response->client_state->max_retries) {
361                         /* If we received enough temporal responses to exceed our maximum give up permanently */
362                         response->client_state->status = SIP_REGISTRATION_REJECTED_PERMANENT;
363                         ast_log(LOG_WARNING, "Maximum retries reached when attempting outbound registration to '%s' with client '%s', stopping registration attempt\n",
364                                 server_uri, client_uri);
365                 } else {
366                         /* On the other hand if we can still try some more do so */
367                         response->client_state->status = SIP_REGISTRATION_REJECTED_TEMPORARY;
368                         response->client_state->retries++;
369                         schedule_registration(response->client_state, response->client_state->retry_interval);
370                         ast_log(LOG_WARNING, "Temporal response '%d' received from '%s' on registration attempt to '%s', retrying in '%d' seconds\n",
371                                 response->code, server_uri, client_uri, response->client_state->retry_interval);
372                 }
373         } else {
374                 /* Finally if there's no hope of registering give up */
375                 response->client_state->status = SIP_REGISTRATION_REJECTED_PERMANENT;
376                 ast_log(LOG_WARNING, "Fatal response '%d' received from '%s' on registration attempt to '%s', stopping outbound registration\n",
377                         response->code, server_uri, client_uri);
378         }
379
380         /* If deferred destruction is in use see if we need to destroy now */
381         if (response->client_state->destroy) {
382                 handle_client_state_destruction(response->client_state);
383         }
384
385         return 0;
386 }
387
388 /*! \brief Callback function for outbound registration client */
389 static void sip_outbound_registration_response_cb(struct pjsip_regc_cbparam *param)
390 {
391         RAII_VAR(struct sip_outbound_registration_client_state *, client_state, param->token, ao2_cleanup);
392         struct registration_response *response = ao2_alloc(sizeof(*response), registration_response_destroy);
393         struct pjsip_retry_after_hdr *retry_after = pjsip_msg_find_hdr(param->rdata->msg_info.msg, PJSIP_H_RETRY_AFTER, NULL);
394
395         response->code = param->code;
396         response->expiration = param->expiration;
397         response->retry_after = retry_after ? retry_after->ivalue : 0;
398         response->client_state = client_state;
399         response->tsx = pjsip_rdata_get_tsx(param->rdata);
400         pjsip_rx_data_clone(param->rdata, 0, &response->rdata);
401         ao2_ref(response->client_state, +1);
402
403         if (ast_sip_push_task(client_state->serializer, handle_registration_response, response)) {
404                 ast_log(LOG_WARNING, "Failed to pass incoming registration response to threadpool\n");
405                 ao2_cleanup(response);
406         }
407 }
408
409 /*! \brief Destructor function for registration state */
410 static void sip_outbound_registration_state_destroy(void *obj)
411 {
412         struct sip_outbound_registration_state *state = obj;
413
414         if (!state->client_state) {
415                 return;
416         }
417
418         if (state->client_state->serializer && ast_sip_push_task(state->client_state->serializer, handle_client_state_destruction, state->client_state)) {
419                 ast_log(LOG_WARNING, "Failed to pass outbound registration client destruction to threadpool\n");
420                 ao2_ref(state->client_state, -1);
421         }
422 }
423
424 /*! \brief Destructor function for client registration state */
425 static void sip_outbound_registration_client_state_destroy(void *obj)
426 {
427         struct sip_outbound_registration_client_state *client_state = obj;
428
429         ast_taskprocessor_unreference(client_state->serializer);
430 }
431
432 /*! \brief Allocator function for registration state */
433 static struct sip_outbound_registration_state *sip_outbound_registration_state_alloc(void)
434 {
435         struct sip_outbound_registration_state *state = ao2_alloc(sizeof(*state), sip_outbound_registration_state_destroy);
436
437         if (!state || !(state->client_state = ao2_alloc(sizeof(*state->client_state), sip_outbound_registration_client_state_destroy))) {
438                 ao2_cleanup(state);
439                 return NULL;
440         }
441
442         if ((pjsip_regc_create(ast_sip_get_pjsip_endpoint(), state->client_state, sip_outbound_registration_response_cb, &state->client_state->client) != PJ_SUCCESS) ||
443                 !(state->client_state->serializer = ast_sip_create_serializer())) {
444                 /* This is on purpose, normal operation will have it be deallocated within the serializer */
445                 pjsip_regc_destroy(state->client_state->client);
446                 ao2_cleanup(state->client_state);
447                 ao2_cleanup(state);
448                 return NULL;
449         }
450
451         state->client_state->status = SIP_REGISTRATION_UNREGISTERED;
452         state->client_state->timer.user_data = state->client_state;
453         state->client_state->timer.cb = sip_outbound_registration_timer_cb;
454
455         return state;
456 }
457
458 /*! \brief Destructor function for registration information */
459 static void sip_outbound_registration_destroy(void *obj)
460 {
461         struct sip_outbound_registration *registration = obj;
462
463         ao2_cleanup(registration->state);
464         destroy_auths(registration->sip_outbound_auths, registration->num_outbound_auths);
465
466         ast_string_field_free_memory(registration);
467 }
468
469 /*! \brief Allocator function for registration information */
470 static void *sip_outbound_registration_alloc(const char *name)
471 {
472         struct sip_outbound_registration *registration = ao2_alloc(sizeof(*registration), sip_outbound_registration_destroy);
473
474         if (!registration || ast_string_field_init(registration, 256)) {
475                 ao2_cleanup(registration);
476                 return NULL;
477         }
478
479         return registration;
480 }
481
482 /*! \brief Helper function which populates a pj_str_t with a contact header */
483 static int sip_dialog_create_contact(pj_pool_t *pool, pj_str_t *contact, const char *user, const pj_str_t *target, pjsip_tpselector *selector)
484 {
485         pj_str_t tmp, local_addr;
486         pjsip_uri *uri;
487         pjsip_sip_uri *sip_uri;
488         pjsip_transport_type_e type = PJSIP_TRANSPORT_UNSPECIFIED;
489         int local_port;
490
491         pj_strdup_with_null(pool, &tmp, target);
492
493         if (!(uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0)) ||
494             (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))) {
495                 return -1;
496         }
497
498         sip_uri = pjsip_uri_get_uri(uri);
499
500         if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri)) {
501                 type = PJSIP_TRANSPORT_TLS;
502         } else if (!sip_uri->transport_param.slen) {
503                 type = PJSIP_TRANSPORT_UDP;
504         } else {
505                 type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
506         }
507
508         if (type == PJSIP_TRANSPORT_UNSPECIFIED) {
509                 return -1;
510         }
511
512         if (pj_strchr(&sip_uri->host, ':')) {
513                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
514         }
515
516         if (pjsip_tpmgr_find_local_addr(pjsip_endpt_get_tpmgr(ast_sip_get_pjsip_endpoint()), pool, type, selector,
517                                                               &local_addr, &local_port) != PJ_SUCCESS) {
518                 return -1;
519         }
520
521         if (!pj_strchr(&sip_uri->host, ':') && pj_strchr(&local_addr, ':')) {
522                 type = (pjsip_transport_type_e)(((int)type) + PJSIP_TRANSPORT_IPV6);
523         }
524
525         contact->ptr = pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
526         contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
527                                       "<%s:%s@%s%.*s%s:%d%s%s>",
528                                       (pjsip_transport_get_flag_from_type(type) & PJSIP_TRANSPORT_SECURE) ? "sips" : "sip",
529                                       user,
530                                       (type & PJSIP_TRANSPORT_IPV6) ? "[" : "",
531                                       (int)local_addr.slen,
532                                       local_addr.ptr,
533                                       (type & PJSIP_TRANSPORT_IPV6) ? "]" : "",
534                                       local_port,
535                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? ";transport=" : "",
536                                       (type != PJSIP_TRANSPORT_UDP && type != PJSIP_TRANSPORT_UDP6) ? pjsip_transport_get_type_name(type) : "");
537
538         return 0;
539 }
540
541 /*!
542  * \internal
543  * \brief Check if a registration can be reused
544  *
545  * This checks if the existing outbound registration's configuration differs from a newly-applied
546  * outbound registration to see if the applied one.
547  *
548  * \param existing The pre-existing outbound registration
549  * \param applied The newly-created registration
550  */
551 static int can_reuse_registration(struct sip_outbound_registration *existing, struct sip_outbound_registration *applied)
552 {
553         int i;
554
555         if (strcmp(existing->server_uri, applied->server_uri) || strcmp(existing->client_uri, applied->client_uri) ||
556                 strcmp(existing->transport, applied->transport) || strcmp(existing->contact_user, applied->contact_user) ||
557                 strcmp(existing->outbound_proxy, applied->outbound_proxy) || existing->num_outbound_auths != applied->num_outbound_auths ||
558                 existing->auth_rejection_permanent != applied->auth_rejection_permanent) {
559                 return 0;
560         }
561
562         for (i = 0; i < existing->num_outbound_auths; ++i) {
563                 if (strcmp(existing->sip_outbound_auths[i], applied->sip_outbound_auths[i])) {
564                         return 0;
565                 }
566         }
567
568         return 1;
569 }
570
571 /*! \brief Apply function which finds or allocates a state structure */
572 static int sip_outbound_registration_apply(const struct ast_sorcery *sorcery, void *obj)
573 {
574         RAII_VAR(struct sip_outbound_registration *, existing, ast_sorcery_retrieve_by_id(sorcery, "registration", ast_sorcery_object_get_id(obj)), ao2_cleanup);
575         struct sip_outbound_registration *applied = obj;
576         pj_str_t server_uri, client_uri, contact_uri;
577         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
578
579         if (!existing) {
580                 /* If no existing registration exists we can just start fresh easily */
581                 applied->state = sip_outbound_registration_state_alloc();
582         } else {
583                 /* If there is an existing registration things are more complicated, we can immediately reuse this state if most stuff remains unchanged */
584                 if (can_reuse_registration(existing, applied)) {
585                         applied->state = existing->state;
586                         ao2_ref(applied->state, +1);
587                         return 0;
588                 }
589                 applied->state = sip_outbound_registration_state_alloc();
590         }
591
592         if (!applied->state) {
593                 return -1;
594         }
595
596         if (!ast_strlen_zero(applied->transport)) {
597                 RAII_VAR(struct ast_sip_transport *, transport, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "transport", applied->transport), ao2_cleanup);
598
599                 if (!transport || !transport->state) {
600                         return -1;
601                 }
602
603                 if (transport->type == AST_TRANSPORT_UDP) {
604                         selector.type = PJSIP_TPSELECTOR_TRANSPORT;
605                         selector.u.transport = transport->state->transport;
606                 } else if (transport->type == AST_TRANSPORT_TCP || transport->type == AST_TRANSPORT_TLS) {
607                         selector.type = PJSIP_TPSELECTOR_LISTENER;
608                         selector.u.listener = transport->state->factory;
609                 } else {
610                         return -1;
611                 }
612         }
613
614         pjsip_regc_set_transport(applied->state->client_state->client, &selector);
615
616         if (!ast_strlen_zero(applied->outbound_proxy)) {
617                 pjsip_route_hdr route_set, *route;
618                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
619                 pj_str_t tmp;
620
621                 pj_list_init(&route_set);
622
623                 pj_strdup2_with_null(pjsip_regc_get_pool(applied->state->client_state->client), &tmp, applied->outbound_proxy);
624                 if (!(route = pjsip_parse_hdr(pjsip_regc_get_pool(applied->state->client_state->client), &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL))) {
625                         return -1;
626                 }
627                 pj_list_push_back(&route_set, route);
628
629                 pjsip_regc_set_route_set(applied->state->client_state->client, &route_set);
630         }
631
632         pj_cstr(&server_uri, applied->server_uri);
633
634         if (sip_dialog_create_contact(pjsip_regc_get_pool(applied->state->client_state->client), &contact_uri, S_OR(applied->contact_user, "s"), &server_uri, &selector)) {
635                 return -1;
636         }
637
638         pj_cstr(&client_uri, applied->client_uri);
639
640         if (pjsip_regc_init(applied->state->client_state->client, &server_uri, &client_uri, &client_uri, 1, &contact_uri, applied->expiration) != PJ_SUCCESS) {
641                 return -1;
642         }
643
644         return 0;
645 }
646
647 /*! \brief Helper function which performs a single registration */
648 static int sip_outbound_registration_perform(void *obj, void *arg, int flags)
649 {
650         struct sip_outbound_registration *registration = obj;
651         size_t i;
652
653         /* Just in case the client state is being reused for this registration, free the auth information */
654         destroy_auths(registration->state->client_state->sip_outbound_auths,
655                         registration->state->client_state->num_outbound_auths);
656         registration->state->client_state->num_outbound_auths = 0;
657
658         registration->state->client_state->sip_outbound_auths = ast_calloc(registration->num_outbound_auths, sizeof(char *));
659         for (i = 0; i < registration->num_outbound_auths; ++i) {
660                 registration->state->client_state->sip_outbound_auths[i] = ast_strdup(registration->sip_outbound_auths[i]);
661         }
662         registration->state->client_state->num_outbound_auths = registration->num_outbound_auths;
663         registration->state->client_state->retry_interval = registration->retry_interval;
664         registration->state->client_state->max_retries = registration->max_retries;
665         registration->state->client_state->retries = 0;
666
667         pjsip_regc_update_expires(registration->state->client_state->client, registration->expiration);
668
669         schedule_registration(registration->state->client_state, (ast_random() % 10) + 1);
670
671         return 0;
672 }
673
674 /*! \brief Helper function which performs all registrations */
675 static void sip_outbound_registration_perform_all(void)
676 {
677         RAII_VAR(struct ao2_container *, registrations, ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "registration", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL), ao2_cleanup);
678
679         if (!registrations) {
680                 return;
681         }
682
683         ao2_callback(registrations, OBJ_NODATA, sip_outbound_registration_perform, NULL);
684 }
685
686 #define AUTH_INCREMENT 4
687
688 static const char **auth_alloc(const char *value, size_t *num_auths)
689 {
690         char *auths = ast_strdupa(value);
691         char *val;
692         int num_alloced = 0;
693         const char **alloced_auths = NULL;
694
695         while ((val = strsep(&auths, ","))) {
696                 if (*num_auths >= num_alloced) {
697                         size_t size;
698                         num_alloced += AUTH_INCREMENT;
699                         size = num_alloced * sizeof(char *);
700                         alloced_auths = ast_realloc(alloced_auths, size);
701                         if (!alloced_auths) {
702                                 goto failure;
703                         }
704                 }
705                 alloced_auths[*num_auths] = ast_strdup(val);
706                 if (!alloced_auths[*num_auths]) {
707                         goto failure;
708                 }
709                 ++(*num_auths);
710         }
711         return alloced_auths;
712
713 failure:
714         destroy_auths(alloced_auths, *num_auths);
715         return NULL;
716 }
717
718 static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
719 {
720         struct sip_outbound_registration *registration = obj;
721
722         registration->sip_outbound_auths = auth_alloc(var->value, &registration->num_outbound_auths);
723         if (!registration->sip_outbound_auths) {
724                 return -1;
725         }
726         return 0;
727 }
728
729 static int load_module(void)
730 {
731         ast_sorcery_apply_default(ast_sip_get_sorcery(), "registration", "config", "res_sip.conf,criteria=type=registration");
732
733         if (ast_sorcery_object_register(ast_sip_get_sorcery(), "registration", sip_outbound_registration_alloc, NULL, sip_outbound_registration_apply)) {
734                 return AST_MODULE_LOAD_DECLINE;
735         }
736
737         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "type", "", OPT_NOOP_T, 0, 0);
738         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "server_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, server_uri));
739         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "client_uri", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, client_uri));
740         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "contact_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, contact_user));
741         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, transport));
742         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct sip_outbound_registration, outbound_proxy));
743         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "expiration", "3600", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, expiration));
744         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "retry_interval", "60", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, retry_interval));
745         ast_sorcery_object_field_register(ast_sip_get_sorcery(), "registration", "max_retries", "10", OPT_UINT_T, 0, FLDSET(struct sip_outbound_registration, max_retries));
746         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));
747         ast_sorcery_object_field_register_custom(ast_sip_get_sorcery(), "registration", "outbound_auth", "", outbound_auth_handler, NULL, 0, 0);
748         ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
749         sip_outbound_registration_perform_all();
750
751         return AST_MODULE_LOAD_SUCCESS;
752 }
753
754 static int reload_module(void)
755 {
756         ast_sorcery_reload_object(ast_sip_get_sorcery(), "registration");
757         sip_outbound_registration_perform_all();
758         return 0;
759 }
760
761 static int unload_module(void)
762 {
763         return 0;
764 }
765
766 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "SIP Outbound Registration Support",
767                 .load = load_module,
768                 .reload = reload_module,
769                 .unload = unload_module,
770                 .load_pri = AST_MODPRI_APP_DEPEND,
771                );