res_pjsip: Handle reloading when permanent contacts exist and qualify is configured.
[asterisk/asterisk.git] / res / res_pjsip_registrar.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/module.h"
32 #include "asterisk/test.h"
33 #include "asterisk/taskprocessor.h"
34 #include "asterisk/manager.h"
35 #include "res_pjsip/include/res_pjsip_private.h"
36
37 /*** DOCUMENTATION
38         <manager name="PJSIPShowRegistrationsInbound" language="en_US">
39                 <synopsis>
40                         Lists PJSIP inbound registrations.
41                 </synopsis>
42                 <syntax />
43                 <description>
44                         <para>
45                         In response <literal>InboundRegistrationDetail</literal> events showing configuration and status
46                         information are raised for each inbound registration object.  As well as <literal>AuthDetail</literal>
47                         events for each associated auth object.  Once all events are completed an
48                         <literal>InboundRegistrationDetailComplete</literal> is issued.
49                         </para>
50                 </description>
51         </manager>
52  ***/
53
54 /*! \brief Internal function which returns the expiration time for a contact */
55 static int registrar_get_expiration(const struct ast_sip_aor *aor, const pjsip_contact_hdr *contact, const pjsip_rx_data *rdata)
56 {
57         pjsip_expires_hdr *expires;
58         int expiration = aor->default_expiration;
59
60         if (contact->expires != -1) {
61                 /* Expiration was provided with the contact itself */
62                 expiration = contact->expires;
63         } else if ((expires = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
64                 /* Expiration was provided using the Expires header */
65                 expiration = expires->ivalue;
66         }
67
68         /* If the value has explicitly been set to 0, do not enforce */
69         if (!expiration) {
70                 return expiration;
71         }
72
73         /* Enforce the range that we will allow for expiration */
74         if (expiration < aor->minimum_expiration) {
75                 expiration = aor->minimum_expiration;
76         } else if (expiration > aor->maximum_expiration) {
77                 expiration = aor->maximum_expiration;
78         }
79
80         return expiration;
81 }
82
83 /*! \brief Structure used for finding contact */
84 struct registrar_contact_details {
85         /*! \brief Pool used for parsing URI */
86         pj_pool_t *pool;
87         /*! \brief URI being looked for */
88         pjsip_uri *uri;
89 };
90
91 /*! \brief Callback function for finding a contact */
92 static int registrar_find_contact(void *obj, void *arg, int flags)
93 {
94         struct ast_sip_contact *contact = obj;
95         const struct registrar_contact_details *details = arg;
96         pjsip_uri *contact_uri = pjsip_parse_uri(details->pool, (char*)contact->uri, strlen(contact->uri), 0);
97
98         return (pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, details->uri, contact_uri) == PJ_SUCCESS) ? CMP_MATCH | CMP_STOP : 0;
99 }
100
101 /*! \brief Internal function which validates provided Contact headers to confirm that they are acceptable, and returns number of contacts */
102 static int registrar_validate_contacts(const pjsip_rx_data *rdata, struct ao2_container *contacts, struct ast_sip_aor *aor, int *added, int *updated, int *deleted)
103 {
104         pjsip_contact_hdr *previous = NULL, *contact = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
105         struct registrar_contact_details details = {
106                 .pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Contact Comparison", 256, 256),
107         };
108
109         if (!details.pool) {
110                 return -1;
111         }
112
113         while ((contact = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact->next))) {
114                 int expiration = registrar_get_expiration(aor, contact, rdata);
115                 RAII_VAR(struct ast_sip_contact *, existing, NULL, ao2_cleanup);
116
117                 if (contact->star) {
118                         /* The expiration MUST be 0 when a '*' contact is used and there must be no other contact */
119                         if ((expiration != 0) || previous) {
120                                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
121                                 return -1;
122                         }
123                         continue;
124                 } else if (previous && previous->star) {
125                         /* If there is a previous contact and it is a '*' this is a deal breaker */
126                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
127                         return -1;
128                 }
129                 previous = contact;
130
131                 if (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
132                         continue;
133                 }
134
135                 details.uri = pjsip_uri_get_uri(contact->uri);
136
137                 /* Determine if this is an add, update, or delete for policy enforcement purposes */
138                 if (!(existing = ao2_callback(contacts, 0, registrar_find_contact, &details))) {
139                         if (expiration) {
140                                 (*added)++;
141                         }
142                 } else if (expiration) {
143                         (*updated)++;
144                 } else {
145                         (*deleted)++;
146                 }
147         }
148
149         /* The provided contacts are acceptable, huzzah! */
150         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
151         return 0;
152 }
153
154 /*! \brief Callback function which prunes static contacts */
155 static int registrar_prune_static(void *obj, void *arg, int flags)
156 {
157         struct ast_sip_contact *contact = obj;
158
159         return ast_tvzero(contact->expiration_time) ? CMP_MATCH : 0;
160 }
161
162 /*! \brief Internal function used to delete a contact from an AOR */
163 static int registrar_delete_contact(void *obj, void *arg, int flags)
164 {
165         struct ast_sip_contact *contact = obj;
166         const char *aor_name = arg;
167
168         ast_sip_location_delete_contact(contact);
169         if (!ast_strlen_zero(aor_name)) {
170                 ast_verb(3, "Removed contact '%s' from AOR '%s' due to request\n", contact->uri, aor_name);
171                 ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
172                                 "Contact: %s\r\n"
173                                 "AOR: %s\r\n"
174                                 "UserAgent: %s",
175                                 contact->uri,
176                                 aor_name,
177                                 contact->user_agent);
178         }
179
180         return 0;
181 }
182
183 /*! \brief Internal function which adds a contact to a response */
184 static int registrar_add_contact(void *obj, void *arg, int flags)
185 {
186         struct ast_sip_contact *contact = obj;
187         pjsip_tx_data *tdata = arg;
188         pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(tdata->pool);
189         pj_str_t uri;
190
191         pj_strdup2_with_null(tdata->pool, &uri, contact->uri);
192         hdr->uri = pjsip_parse_uri(tdata->pool, uri.ptr, uri.slen, PJSIP_PARSE_URI_AS_NAMEADDR);
193         hdr->expires = ast_tvdiff_ms(contact->expiration_time, ast_tvnow()) / 1000;
194
195         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr);
196
197         return 0;
198 }
199
200 /*! \brief Helper function which adds a Date header to a response */
201 static void registrar_add_date_header(pjsip_tx_data *tdata)
202 {
203         char date[256];
204         struct tm tm;
205         time_t t = time(NULL);
206
207         gmtime_r(&t, &tm);
208         strftime(date, sizeof(date), "%a, %d %b %Y %T GMT", &tm);
209
210         ast_sip_add_header(tdata, "Date", date);
211 }
212
213 #define SERIALIZER_BUCKETS 59
214
215 static struct ao2_container *serializers;
216
217 /*! \brief Serializer with associated aor key */
218 struct serializer {
219         /* Serializer to distribute tasks to */
220         struct ast_taskprocessor *serializer;
221         /* The name of the aor to associate with the serializer */
222         char aor_name[0];
223 };
224
225 static void serializer_destroy(void *obj)
226 {
227         struct serializer *ser = obj;
228
229         ast_taskprocessor_unreference(ser->serializer);
230 }
231
232 static struct serializer *serializer_create(const char *aor_name)
233 {
234         size_t size = strlen(aor_name) + 1;
235         struct serializer *ser = ao2_alloc(
236                 sizeof(*ser) + size, serializer_destroy);
237
238         if (!ser) {
239                 return NULL;
240         }
241
242         if (!(ser->serializer = ast_sip_create_serializer())) {
243                 ao2_ref(ser, -1);
244                 return NULL;
245         }
246
247         strcpy(ser->aor_name, aor_name);
248         return ser;
249 }
250
251 static struct serializer *serializer_find_or_create(const char *aor_name)
252 {
253         struct serializer *ser = ao2_find(serializers, aor_name, OBJ_SEARCH_KEY);
254
255         if (ser) {
256                 return ser;
257         }
258
259         if (!(ser = serializer_create(aor_name))) {
260                 return NULL;
261         }
262
263         ao2_link(serializers, ser);
264         return ser;
265 }
266
267 static int serializer_hash(const void *obj, const int flags)
268 {
269         const struct serializer *object;
270         const char *key;
271
272         switch (flags & OBJ_SEARCH_MASK) {
273         case OBJ_SEARCH_KEY:
274                 key = obj;
275                 return ast_str_hash(key);
276         case OBJ_SEARCH_OBJECT:
277                 object = obj;
278                 return ast_str_hash(object->aor_name);
279         default:
280                 /* Hash can only work on something with a full key. */
281                 ast_assert(0);
282                 return 0;
283         }
284 }
285
286 static int serializer_cmp(void *obj_left, void *obj_right, int flags)
287 {
288         const struct serializer *object_left = obj_left;
289         const struct serializer *object_right = obj_right;
290         const char *right_key = obj_right;
291         int cmp;
292
293         switch (flags & OBJ_SEARCH_MASK) {
294         case OBJ_SEARCH_OBJECT:
295                 right_key = object_right->aor_name;
296                 /* Fall through */
297         case OBJ_SEARCH_KEY:
298                 cmp = strcmp(object_left->aor_name, right_key);
299                 break;
300         case OBJ_SEARCH_PARTIAL_KEY:
301                 /*
302                  * We could also use a partial key struct containing a length
303                  * so strlen() does not get called for every comparison instead.
304                  */
305                 cmp = strncmp(object_left->aor_name, right_key, strlen(right_key));
306                 break;
307         default:
308                 cmp = 0;
309                 break;
310         }
311
312         return cmp ? 0 : CMP_MATCH;
313 }
314
315 struct rx_task_data {
316         pjsip_rx_data *rdata;
317         struct ast_sip_endpoint *endpoint;
318         struct ast_sip_aor *aor;
319 };
320
321 static void rx_task_data_destroy(void *obj)
322 {
323         struct rx_task_data *task_data = obj;
324
325         pjsip_rx_data_free_cloned(task_data->rdata);
326         ao2_cleanup(task_data->endpoint);
327         ao2_cleanup(task_data->aor);
328 }
329
330 static struct rx_task_data *rx_task_data_create(pjsip_rx_data *rdata,
331                                                 struct ast_sip_endpoint *endpoint,
332                                                 struct ast_sip_aor *aor)
333 {
334         struct rx_task_data *task_data = ao2_alloc(
335                 sizeof(*task_data), rx_task_data_destroy);
336
337         if (!task_data) {
338                 return NULL;
339         }
340
341         pjsip_rx_data_clone(rdata, 0, &task_data->rdata);
342
343         task_data->endpoint = endpoint;
344         ao2_ref(task_data->endpoint, +1);
345
346         task_data->aor = aor;
347         ao2_ref(task_data->aor, +1);
348
349         return task_data;
350 }
351
352 static const pj_str_t path_hdr_name = { "Path", 4 };
353
354 static int build_path_data(struct rx_task_data *task_data, struct ast_str **path_str)
355 {
356         pjsip_generic_string_hdr *path_hdr = pjsip_msg_find_hdr_by_name(task_data->rdata->msg_info.msg, &path_hdr_name, NULL);
357
358         if (!path_hdr) {
359                 return 0;
360         }
361
362         *path_str = ast_str_create(64);
363         if (!path_str) {
364                 return -1;
365         }
366
367         ast_str_set(path_str, 0, "%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
368
369         while ((path_hdr = (pjsip_generic_string_hdr *) pjsip_msg_find_hdr_by_name(task_data->rdata->msg_info.msg, &path_hdr_name, path_hdr->next))) {
370                 ast_str_append(path_str, 0, ",%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
371         }
372
373         return 0;
374 }
375
376 static int registrar_validate_path(struct rx_task_data *task_data, struct ast_str **path_str)
377 {
378         const pj_str_t path_supported_name = { "path", 4 };
379         pjsip_supported_hdr *supported_hdr;
380         int i;
381
382         if (!task_data->aor->support_path) {
383                 return 0;
384         }
385
386         if (build_path_data(task_data, path_str)) {
387                 return -1;
388         }
389
390         if (!*path_str) {
391                 return 0;
392         }
393
394         supported_hdr = pjsip_msg_find_hdr(task_data->rdata->msg_info.msg, PJSIP_H_SUPPORTED, NULL);
395         if (!supported_hdr) {
396                 return -1;
397         }
398
399         /* Find advertised path support */
400         for (i = 0; i < supported_hdr->count; i++) {
401                 if (!pj_stricmp(&supported_hdr->values[i], &path_supported_name)) {
402                         return 0;
403                 }
404         }
405
406         /* Path header present, but support not advertised */
407         return -1;
408 }
409
410 static int rx_task(void *data)
411 {
412         static const pj_str_t USER_AGENT = { "User-Agent", 10 };
413
414         RAII_VAR(struct rx_task_data *, task_data, data, ao2_cleanup);
415         RAII_VAR(struct ao2_container *, contacts, NULL, ao2_cleanup);
416
417         int added = 0, updated = 0, deleted = 0;
418         pjsip_contact_hdr *contact_hdr = NULL;
419         struct registrar_contact_details details = { 0, };
420         pjsip_tx_data *tdata;
421         pjsip_response_addr addr;
422         const char *aor_name = ast_sorcery_object_get_id(task_data->aor);
423         RAII_VAR(struct ast_str *, path_str, NULL, ast_free);
424         struct ast_sip_contact *response_contact;
425         char *user_agent = NULL;
426         pjsip_user_agent_hdr *user_agent_hdr;
427
428         /* Retrieve the current contacts, we'll need to know whether to update or not */
429         contacts = ast_sip_location_retrieve_aor_contacts(task_data->aor);
430
431         /* So we don't count static contacts against max_contacts we prune them out from the container */
432         ao2_callback(contacts, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, registrar_prune_static, NULL);
433
434         if (registrar_validate_contacts(task_data->rdata, contacts, task_data->aor, &added, &updated, &deleted)) {
435                 /* The provided Contact headers do not conform to the specification */
436                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), task_data->rdata, 400, NULL, NULL, NULL);
437                 ast_sip_report_failed_acl(task_data->endpoint, task_data->rdata, "registrar_invalid_contacts_provided");
438                 ast_log(LOG_WARNING, "Failed to validate contacts in REGISTER request from '%s'\n",
439                                 ast_sorcery_object_get_id(task_data->endpoint));
440                 return PJ_TRUE;
441         }
442
443         if (registrar_validate_path(task_data, &path_str)) {
444                 /* Ensure that intervening proxies did not make invalid modifications to the request */
445                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), task_data->rdata, 420, NULL, NULL, NULL);
446                 ast_log(LOG_WARNING, "Invalid modifications made to REGISTER request from '%s' by intervening proxy\n",
447                                 ast_sorcery_object_get_id(task_data->endpoint));
448                 return PJ_TRUE;
449         }
450
451         if ((MAX(added - deleted, 0) + (!task_data->aor->remove_existing ? ao2_container_count(contacts) : 0)) > task_data->aor->max_contacts) {
452                 /* Enforce the maximum number of contacts */
453                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), task_data->rdata, 403, NULL, NULL, NULL);
454                 ast_sip_report_failed_acl(task_data->endpoint, task_data->rdata, "registrar_attempt_exceeds_maximum_configured_contacts");
455                 ast_log(LOG_WARNING, "Registration attempt from endpoint '%s' to AOR '%s' will exceed max contacts of %d\n",
456                                 ast_sorcery_object_get_id(task_data->endpoint), ast_sorcery_object_get_id(task_data->aor), task_data->aor->max_contacts);
457                 return PJ_TRUE;
458         }
459
460         if (!(details.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Contact Comparison", 256, 256))) {
461                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), task_data->rdata, 500, NULL, NULL, NULL);
462                 return PJ_TRUE;
463         }
464
465         user_agent_hdr = pjsip_msg_find_hdr_by_name(task_data->rdata->msg_info.msg, &USER_AGENT, NULL);
466         if (user_agent_hdr) {
467                 size_t alloc_size = pj_strlen(&user_agent_hdr->hvalue) + 1;
468                 user_agent = ast_alloca(alloc_size);
469                 ast_copy_pj_str(user_agent, &user_agent_hdr->hvalue, alloc_size);
470         }
471
472         /* Iterate each provided Contact header and add, update, or delete */
473         while ((contact_hdr = pjsip_msg_find_hdr(task_data->rdata->msg_info.msg, PJSIP_H_CONTACT, contact_hdr ? contact_hdr->next : NULL))) {
474                 int expiration;
475                 char contact_uri[PJSIP_MAX_URL_SIZE];
476                 RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
477
478                 if (contact_hdr->star) {
479                         /* A star means to unregister everything, so do so for the possible contacts */
480                         ao2_callback(contacts, OBJ_NODATA | OBJ_MULTIPLE, registrar_delete_contact, (void *)aor_name);
481                         break;
482                 }
483
484                 if (!PJSIP_URI_SCHEME_IS_SIP(contact_hdr->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact_hdr->uri)) {
485                         /* This registrar only currently supports sip: and sips: URI schemes */
486                         continue;
487                 }
488
489                 expiration = registrar_get_expiration(task_data->aor, contact_hdr, task_data->rdata);
490                 details.uri = pjsip_uri_get_uri(contact_hdr->uri);
491                 pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri));
492
493                 if (!(contact = ao2_callback(contacts, OBJ_UNLINK, registrar_find_contact, &details))) {
494                         /* If they are actually trying to delete a contact that does not exist... be forgiving */
495                         if (!expiration) {
496                                 ast_verb(3, "Attempted to remove non-existent contact '%s' from AOR '%s' by request\n",
497                                         contact_uri, aor_name);
498                                 continue;
499                         }
500
501                         if (ast_sip_location_add_contact(task_data->aor, contact_uri, ast_tvadd(ast_tvnow(),
502                                 ast_samp2tv(expiration, 1)), path_str ? ast_str_buffer(path_str) : NULL,
503                                         user_agent)) {
504                                 ast_log(LOG_ERROR, "Unable to bind contact '%s' to AOR '%s'\n",
505                                                 contact_uri, aor_name);
506                                 continue;
507                         }
508
509                         ast_verb(3, "Added contact '%s' to AOR '%s' with expiration of %d seconds\n",
510                                 contact_uri, aor_name, expiration);
511                         ast_test_suite_event_notify("AOR_CONTACT_ADDED",
512                                         "Contact: %s\r\n"
513                                         "AOR: %s\r\n"
514                                         "Expiration: %d\r\n"
515                                         "UserAgent: %s",
516                                         contact_uri,
517                                         aor_name,
518                                         expiration,
519                                         user_agent);
520                 } else if (expiration) {
521                         struct ast_sip_contact *contact_update;
522
523                         contact_update = ast_sorcery_copy(ast_sip_get_sorcery(), contact);
524                         if (!contact_update) {
525                                 ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
526                                         contact->uri, expiration);
527                                 continue;
528                         }
529
530                         contact_update->expiration_time = ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1));
531                         contact_update->qualify_frequency = task_data->aor->qualify_frequency;
532                         contact_update->authenticate_qualify = task_data->aor->authenticate_qualify;
533                         if (path_str) {
534                                 ast_string_field_set(contact_update, path, ast_str_buffer(path_str));
535                         }
536                         if (user_agent) {
537                                 ast_string_field_set(contact_update, user_agent, user_agent);
538                         }
539
540                         ast_sip_location_update_contact(contact_update);
541                         ast_debug(3, "Refreshed contact '%s' on AOR '%s' with new expiration of %d seconds\n",
542                                 contact_uri, aor_name, expiration);
543                         ast_test_suite_event_notify("AOR_CONTACT_REFRESHED",
544                                         "Contact: %s\r\n"
545                                         "AOR: %s\r\n"
546                                         "Expiration: %d\r\n"
547                                         "UserAgent: %s",
548                                         contact_uri,
549                                         aor_name,
550                                         expiration,
551                                         contact_update->user_agent);
552                         ao2_cleanup(contact_update);
553                 } else {
554                         /* We want to report the user agent that was actually in the removed contact */
555                         user_agent = ast_strdupa(contact->user_agent);
556                         ast_sip_location_delete_contact(contact);
557                         ast_verb(3, "Removed contact '%s' from AOR '%s' due to request\n", contact_uri, aor_name);
558                         ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
559                                         "Contact: %s\r\n"
560                                         "AOR: %s\r\n"
561                                         "UserAgent: %s",
562                                         contact_uri,
563                                         aor_name,
564                                         user_agent);
565                 }
566         }
567
568         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
569
570         /* If the AOR is configured to remove any existing contacts that have not been updated/added as a result of this REGISTER
571          * do so
572          */
573         if (task_data->aor->remove_existing) {
574                 ao2_callback(contacts, OBJ_NODATA | OBJ_MULTIPLE, registrar_delete_contact, NULL);
575         }
576
577         /* Update the contacts as things will probably have changed */
578         ao2_cleanup(contacts);
579
580         contacts = ast_sip_location_retrieve_aor_contacts(task_data->aor);
581         response_contact = ao2_callback(contacts, 0, NULL, NULL);
582
583         /* Send a response containing all of the contacts (including static) that are present on this AOR */
584         if (ast_sip_create_response(task_data->rdata, 200, response_contact, &tdata) != PJ_SUCCESS) {
585                 ao2_cleanup(response_contact);
586                 return PJ_TRUE;
587         }
588         ao2_cleanup(response_contact);
589
590         /* Add the date header to the response, some UAs use this to set their date and time */
591         registrar_add_date_header(tdata);
592
593         ao2_callback(contacts, 0, registrar_add_contact, tdata);
594
595         if (pjsip_get_response_addr(tdata->pool, task_data->rdata, &addr) == PJ_SUCCESS) {
596                 ast_sip_send_response(&addr, tdata, task_data->endpoint);
597         } else {
598                 pjsip_tx_data_dec_ref(tdata);
599         }
600
601         return PJ_TRUE;
602 }
603
604 static pj_bool_t registrar_on_rx_request(struct pjsip_rx_data *rdata)
605 {
606         RAII_VAR(struct serializer *, ser, NULL, ao2_cleanup);
607         struct rx_task_data *task_data;
608
609         RAII_VAR(struct ast_sip_endpoint *, endpoint,
610                  ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
611         RAII_VAR(struct ast_sip_aor *, aor, NULL, ao2_cleanup);
612         pjsip_sip_uri *uri;
613         char *domain_name;
614         char *configured_aors, *aor_name;
615         RAII_VAR(struct ast_str *, id, NULL, ast_free);
616
617         if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method) || !endpoint) {
618                 return PJ_FALSE;
619         }
620
621         if (ast_strlen_zero(endpoint->aors)) {
622                 /* Short circuit early if the endpoint has no AORs configured on it, which means no registration possible */
623                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
624                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_without_configured_aors");
625                 ast_log(LOG_WARNING, "Endpoint '%s' has no configured AORs\n", ast_sorcery_object_get_id(endpoint));
626                 return PJ_TRUE;
627         }
628
629         if (!PJSIP_URI_SCHEME_IS_SIP(rdata->msg_info.to->uri) && !PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.to->uri)) {
630                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
631                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_uri_in_to_received");
632                 ast_log(LOG_WARNING, "Endpoint '%s' attempted to register to an AOR with a non-SIP URI\n", ast_sorcery_object_get_id(endpoint));
633                 return PJ_TRUE;
634         }
635
636         uri = pjsip_uri_get_uri(rdata->msg_info.to->uri);
637         domain_name = ast_alloca(uri->host.slen + 1);
638         ast_copy_pj_str(domain_name, &uri->host, uri->host.slen + 1);
639
640         configured_aors = ast_strdupa(endpoint->aors);
641
642         /* Iterate the configured AORs to see if the user or the user+domain match */
643         while ((aor_name = strsep(&configured_aors, ","))) {
644                 struct ast_sip_domain_alias *alias = NULL;
645
646                 if (!pj_strcmp2(&uri->user, aor_name)) {
647                         break;
648                 }
649
650                 if (!id && !(id = ast_str_create(uri->user.slen + uri->host.slen + 2))) {
651                         return PJ_TRUE;
652                 }
653
654                 ast_str_set(&id, 0, "%.*s@", (int)uri->user.slen, uri->user.ptr);
655                 if ((alias = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "domain_alias", domain_name))) {
656                         ast_str_append(&id, 0, "%s", alias->domain);
657                         ao2_cleanup(alias);
658                 } else {
659                         ast_str_append(&id, 0, "%s", domain_name);
660                 }
661
662                 if (!strcmp(aor_name, ast_str_buffer(id))) {
663                         ast_free(id);
664                         break;
665                 }
666         }
667
668         if (ast_strlen_zero(aor_name) || !(aor = ast_sip_location_retrieve_aor(aor_name))) {
669                 /* The provided AOR name was not found (be it within the configuration or sorcery itself) */
670                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
671                 ast_sip_report_req_no_support(endpoint, rdata, "registrar_requested_aor_not_found");
672                 ast_log(LOG_WARNING, "AOR '%.*s' not found for endpoint '%s'\n", (int)uri->user.slen, uri->user.ptr, ast_sorcery_object_get_id(endpoint));
673                 return PJ_TRUE;
674         }
675
676         if (!aor->max_contacts) {
677                 /* Registration is not permitted for this AOR */
678                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
679                 ast_sip_report_req_no_support(endpoint, rdata, "registrar_attempt_without_registration_permitted");
680                 ast_log(LOG_WARNING, "AOR '%s' has no configured max_contacts. Endpoint '%s' unable to register\n",
681                                 ast_sorcery_object_get_id(aor), ast_sorcery_object_get_id(endpoint));
682                 return PJ_TRUE;
683         }
684
685         if (!(ser = serializer_find_or_create(aor_name))) {
686                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
687                 ast_sip_report_mem_limit(endpoint, rdata);
688                 ast_log(LOG_WARNING, "Endpoint '%s' unable to register on AOR '%s' - could not get serializer\n",
689                         ast_sorcery_object_get_id(endpoint), ast_sorcery_object_get_id(aor));
690                 return PJ_TRUE;
691         }
692
693         if (!(task_data = rx_task_data_create(rdata, endpoint, aor))) {
694                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
695                 ast_sip_report_mem_limit(endpoint, rdata);
696                 ast_log(LOG_WARNING, "Endpoint '%s' unable to register on AOR '%s' - could not create rx_task_data\n",
697                         ast_sorcery_object_get_id(endpoint), ast_sorcery_object_get_id(aor));
698                 return PJ_TRUE;
699         }
700
701         if (ast_sip_push_task(ser->serializer, rx_task, task_data)) {
702                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
703                 ast_sip_report_mem_limit(endpoint, rdata);
704                 ast_log(LOG_WARNING, "Endpoint '%s' unable to register on AOR '%s' - could not serialize task\n",
705                         ast_sorcery_object_get_id(endpoint), ast_sorcery_object_get_id(aor));
706                 ao2_ref(task_data, -1);
707         }
708         return PJ_TRUE;
709 }
710
711 /* function pointer to callback needs to be within the module
712    in order to avoid problems with an undefined symbol */
713 static int sip_contact_to_str(void *acp, void *arg, int flags)
714 {
715         return ast_sip_contact_to_str(acp, arg, flags);
716 }
717
718 static int ami_registrations_aor(void *obj, void *arg, int flags)
719 {
720         struct ast_sip_aor *aor = obj;
721         struct ast_sip_ami *ami = arg;
722         int *count = ami->arg;
723         RAII_VAR(struct ast_str *, buf,
724                  ast_sip_create_ami_event("InboundRegistrationDetail", ami), ast_free);
725
726         if (!buf) {
727                 return -1;
728         }
729
730         ast_sip_sorcery_object_to_ami(aor, &buf);
731         ast_str_append(&buf, 0, "Contacts: ");
732         ast_sip_for_each_contact(aor, sip_contact_to_str, &buf);
733         ast_str_append(&buf, 0, "\r\n");
734
735         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
736         (*count)++;
737         return 0;
738 }
739
740 static int ami_registrations_endpoint(void *obj, void *arg, int flags)
741 {
742         struct ast_sip_endpoint *endpoint = obj;
743         return ast_sip_for_each_aor(
744                 endpoint->aors, ami_registrations_aor, arg);
745 }
746
747 static int ami_registrations_endpoints(void *arg)
748 {
749         RAII_VAR(struct ao2_container *, endpoints,
750                  ast_sip_get_endpoints(), ao2_cleanup);
751
752         if (!endpoints) {
753                 return 0;
754         }
755
756         ao2_callback(endpoints, OBJ_NODATA, ami_registrations_endpoint, arg);
757         return 0;
758 }
759
760 static int ami_show_registrations(struct mansession *s, const struct message *m)
761 {
762         int count = 0;
763         struct ast_sip_ami ami = { .s = s, .m = m, .arg = &count };
764         astman_send_listack(s, m, "Following are Events for each Inbound "
765                             "registration", "start");
766
767         ami_registrations_endpoints(&ami);
768
769         astman_append(s,
770                       "Event: InboundRegistrationDetailComplete\r\n"
771                       "EventList: Complete\r\n"
772                       "ListItems: %d\r\n\r\n", count);
773         return 0;
774 }
775
776 #define AMI_SHOW_REGISTRATIONS "PJSIPShowRegistrationsInbound"
777
778 static pjsip_module registrar_module = {
779         .name = { "Registrar", 9 },
780         .id = -1,
781         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
782         .on_rx_request = registrar_on_rx_request,
783 };
784
785 static int load_module(void)
786 {
787         const pj_str_t STR_REGISTER = { "REGISTER", 8 };
788
789         if (!(serializers = ao2_container_alloc(
790                       SERIALIZER_BUCKETS, serializer_hash, serializer_cmp))) {
791                 return AST_MODULE_LOAD_DECLINE;
792         }
793
794         if (ast_sip_register_service(&registrar_module)) {
795                 return AST_MODULE_LOAD_DECLINE;
796         }
797
798         if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW, NULL, 1, &STR_REGISTER) != PJ_SUCCESS) {
799                 ast_sip_unregister_service(&registrar_module);
800                 return AST_MODULE_LOAD_DECLINE;
801         }
802
803         ast_manager_register_xml(AMI_SHOW_REGISTRATIONS, EVENT_FLAG_SYSTEM,
804                                  ami_show_registrations);
805
806         return AST_MODULE_LOAD_SUCCESS;
807 }
808
809 static int unload_module(void)
810 {
811         ast_manager_unregister(AMI_SHOW_REGISTRATIONS);
812         ast_sip_unregister_service(&registrar_module);
813
814         ao2_cleanup(serializers);
815         return 0;
816 }
817
818 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Registrar Support",
819                 .load = load_module,
820                 .unload = unload_module,
821                 .load_pri = AST_MODPRI_APP_DEPEND,
822                );