stasis: Improve topic/subscription names and statistics.
[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_pjproject</depend>
22         <depend>res_pjsip</depend>
23         <support_level>core</support_level>
24  ***/
25
26 #include "asterisk.h"
27
28 #include <signal.h>
29 #include <pjsip.h>
30 #include <pjsip_ua.h>
31
32 #include "asterisk/res_pjsip.h"
33 #include "asterisk/module.h"
34 #include "asterisk/paths.h"
35 #include "asterisk/test.h"
36 #include "asterisk/taskprocessor.h"
37 #include "asterisk/manager.h"
38 #include "asterisk/named_locks.h"
39 #include "asterisk/res_pjproject.h"
40 #include "res_pjsip/include/res_pjsip_private.h"
41
42 /*** DOCUMENTATION
43         <manager name="PJSIPShowRegistrationsInbound" language="en_US">
44                 <synopsis>
45                         Lists PJSIP inbound registrations.
46                 </synopsis>
47                 <syntax />
48                 <description>
49                         <para>
50                         In response, <literal>InboundRegistrationDetail</literal> events showing configuration
51                         and status information are raised for all contacts, static or dynamic.  Once all events
52                         are completed an <literal>InboundRegistrationDetailComplete</literal> is issued.
53                         </para>
54                         <warning><para>
55                                 This command just dumps all coonfigured AORs with contacts, even if the contact
56                                 is a permanent one.  To really get just inbound registrations, use
57                                 <literal>PJSIPShowRegistrationInboundContactStatuses</literal>.
58                         </para>
59                         </warning>
60                 </description>
61                 <see-also>
62                         <ref type="manager" module="res_pjsip_registrar">PJSIPShowRegistrationInboundContactStatuses</ref>
63                 </see-also>
64         </manager>
65         <manager name="PJSIPShowRegistrationInboundContactStatuses" language="en_US">
66                 <synopsis>
67                         Lists ContactStatuses for PJSIP inbound registrations.
68                 </synopsis>
69                 <syntax />
70                 <description>
71                         <para>
72                         In response, <literal>ContactStatusDetail</literal> events showing status information
73                         are raised for each inbound registration (dynamic contact) object.  Once all events
74                         are completed a <literal>ContactStatusDetailComplete</literal> event is issued.
75                         </para>
76                 </description>
77         </manager>
78  ***/
79
80 static int pj_max_hostname = PJ_MAX_HOSTNAME;
81 static int pjsip_max_url_size = PJSIP_MAX_URL_SIZE;
82
83 /*! \brief Internal function which returns the expiration time for a contact */
84 static int registrar_get_expiration(const struct ast_sip_aor *aor, const pjsip_contact_hdr *contact, const pjsip_rx_data *rdata)
85 {
86         pjsip_expires_hdr *expires;
87         int expiration = aor->default_expiration;
88
89         if (contact && contact->expires != -1) {
90                 /* Expiration was provided with the contact itself */
91                 expiration = contact->expires;
92         } else if ((expires = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
93                 /* Expiration was provided using the Expires header */
94                 expiration = expires->ivalue;
95         }
96
97         /* If the value has explicitly been set to 0, do not enforce */
98         if (!expiration) {
99                 return expiration;
100         }
101
102         /* Enforce the range that we will allow for expiration */
103         if (expiration < aor->minimum_expiration) {
104                 expiration = aor->minimum_expiration;
105         } else if (expiration > aor->maximum_expiration) {
106                 expiration = aor->maximum_expiration;
107         }
108
109         return expiration;
110 }
111
112 /*! \brief Structure used for finding contact */
113 struct registrar_contact_details {
114         /*! \brief Pool used for parsing URI */
115         pj_pool_t *pool;
116         /*! \brief URI being looked for */
117         pjsip_sip_uri *uri;
118 };
119
120 /*! \brief Callback function for finding a contact */
121 static int registrar_find_contact(void *obj, void *arg, int flags)
122 {
123         struct ast_sip_contact *contact = obj;
124         const struct registrar_contact_details *details = arg;
125         pjsip_uri *contact_uri;
126
127         if (ast_tvzero(contact->expiration_time)) {
128                 return 0;
129         }
130
131         contact_uri = pjsip_parse_uri(details->pool, (char*)contact->uri, strlen(contact->uri), 0);
132
133         return (pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, details->uri, contact_uri) == PJ_SUCCESS) ? CMP_MATCH : 0;
134 }
135
136 /*! \brief Internal function which validates provided Contact headers to confirm that they are acceptable, and returns number of contacts */
137 static int registrar_validate_contacts(const pjsip_rx_data *rdata, pj_pool_t *pool, struct ao2_container *contacts,
138         struct ast_sip_aor *aor, int permanent, int *added, int *updated, int *deleted)
139 {
140         pjsip_contact_hdr *previous = NULL;
141         pjsip_contact_hdr *contact = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
142         struct registrar_contact_details details = {
143                 .pool = pool,
144         };
145
146         for (; (contact = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact->next)); pj_pool_reset(pool)) {
147                 int expiration = registrar_get_expiration(aor, contact, rdata);
148                 struct ast_sip_contact *existing;
149                 char contact_uri[pjsip_max_url_size];
150
151                 if (contact->star) {
152                         /* The expiration MUST be 0 when a '*' contact is used and there must be no other contact */
153                         if (expiration != 0 || previous) {
154                                 return -1;
155                         }
156                         /* Count all contacts to delete */
157                         *deleted = ao2_container_count(contacts) - permanent;
158                         previous = contact;
159                         continue;
160                 } else if (previous && previous->star) {
161                         /* If there is a previous contact and it is a '*' this is a deal breaker */
162                         return -1;
163                 }
164                 previous = contact;
165
166                 if (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
167                         continue;
168                 }
169
170                 details.uri = pjsip_uri_get_uri(contact->uri);
171
172                 /* pjsip_uri_print returns -1 if there's not enough room in the buffer */
173                 if (pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri)) < 0) {
174                         /* If the total length of the uri is greater than pjproject can handle, go no further */
175                         return -1;
176                 }
177
178                 if (details.uri->host.slen >= pj_max_hostname) {
179                         /* If the length of the hostname is greater than pjproject can handle, go no further */
180                         return -1;
181                 }
182
183                 /* Determine if this is an add, update, or delete for policy enforcement purposes */
184                 existing = ao2_callback(contacts, 0, registrar_find_contact, &details);
185                 ao2_cleanup(existing);
186                 if (!existing) {
187                         if (expiration) {
188                                 ++*added;
189                         }
190                 } else if (expiration) {
191                         ++*updated;
192                 } else {
193                         ++*deleted;
194                 }
195         }
196
197         return 0;
198 }
199
200 enum contact_delete_type {
201         CONTACT_DELETE_ERROR,
202         CONTACT_DELETE_EXISTING,
203         CONTACT_DELETE_EXPIRE,
204         CONTACT_DELETE_REQUEST,
205         CONTACT_DELETE_SHUTDOWN,
206 };
207
208 static int registrar_contact_delete(enum contact_delete_type type, pjsip_transport *transport,
209         struct ast_sip_contact *contact, const char *aor_name);
210
211 /*! \brief Internal function used to delete a contact from an AOR */
212 static int registrar_delete_contact(void *obj, void *arg, int flags)
213 {
214         return registrar_contact_delete(
215                 CONTACT_DELETE_REQUEST, NULL, obj, arg) ? 0 : CMP_MATCH;
216 }
217
218 /*! \brief Internal function which adds a contact to a response */
219 static int registrar_add_contact(void *obj, void *arg, int flags)
220 {
221         struct ast_sip_contact *contact = obj;
222         pjsip_tx_data *tdata = arg;
223         pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(tdata->pool);
224         pj_str_t uri;
225
226         pj_strdup2_with_null(tdata->pool, &uri, contact->uri);
227         hdr->uri = pjsip_parse_uri(tdata->pool, uri.ptr, uri.slen, PJSIP_PARSE_URI_AS_NAMEADDR);
228         hdr->expires = ast_tvdiff_ms(contact->expiration_time, ast_tvnow()) / 1000;
229
230         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr);
231
232         return 0;
233 }
234
235 /*! \brief Helper function which adds a Date header to a response */
236 static void registrar_add_date_header(pjsip_tx_data *tdata)
237 {
238         char date[256];
239         struct tm tm;
240         time_t t = time(NULL);
241
242         gmtime_r(&t, &tm);
243         strftime(date, sizeof(date), "%a, %d %b %Y %T GMT", &tm);
244
245         ast_sip_add_header(tdata, "Date", date);
246 }
247
248 static const pj_str_t path_hdr_name = { "Path", 4 };
249
250 static int build_path_data(pjsip_rx_data *rdata, struct ast_str **path_str)
251 {
252         pjsip_generic_string_hdr *path_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &path_hdr_name, NULL);
253
254         if (!path_hdr) {
255                 return 0;
256         }
257
258         *path_str = ast_str_create(64);
259         if (!*path_str) {
260                 return -1;
261         }
262
263         ast_str_set(path_str, 0, "%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
264
265         while ((path_hdr = (pjsip_generic_string_hdr *) pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &path_hdr_name, path_hdr->next))) {
266                 ast_str_append(path_str, 0, ",%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
267         }
268
269         return 0;
270 }
271
272 static int registrar_validate_path(pjsip_rx_data *rdata, struct ast_sip_aor *aor, struct ast_str **path_str)
273 {
274         const pj_str_t path_supported_name = { "path", 4 };
275         pjsip_supported_hdr *supported_hdr;
276         int i;
277
278         if (!aor->support_path) {
279                 return 0;
280         }
281
282         if (build_path_data(rdata, path_str)) {
283                 return -1;
284         }
285
286         if (!*path_str) {
287                 return 0;
288         }
289
290         supported_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_SUPPORTED, NULL);
291         if (!supported_hdr) {
292                 return -1;
293         }
294
295         /* Find advertised path support */
296         for (i = 0; i < supported_hdr->count; i++) {
297                 if (!pj_stricmp(&supported_hdr->values[i], &path_supported_name)) {
298                         return 0;
299                 }
300         }
301
302         /* Path header present, but support not advertised */
303         return -1;
304 }
305
306 /*! Transport monitor for incoming REGISTER contacts */
307 struct contact_transport_monitor {
308         /*!
309          * \brief Sorcery contact name to remove on transport shutdown
310          * \note Stored after aor_name in space reserved when struct allocated.
311          */
312         char *contact_name;
313         /*! Indicates that the monitor is in the process of removing a contact */
314         int removing;
315         /*! AOR name the contact is associated */
316         char aor_name[0];
317 };
318
319 static int contact_transport_monitor_matcher(void *a, void *b)
320 {
321         struct contact_transport_monitor *ma = a;
322         struct contact_transport_monitor *mb = b;
323
324         return strcmp(ma->aor_name, mb->aor_name) == 0
325                 && strcmp(ma->contact_name, mb->contact_name) == 0;
326 }
327
328 static int register_contact_transport_remove_cb(void *data)
329 {
330         struct contact_transport_monitor *monitor = data;
331         struct ast_sip_contact *contact;
332         struct ast_sip_aor *aor;
333
334         aor = ast_sip_location_retrieve_aor(monitor->aor_name);
335         if (!aor) {
336                 ao2_lock(monitor);
337                 monitor->removing = 0;
338                 ao2_unlock(monitor);
339                 ao2_ref(monitor, -1);
340                 return 0;
341         }
342
343         ao2_lock(aor);
344
345         contact = ast_sip_location_retrieve_contact(monitor->contact_name);
346         if (contact) {
347                 registrar_contact_delete(CONTACT_DELETE_SHUTDOWN, NULL, contact, monitor->aor_name);
348                 ao2_ref(contact, -1);
349         }
350         ao2_unlock(aor);
351         ao2_ref(aor, -1);
352
353         ao2_ref(monitor, -1);
354         return 0;
355 }
356
357 /*!
358  * \internal
359  * \brief The reliable transport we registered as a contact has shutdown.
360  *
361  * \param data What contact needs to be removed.
362  *
363  * \note Normally executed by the pjsip monitor thread.
364  *
365  * \return Nothing
366  */
367 static void register_contact_transport_shutdown_cb(void *data)
368 {
369         struct contact_transport_monitor *monitor = data;
370
371         /*
372          * It's possible for this shutdown handler to get called multiple times for the
373          * same monitor from different threads. Only one of the calls needs to do the
374          * actual removing of the contact, so if one is currently removing then any
375          * subsequent calls can skip.
376          */
377         ao2_lock(monitor);
378         if (monitor->removing) {
379                 ao2_unlock(monitor);
380                 return;
381         }
382
383         monitor->removing = 1;
384
385         /*
386          * Push off to a default serializer.  This is in case sorcery
387          * does database accesses for contacts.  Database accesses may
388          * not be on this machine.  We don't want to tie up the pjsip
389          * monitor thread with potentially long access times.
390          */
391         ao2_ref(monitor, +1);
392         if (ast_sip_push_task(NULL, register_contact_transport_remove_cb, monitor)) {
393                 monitor->removing = 0;
394                 ao2_ref(monitor, -1);
395         }
396
397         ao2_unlock(monitor);
398 }
399
400
401 static int registrar_contact_delete(enum contact_delete_type type, pjsip_transport *transport,
402         struct ast_sip_contact *contact, const char *aor_name)
403 {
404         int aor_size;
405
406         /* Permanent contacts can't be deleted */
407         if (ast_tvzero(contact->expiration_time)) {
408                 return -1;
409         }
410
411         aor_size = aor_name ? strlen(aor_name) : 0;
412         if (contact->prune_on_boot && type != CONTACT_DELETE_SHUTDOWN && aor_size) {
413                 const char *contact_name = ast_sorcery_object_get_id(contact);
414                 struct contact_transport_monitor *monitor = ast_alloca(
415                         sizeof(*monitor) + 2 + aor_size + strlen(contact_name));
416
417                 strcpy(monitor->aor_name, aor_name); /* Safe */
418                 monitor->contact_name = monitor->aor_name + aor_size + 1;
419                 strcpy(monitor->contact_name, contact_name); /* Safe */
420
421                 if (transport) {
422                         ast_sip_transport_monitor_unregister(transport,
423                                 register_contact_transport_shutdown_cb, monitor,
424                                 contact_transport_monitor_matcher);
425                 } else {
426                         /*
427                          * If a specific transport is not supplied then unregister the matching
428                          * monitor from all reliable transports.
429                          */
430                         ast_sip_transport_monitor_unregister_all(register_contact_transport_shutdown_cb,
431                                 monitor, contact_transport_monitor_matcher);
432                 }
433         }
434
435         ast_sip_location_delete_contact(contact);
436
437         if (aor_size) {
438                 if (VERBOSITY_ATLEAST(3)) {
439                         const char *reason = "none";
440
441                         switch (type) {
442                         case CONTACT_DELETE_ERROR:
443                                 reason = "registration failure";
444                                 break;
445                         case CONTACT_DELETE_EXISTING:
446                                 reason = "remove existing";
447                                 break;
448                         case CONTACT_DELETE_EXPIRE:
449                                 reason = "expiration";
450                                 break;
451                         case CONTACT_DELETE_REQUEST:
452                                 reason = "request";
453                                 break;
454                         case CONTACT_DELETE_SHUTDOWN:
455                                 reason = "shutdown";
456                                 break;
457                         }
458
459                         ast_verb(3, "Removed contact '%s' from AOR '%s' due to %s\n",
460                                          contact->uri, aor_name, reason);
461                 }
462
463                 ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
464                                 "Contact: %s\r\n"
465                                 "AOR: %s\r\n"
466                                 "UserAgent: %s",
467                                 contact->uri,
468                                 aor_name,
469                                 contact->user_agent);
470         }
471
472         return 0;
473 }
474
475 AST_VECTOR(excess_contact_vector, struct ast_sip_contact *);
476
477 static int vec_contact_cmp(struct ast_sip_contact *left, struct ast_sip_contact *right)
478 {
479         struct ast_sip_contact *left_contact = left;
480         struct ast_sip_contact *right_contact = right;
481
482         /* Sort from soonest to expire to last to expire */
483         return ast_tvcmp(left_contact->expiration_time, right_contact->expiration_time);
484 }
485
486 static int vec_contact_add(void *obj, void *arg, int flags)
487 {
488         struct ast_sip_contact *contact = obj;
489         struct excess_contact_vector *contact_vec = arg;
490
491         /*
492          * Performance wise, an insertion sort is fine because we
493          * shouldn't need to remove more than a handful of contacts.
494          * I expect we'll typically be removing only one contact.
495          */
496         AST_VECTOR_ADD_SORTED(contact_vec, contact, vec_contact_cmp);
497         if (AST_VECTOR_SIZE(contact_vec) == AST_VECTOR_MAX_SIZE(contact_vec)) {
498                 /*
499                  * We added a contact over the number we need to remove.
500                  * Remove the longest to expire contact from the vector
501                  * which is the last element in the vector.  It may be
502                  * the one we just added or the one we just added pushed
503                  * out an earlier contact from removal consideration.
504                  */
505                 --AST_VECTOR_SIZE(contact_vec);
506         }
507         return 0;
508 }
509
510 /*!
511  * \internal
512  * \brief Remove excess existing contacts that expire the soonest.
513  * \since 13.18.0
514  *
515  * \param contacts Container of unmodified contacts that could remove.
516  * \param to_remove Maximum number of contacts to remove.
517  *
518  * \return Nothing
519  */
520 static void remove_excess_contacts(struct ao2_container *contacts, struct ao2_container *response_contacts,
521         unsigned int to_remove)
522 {
523         struct excess_contact_vector contact_vec;
524
525         /*
526          * Create a sorted vector to hold the to_remove soonest to
527          * expire contacts.  The vector has an extra space to
528          * temporarily hold the longest to expire contact that we
529          * won't remove.
530          */
531         if (AST_VECTOR_INIT(&contact_vec, to_remove + 1)) {
532                 return;
533         }
534         ao2_callback(contacts, OBJ_NODATA | OBJ_MULTIPLE, vec_contact_add, &contact_vec);
535
536         /*
537          * The vector should always be populated with the number
538          * of contacts we need to remove.  Just in case, we will
539          * remove all contacts in the vector even if the contacts
540          * container had fewer contacts than there should be.
541          */
542         ast_assert(AST_VECTOR_SIZE(&contact_vec) == to_remove);
543         to_remove = AST_VECTOR_SIZE(&contact_vec);
544
545         /* Remove the excess contacts that expire the soonest */
546         while (to_remove--) {
547                 struct ast_sip_contact *contact;
548
549                 contact = AST_VECTOR_GET(&contact_vec, to_remove);
550
551                 registrar_contact_delete(CONTACT_DELETE_EXISTING, NULL, contact, contact->aor);
552
553                 ao2_unlink(response_contacts, contact);
554         }
555
556         AST_VECTOR_FREE(&contact_vec);
557 }
558
559 /*! \brief Callback function which adds non-permanent contacts to a container */
560 static int registrar_add_non_permanent(void *obj, void *arg, int flags)
561 {
562         struct ast_sip_contact *contact = obj;
563         struct ao2_container *container = arg;
564
565         if (ast_tvzero(contact->expiration_time)) {
566                 return 0;
567         }
568
569         ao2_link(container, contact);
570
571         return 0;
572 }
573
574 struct aor_core_response {
575         /*! Tx data to use for statefull response.  NULL for stateless response. */
576         pjsip_tx_data *tdata;
577         /*! SIP response code to send in stateless response */
578         int code;
579 };
580
581 static void register_aor_core(pjsip_rx_data *rdata,
582         struct ast_sip_endpoint *endpoint,
583         struct ast_sip_aor *aor,
584         const char *aor_name,
585         struct ao2_container *contacts,
586         struct aor_core_response *response)
587 {
588         static const pj_str_t USER_AGENT = { "User-Agent", 10 };
589
590         int added = 0;
591         int updated = 0;
592         int deleted = 0;
593         int permanent = 0;
594         int contact_count;
595         struct ao2_container *existing_contacts = NULL;
596         pjsip_contact_hdr *contact_hdr = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
597         struct registrar_contact_details details = { 0, };
598         pjsip_tx_data *tdata;
599         RAII_VAR(struct ast_str *, path_str, NULL, ast_free);
600         struct ast_sip_contact *response_contact;
601         char *user_agent = NULL;
602         pjsip_user_agent_hdr *user_agent_hdr;
603         pjsip_expires_hdr *expires_hdr;
604         pjsip_via_hdr *via_hdr;
605         pjsip_via_hdr *via_hdr_last;
606         char *via_addr = NULL;
607         int via_port = 0;
608         pjsip_cid_hdr *call_id_hdr;
609         char *call_id = NULL;
610         size_t alloc_size;
611
612         /* We create a single pool and use it throughout this function where we need one */
613         details.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(),
614                 "Contact Comparison", 1024, 256);
615         if (!details.pool) {
616                 response->code = 500;
617                 return;
618         }
619
620         /* If there are any permanent contacts configured on the AOR we need to take them
621          * into account when counting contacts.
622          */
623         if (aor->permanent_contacts) {
624                 permanent = ao2_container_count(aor->permanent_contacts);
625         }
626
627         if (registrar_validate_contacts(rdata, details.pool, contacts, aor, permanent, &added, &updated, &deleted)) {
628                 /* The provided Contact headers do not conform to the specification */
629                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_contacts_provided");
630                 ast_log(LOG_WARNING, "Failed to validate contacts in REGISTER request from '%s'\n",
631                                 ast_sorcery_object_get_id(endpoint));
632                 response->code = 400;
633                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
634                 return;
635         }
636
637         if (registrar_validate_path(rdata, aor, &path_str)) {
638                 /* Ensure that intervening proxies did not make invalid modifications to the request */
639                 ast_log(LOG_WARNING, "Invalid modifications made to REGISTER request from '%s' by intervening proxy\n",
640                                 ast_sorcery_object_get_id(endpoint));
641                 response->code = 420;
642                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
643                 return;
644         }
645
646         if (aor->remove_existing) {
647                 /* Cumulative number of contacts affected by this registration */
648                 contact_count = MAX(updated + added - deleted,  0);
649
650                 /* We need to keep track of only existing contacts so we can later
651                  * remove them if need be.
652                  */
653                 existing_contacts = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
654                         NULL, ast_sorcery_object_id_compare);
655                 if (!existing_contacts) {
656                         response->code = 500;
657                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
658                         return;
659                 }
660
661                 ao2_callback(contacts, OBJ_NODATA, registrar_add_non_permanent, existing_contacts);
662         } else {
663                 /* Total contacts after this registration */
664                 contact_count = ao2_container_count(contacts) - permanent + added - deleted;
665         }
666         if (contact_count > aor->max_contacts) {
667                 /* Enforce the maximum number of contacts */
668                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_exceeds_maximum_configured_contacts");
669                 ast_log(LOG_WARNING, "Registration attempt from endpoint '%s' to AOR '%s' will exceed max contacts of %u\n",
670                                 ast_sorcery_object_get_id(endpoint), aor_name, aor->max_contacts);
671                 response->code = 403;
672                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
673                 ao2_cleanup(existing_contacts);
674                 return;
675         }
676
677         user_agent_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &USER_AGENT, NULL);
678         if (user_agent_hdr) {
679                 alloc_size = pj_strlen(&user_agent_hdr->hvalue) + 1;
680                 user_agent = ast_alloca(alloc_size);
681                 ast_copy_pj_str(user_agent, &user_agent_hdr->hvalue, alloc_size);
682         }
683
684         /* Find the first Via header */
685         via_hdr = via_hdr_last = (pjsip_via_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_VIA, NULL);
686         if (via_hdr) {
687                 /* Find the last Via header */
688                 while ( (via_hdr = (pjsip_via_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg,
689                                 PJSIP_H_VIA, via_hdr->next)) != NULL) {
690                         via_hdr_last = via_hdr;
691                 }
692                 alloc_size = pj_strlen(&via_hdr_last->sent_by.host) + 1;
693                 via_addr = ast_alloca(alloc_size);
694                 ast_copy_pj_str(via_addr, &via_hdr_last->sent_by.host, alloc_size);
695                 via_port=via_hdr_last->sent_by.port;
696         }
697
698         call_id_hdr = (pjsip_cid_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CALL_ID, NULL);
699         if (call_id_hdr) {
700                 alloc_size = pj_strlen(&call_id_hdr->id) + 1;
701                 call_id = ast_alloca(alloc_size);
702                 ast_copy_pj_str(call_id, &call_id_hdr->id, alloc_size);
703         }
704
705         /* Iterate each provided Contact header and add, update, or delete */
706         for (; (contact_hdr = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact_hdr->next)); pj_pool_reset(details.pool)) {
707                 int expiration;
708                 char contact_uri[pjsip_max_url_size];
709                 RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
710
711                 if (contact_hdr->star) {
712                         /* A star means to unregister everything, so do so for the possible contacts */
713                         ao2_callback(contacts, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
714                                 registrar_delete_contact, (void *)aor_name);
715                         /* If we are keeping track of existing contacts for removal then, well, there is
716                          * absolutely nothing left so no need to try to remove any.
717                          */
718                         if (existing_contacts) {
719                                 ao2_ref(existing_contacts, -1);
720                                 existing_contacts = NULL;
721                         }
722                         break;
723                 }
724
725                 if (!PJSIP_URI_SCHEME_IS_SIP(contact_hdr->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact_hdr->uri)) {
726                         /* This registrar only currently supports sip: and sips: URI schemes */
727                         continue;
728                 }
729
730                 expiration = registrar_get_expiration(aor, contact_hdr, rdata);
731                 details.uri = pjsip_uri_get_uri(contact_hdr->uri);
732                 pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri));
733
734                 contact = ao2_callback(contacts, OBJ_UNLINK, registrar_find_contact, &details);
735
736                 /* If a contact was returned and we need to keep track of existing contacts then it
737                  * should be removed.
738                  */
739                 if (contact && existing_contacts) {
740                         ao2_unlink(existing_contacts, contact);
741                 }
742
743                 if (!contact) {
744                         int prune_on_boot;
745
746                         /* If they are actually trying to delete a contact that does not exist... be forgiving */
747                         if (!expiration) {
748                                 ast_verb(3, "Attempted to remove non-existent contact '%s' from AOR '%s' by request\n",
749                                         contact_uri, aor_name);
750                                 continue;
751                         }
752
753                         prune_on_boot = !ast_sip_will_uri_survive_restart(details.uri, endpoint, rdata);
754
755                         contact = ast_sip_location_create_contact(aor, contact_uri,
756                                 ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1)),
757                                 path_str ? ast_str_buffer(path_str) : NULL,
758                                 user_agent, via_addr, via_port, call_id, prune_on_boot, endpoint);
759                         if (!contact) {
760                                 ast_log(LOG_ERROR, "Unable to bind contact '%s' to AOR '%s'\n",
761                                         contact_uri, aor_name);
762                                 continue;
763                         }
764
765                         if (prune_on_boot) {
766                                 const char *contact_name;
767                                 struct contact_transport_monitor *monitor;
768
769                                 /*
770                                  * Monitor the transport in case it gets disconnected because
771                                  * the contact won't be valid anymore if that happens.
772                                  */
773                                 contact_name = ast_sorcery_object_get_id(contact);
774                                 monitor = ao2_alloc(sizeof(*monitor) + 2 + strlen(aor_name)
775                                         + strlen(contact_name), NULL);
776                                 if (monitor) {
777                                         strcpy(monitor->aor_name, aor_name);/* Safe */
778                                         monitor->contact_name = monitor->aor_name + strlen(aor_name) + 1;
779                                         strcpy(monitor->contact_name, contact_name);/* Safe */
780
781                                         ast_sip_transport_monitor_register_replace(rdata->tp_info.transport,
782                                                 register_contact_transport_shutdown_cb, monitor, contact_transport_monitor_matcher);
783                                         ao2_ref(monitor, -1);
784                                 }
785                         }
786
787                         ast_verb(3, "Added contact '%s' to AOR '%s' with expiration of %d seconds\n",
788                                 contact_uri, aor_name, expiration);
789                         ast_test_suite_event_notify("AOR_CONTACT_ADDED",
790                                         "Contact: %s\r\n"
791                                         "AOR: %s\r\n"
792                                         "Expiration: %d\r\n"
793                                         "UserAgent: %s",
794                                         contact_uri,
795                                         aor_name,
796                                         expiration,
797                                         user_agent);
798
799                         ao2_link(contacts, contact);
800                 } else if (expiration) {
801                         struct ast_sip_contact *contact_update;
802
803                         contact_update = ast_sorcery_copy(ast_sip_get_sorcery(), contact);
804                         if (!contact_update) {
805                                 ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
806                                         contact->uri, expiration);
807                                 continue;
808                         }
809
810                         contact_update->expiration_time = ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1));
811                         contact_update->qualify_frequency = aor->qualify_frequency;
812                         contact_update->authenticate_qualify = aor->authenticate_qualify;
813                         if (path_str) {
814                                 ast_string_field_set(contact_update, path, ast_str_buffer(path_str));
815                         }
816                         if (user_agent) {
817                                 ast_string_field_set(contact_update, user_agent, user_agent);
818                         }
819                         if (!ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
820                                 ast_string_field_set(contact_update, reg_server, ast_config_AST_SYSTEM_NAME);
821                         }
822
823                         if (ast_sip_location_update_contact(contact_update)) {
824                                 ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
825                                         contact->uri, expiration);
826                                 registrar_contact_delete(CONTACT_DELETE_ERROR, rdata->tp_info.transport,
827                                         contact, aor_name);
828                                 continue;
829                         }
830                         ast_debug(3, "Refreshed contact '%s' on AOR '%s' with new expiration of %d seconds\n",
831                                 contact_uri, aor_name, expiration);
832                         ast_test_suite_event_notify("AOR_CONTACT_REFRESHED",
833                                         "Contact: %s\r\n"
834                                         "AOR: %s\r\n"
835                                         "Expiration: %d\r\n"
836                                         "UserAgent: %s",
837                                         contact_uri,
838                                         aor_name,
839                                         expiration,
840                                         contact_update->user_agent);
841                         ao2_link(contacts, contact_update);
842                         ao2_cleanup(contact_update);
843                 } else {
844                         registrar_contact_delete(CONTACT_DELETE_REQUEST, rdata->tp_info.transport,
845                                         contact, aor_name);
846                 }
847         }
848
849         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
850
851         /*
852          * If the AOR is configured to remove any contacts over max_contacts
853          * that have not been updated/added/deleted as a result of this
854          * REGISTER do so.
855          *
856          * The existing contacts container holds all contacts that were not
857          * involved in this REGISTER.
858          * The contacts container holds the current contacts of the AOR.
859          */
860         if (aor->remove_existing && existing_contacts) {
861                 /* Total contacts after this registration */
862                 contact_count = ao2_container_count(existing_contacts) + updated + added;
863                 if (contact_count > aor->max_contacts) {
864                         /* Remove excess existing contacts that expire the soonest */
865                         remove_excess_contacts(existing_contacts, contacts, contact_count - aor->max_contacts);
866                 }
867                 ao2_ref(existing_contacts, -1);
868         }
869
870         response_contact = ao2_callback(contacts, 0, NULL, NULL);
871
872         /* Send a response containing all of the contacts (including static) that are present on this AOR */
873         if (ast_sip_create_response(rdata, 200, response_contact, &tdata) != PJ_SUCCESS) {
874                 ao2_cleanup(response_contact);
875                 ao2_cleanup(contacts);
876                 response->code = 500;
877                 return;
878         }
879         ao2_cleanup(response_contact);
880
881         /* Add the date header to the response, some UAs use this to set their date and time */
882         registrar_add_date_header(tdata);
883
884         ao2_callback(contacts, 0, registrar_add_contact, tdata);
885
886         if ((expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
887                 expires_hdr = pjsip_expires_hdr_create(tdata->pool, registrar_get_expiration(aor, NULL, rdata));
888                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)expires_hdr);
889         }
890
891         response->tdata = tdata;
892 }
893
894 static int register_aor(pjsip_rx_data *rdata,
895         struct ast_sip_endpoint *endpoint,
896         struct ast_sip_aor *aor,
897         const char *aor_name)
898 {
899         struct aor_core_response response = {
900                 .code = 500,
901         };
902         struct ao2_container *contacts = NULL;
903
904         ao2_lock(aor);
905         contacts = ast_sip_location_retrieve_aor_contacts_nolock(aor);
906         if (!contacts) {
907                 ao2_unlock(aor);
908                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(),
909                         rdata, response.code, NULL, NULL, NULL);
910                 return PJ_TRUE;
911         }
912
913         register_aor_core(rdata, endpoint, aor, aor_name, contacts, &response);
914         ao2_cleanup(contacts);
915         ao2_unlock(aor);
916
917         /* Now send the REGISTER response to the peer */
918         if (response.tdata) {
919                 ast_sip_send_stateful_response(rdata, response.tdata, endpoint);
920         } else {
921                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(),
922                         rdata, response.code, NULL, NULL, NULL);
923         }
924         return PJ_TRUE;
925 }
926
927 static int match_aor(const char *aor_name, const char *id)
928 {
929         if (ast_strlen_zero(aor_name)) {
930                 return 0;
931         }
932
933         if (!strcmp(aor_name, id)) {
934                 ast_debug(3, "Matched id '%s' to aor '%s'\n", id, aor_name);
935                 return 1;
936         }
937
938         return 0;
939 }
940
941 static char *find_aor_name(const char *username, const char *domain, const char *aors)
942 {
943         char *configured_aors;
944         char *aors_buf;
945         char *aor_name;
946         char *id_domain;
947         struct ast_sip_domain_alias *alias;
948
949         id_domain = ast_alloca(strlen(username) + strlen(domain) + 2);
950         sprintf(id_domain, "%s@%s", username, domain);
951
952         aors_buf = ast_strdupa(aors);
953
954         /* Look for exact match on username@domain */
955         configured_aors = aors_buf;
956         while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
957                 if (match_aor(aor_name, id_domain)) {
958                         return ast_strdup(aor_name);
959                 }
960         }
961
962         /* If there's a domain alias, look for exact match on username@domain_alias */
963         alias = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "domain_alias", domain);
964         if (alias) {
965                 char *id_domain_alias = ast_alloca(strlen(username) + strlen(alias->domain) + 2);
966
967                 sprintf(id_domain, "%s@%s", username, alias->domain);
968                 ao2_cleanup(alias);
969
970                 configured_aors = strcpy(aors_buf, aors);/* Safe */
971                 while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
972                         if (match_aor(aor_name, id_domain_alias)) {
973                                 return ast_strdup(aor_name);
974                         }
975                 }
976         }
977
978         if (ast_strlen_zero(username)) {
979                 /* No username, no match */
980                 return NULL;
981         }
982
983         /* Look for exact match on username only */
984         configured_aors = strcpy(aors_buf, aors);/* Safe */
985         while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
986                 if (match_aor(aor_name, username)) {
987                         return ast_strdup(aor_name);
988                 }
989         }
990
991         return NULL;
992 }
993
994 static struct ast_sip_aor *find_registrar_aor(struct pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint)
995 {
996         struct ast_sip_aor *aor = NULL;
997         char *aor_name = NULL;
998         char *domain_name;
999         char *username = NULL;
1000         int i;
1001
1002         for (i = 0; i < AST_VECTOR_SIZE(&endpoint->ident_method_order); ++i) {
1003                 pjsip_sip_uri *uri;
1004                 pjsip_authorization_hdr *header = NULL;
1005
1006                 switch (AST_VECTOR_GET(&endpoint->ident_method_order, i)) {
1007                 case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME:
1008                         uri = pjsip_uri_get_uri(rdata->msg_info.to->uri);
1009
1010                         domain_name = ast_alloca(uri->host.slen + 1);
1011                         ast_copy_pj_str(domain_name, &uri->host, uri->host.slen + 1);
1012                         username = ast_alloca(uri->user.slen + 1);
1013                         ast_copy_pj_str(username, &uri->user, uri->user.slen + 1);
1014
1015                         /*
1016                          * We may want to match without any user options getting
1017                          * in the way.
1018                          */
1019                         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(username);
1020
1021                         aor_name = find_aor_name(username, domain_name, endpoint->aors);
1022                         if (aor_name) {
1023                                 ast_debug(3, "Matched aor '%s' by To username\n", aor_name);
1024                         }
1025                         break;
1026                 case AST_SIP_ENDPOINT_IDENTIFY_BY_AUTH_USERNAME:
1027                         while ((header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_AUTHORIZATION,
1028                                 header ? header->next : NULL))) {
1029                                 if (header && !pj_stricmp2(&header->scheme, "digest")) {
1030                                         username = ast_alloca(header->credential.digest.username.slen + 1);
1031                                         ast_copy_pj_str(username, &header->credential.digest.username, header->credential.digest.username.slen + 1);
1032                                         domain_name = ast_alloca(header->credential.digest.realm.slen + 1);
1033                                         ast_copy_pj_str(domain_name, &header->credential.digest.realm, header->credential.digest.realm.slen + 1);
1034
1035                                         aor_name = find_aor_name(username, domain_name, endpoint->aors);
1036                                         if (aor_name) {
1037                                                 ast_debug(3, "Matched aor '%s' by Authentication username\n", aor_name);
1038                                                 break;
1039                                         }
1040                                 }
1041                         }
1042                         break;
1043                 default:
1044                         continue;
1045                 }
1046
1047                 if (aor_name) {
1048                         break;
1049                 }
1050         }
1051
1052         if (ast_strlen_zero(aor_name) || !(aor = ast_sip_location_retrieve_aor(aor_name))) {
1053                 /* The provided AOR name was not found (be it within the configuration or sorcery itself) */
1054                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
1055                 ast_sip_report_req_no_support(endpoint, rdata, "registrar_requested_aor_not_found");
1056                 ast_log(LOG_WARNING, "AOR '%s' not found for endpoint '%s'\n",
1057                         username ?: "", ast_sorcery_object_get_id(endpoint));
1058         }
1059         ast_free(aor_name);
1060         return aor;
1061 }
1062
1063 static pj_bool_t registrar_on_rx_request(struct pjsip_rx_data *rdata)
1064 {
1065         RAII_VAR(struct ast_sip_endpoint *, endpoint,
1066                  ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
1067         struct ast_sip_aor *aor;
1068         const char *aor_name;
1069
1070         if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method) || !endpoint) {
1071                 return PJ_FALSE;
1072         }
1073
1074         if (ast_strlen_zero(endpoint->aors)) {
1075                 /* Short circuit early if the endpoint has no AORs configured on it, which means no registration possible */
1076                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
1077                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_without_configured_aors");
1078                 ast_log(LOG_WARNING, "Endpoint '%s' has no configured AORs\n", ast_sorcery_object_get_id(endpoint));
1079                 return PJ_TRUE;
1080         }
1081
1082         if (!PJSIP_URI_SCHEME_IS_SIP(rdata->msg_info.to->uri) && !PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.to->uri)) {
1083                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
1084                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_uri_in_to_received");
1085                 ast_log(LOG_WARNING, "Endpoint '%s' attempted to register to an AOR with a non-SIP URI\n", ast_sorcery_object_get_id(endpoint));
1086                 return PJ_TRUE;
1087         }
1088
1089         aor = find_registrar_aor(rdata, endpoint);
1090         if (!aor) {
1091                 /* We've already responded about not finding an AOR. */
1092                 return PJ_TRUE;
1093         }
1094
1095         aor_name = ast_sorcery_object_get_id(aor);
1096
1097         if (!aor->max_contacts) {
1098                 /* Registration is not permitted for this AOR */
1099                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
1100                 ast_sip_report_req_no_support(endpoint, rdata, "registrar_attempt_without_registration_permitted");
1101                 ast_log(LOG_WARNING, "AOR '%s' has no configured max_contacts. Endpoint '%s' unable to register\n",
1102                         aor_name, ast_sorcery_object_get_id(endpoint));
1103         } else {
1104                 register_aor(rdata, endpoint, aor, aor_name);
1105         }
1106         ao2_ref(aor, -1);
1107         return PJ_TRUE;
1108 }
1109
1110 /* function pointer to callback needs to be within the module
1111    in order to avoid problems with an undefined symbol */
1112 static int sip_contact_to_str(void *acp, void *arg, int flags)
1113 {
1114         return ast_sip_contact_to_str(acp, arg, flags);
1115 }
1116
1117 static int ami_registrations_aor(void *obj, void *arg, int flags)
1118 {
1119         struct ast_sip_aor *aor = obj;
1120         struct ast_sip_ami *ami = arg;
1121         int *count = ami->arg;
1122         RAII_VAR(struct ast_str *, buf,
1123                  ast_sip_create_ami_event("InboundRegistrationDetail", ami), ast_free);
1124
1125         if (!buf) {
1126                 return -1;
1127         }
1128
1129         ast_sip_sorcery_object_to_ami(aor, &buf);
1130         ast_str_append(&buf, 0, "Contacts: ");
1131         ast_sip_for_each_contact(aor, sip_contact_to_str, &buf);
1132         ast_str_append(&buf, 0, "\r\n");
1133
1134         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1135         (*count)++;
1136         return 0;
1137 }
1138
1139 static int ami_registrations_endpoint(void *obj, void *arg, int flags)
1140 {
1141         struct ast_sip_endpoint *endpoint = obj;
1142         return ast_sip_for_each_aor(
1143                 endpoint->aors, ami_registrations_aor, arg);
1144 }
1145
1146 static int ami_registrations_endpoints(void *arg)
1147 {
1148         RAII_VAR(struct ao2_container *, endpoints,
1149                  ast_sip_get_endpoints(), ao2_cleanup);
1150
1151         if (!endpoints) {
1152                 return 0;
1153         }
1154
1155         ao2_callback(endpoints, OBJ_NODATA, ami_registrations_endpoint, arg);
1156         return 0;
1157 }
1158
1159 static int ami_show_registrations(struct mansession *s, const struct message *m)
1160 {
1161         int count = 0;
1162         struct ast_sip_ami ami = { .s = s, .m = m, .arg = &count, .action_id = astman_get_header(m, "ActionID"), };
1163
1164         astman_send_listack(s, m, "Following are Events for each Inbound registration",
1165                 "start");
1166
1167         ami_registrations_endpoints(&ami);
1168
1169         astman_send_list_complete_start(s, m, "InboundRegistrationDetailComplete", count);
1170         astman_send_list_complete_end(s);
1171         return 0;
1172 }
1173
1174 static int ami_show_registration_contact_statuses(struct mansession *s, const struct message *m)
1175 {
1176         int count = 0;
1177         struct ast_sip_ami ami = { .s = s, .m = m, .arg = NULL, .action_id = astman_get_header(m, "ActionID"), };
1178         struct ao2_container *contacts = ast_sorcery_retrieve_by_fields(
1179                 ast_sip_get_sorcery(), "contact", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1180         struct ao2_iterator i;
1181         struct ast_sip_contact *contact;
1182
1183         astman_send_listack(s, m, "Following are ContactStatusEvents for each Inbound "
1184                             "registration", "start");
1185
1186         if (contacts) {
1187                 i = ao2_iterator_init(contacts, 0);
1188                 while ((contact = ao2_iterator_next(&i))) {
1189                         struct ast_sip_contact_wrapper wrapper;
1190
1191                         wrapper.aor_id = (char *)contact->aor;
1192                         wrapper.contact = contact;
1193                         wrapper.contact_id = (char *)ast_sorcery_object_get_id(contact);
1194
1195                         ast_sip_format_contact_ami(&wrapper, &ami, 0);
1196                         count++;
1197
1198                         ao2_ref(contact, -1);
1199                 }
1200                 ao2_iterator_destroy(&i);
1201                 ao2_ref(contacts, -1);
1202         }
1203
1204         astman_send_list_complete_start(s, m, "ContactStatusDetailComplete", count);
1205         astman_send_list_complete_end(s);
1206         return 0;
1207 }
1208
1209 #define AMI_SHOW_REGISTRATION_CONTACT_STATUSES "PJSIPShowRegistrationInboundContactStatuses"
1210 #define AMI_SHOW_REGISTRATIONS "PJSIPShowRegistrationsInbound"
1211
1212 static pjsip_module registrar_module = {
1213         .name = { "Registrar", 9 },
1214         .id = -1,
1215         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1216         .on_rx_request = registrar_on_rx_request,
1217 };
1218
1219 /*! \brief Thread keeping things alive */
1220 static pthread_t check_thread = AST_PTHREADT_NULL;
1221
1222 /*! \brief The global interval at which to check for contact expiration */
1223 static unsigned int check_interval;
1224
1225 /*! \brief Callback function which deletes a contact */
1226 static int expire_contact(void *obj, void *arg, int flags)
1227 {
1228         struct ast_sip_contact *contact = obj;
1229         struct ast_named_lock *lock;
1230
1231         lock = ast_named_lock_get(AST_NAMED_LOCK_TYPE_MUTEX, "aor", contact->aor);
1232         if (!lock) {
1233                 return 0;
1234         }
1235
1236         /*
1237          * We need to check the expiration again with the aor lock held
1238          * in case another thread is attempting to renew the contact.
1239          */
1240         ao2_lock(lock);
1241         if (ast_tvdiff_ms(ast_tvnow(), contact->expiration_time) > 0) {
1242                 registrar_contact_delete(CONTACT_DELETE_EXPIRE, NULL, contact, contact->aor);
1243         }
1244         ao2_unlock(lock);
1245         ast_named_lock_put(lock);
1246
1247         return 0;
1248 }
1249
1250 static void *check_expiration_thread(void *data)
1251 {
1252         struct ao2_container *contacts;
1253         struct ast_variable *var;
1254         char *time = alloca(64);
1255
1256         while (check_interval) {
1257                 sleep(check_interval);
1258
1259                 sprintf(time, "%ld", ast_tvnow().tv_sec);
1260                 var = ast_variable_new("expiration_time <=", time, "");
1261
1262                 ast_debug(4, "Woke up at %s  Interval: %d\n", time, check_interval);
1263
1264                 contacts = ast_sorcery_retrieve_by_fields(ast_sip_get_sorcery(), "contact",
1265                         AST_RETRIEVE_FLAG_MULTIPLE, var);
1266
1267                 ast_variables_destroy(var);
1268                 if (contacts) {
1269                         ast_debug(3, "Expiring %d contacts\n", ao2_container_count(contacts));
1270                         ao2_callback(contacts, OBJ_NODATA, expire_contact, NULL);
1271                         ao2_ref(contacts, -1);
1272                 }
1273         }
1274
1275         return NULL;
1276 }
1277
1278 static void expiration_global_loaded(const char *object_type)
1279 {
1280         check_interval = ast_sip_get_contact_expiration_check_interval();
1281
1282         /* Observer calls are serialized so this is safe without it's own lock */
1283         if (check_interval) {
1284                 if (check_thread == AST_PTHREADT_NULL) {
1285                         if (ast_pthread_create_background(&check_thread, NULL, check_expiration_thread, NULL)) {
1286                                 ast_log(LOG_ERROR, "Could not create thread for checking contact expiration.\n");
1287                                 return;
1288                         }
1289                         ast_debug(3, "Interval = %d, starting thread\n", check_interval);
1290                 }
1291         } else {
1292                 if (check_thread != AST_PTHREADT_NULL) {
1293                         pthread_kill(check_thread, SIGURG);
1294                         pthread_join(check_thread, NULL);
1295                         check_thread = AST_PTHREADT_NULL;
1296                         ast_debug(3, "Interval = 0, shutting thread down\n");
1297                 }
1298         }
1299 }
1300
1301 /*! \brief Observer which is used to update our interval when the global setting changes */
1302 static struct ast_sorcery_observer expiration_global_observer = {
1303         .loaded = expiration_global_loaded,
1304 };
1305
1306 static int load_module(void)
1307 {
1308         const pj_str_t STR_REGISTER = { "REGISTER", 8 };
1309
1310         ast_pjproject_get_buildopt("PJ_MAX_HOSTNAME", "%d", &pj_max_hostname);
1311         /* As of pjproject 2.4.5, PJSIP_MAX_URL_SIZE isn't exposed yet but we try anyway. */
1312         ast_pjproject_get_buildopt("PJSIP_MAX_URL_SIZE", "%d", &pjsip_max_url_size);
1313
1314         if (ast_sip_register_service(&registrar_module)) {
1315                 return AST_MODULE_LOAD_DECLINE;
1316         }
1317
1318         if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW, NULL, 1, &STR_REGISTER) != PJ_SUCCESS) {
1319                 ast_sip_unregister_service(&registrar_module);
1320                 return AST_MODULE_LOAD_DECLINE;
1321         }
1322
1323         ast_manager_register_xml(AMI_SHOW_REGISTRATIONS, EVENT_FLAG_SYSTEM,
1324                                  ami_show_registrations);
1325         ast_manager_register_xml(AMI_SHOW_REGISTRATION_CONTACT_STATUSES, EVENT_FLAG_SYSTEM,
1326                                  ami_show_registration_contact_statuses);
1327
1328         ast_sorcery_observer_add(ast_sip_get_sorcery(), "global", &expiration_global_observer);
1329         ast_sorcery_reload_object(ast_sip_get_sorcery(), "global");
1330
1331         return AST_MODULE_LOAD_SUCCESS;
1332 }
1333
1334 static int unload_module(void)
1335 {
1336         if (check_thread != AST_PTHREADT_NULL) {
1337                 check_interval = 0;
1338                 pthread_kill(check_thread, SIGURG);
1339                 pthread_join(check_thread, NULL);
1340
1341                 check_thread = AST_PTHREADT_NULL;
1342         }
1343
1344         ast_sorcery_observer_remove(ast_sip_get_sorcery(), "global", &expiration_global_observer);
1345
1346         ast_manager_unregister(AMI_SHOW_REGISTRATIONS);
1347         ast_manager_unregister(AMI_SHOW_REGISTRATION_CONTACT_STATUSES);
1348         ast_sip_unregister_service(&registrar_module);
1349         ast_sip_transport_monitor_unregister_all(register_contact_transport_shutdown_cb, NULL, NULL);
1350         return 0;
1351 }
1352
1353 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Registrar Support",
1354         .support_level = AST_MODULE_SUPPORT_CORE,
1355         .load = load_module,
1356         .unload = unload_module,
1357         .load_pri = AST_MODPRI_CHANNEL_DEPEND - 3,
1358         .requires = "res_pjproject,res_pjsip",
1359 );