res_pjsip_registrar.c: Update remove_existing AOR contact handling.
[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 <pjsip.h>
29 #include <pjsip_ua.h>
30
31 #include "asterisk/res_pjsip.h"
32 #include "asterisk/module.h"
33 #include "asterisk/paths.h"
34 #include "asterisk/test.h"
35 #include "asterisk/taskprocessor.h"
36 #include "asterisk/manager.h"
37 #include "asterisk/named_locks.h"
38 #include "asterisk/res_pjproject.h"
39 #include "res_pjsip/include/res_pjsip_private.h"
40
41 /*** DOCUMENTATION
42         <manager name="PJSIPShowRegistrationsInbound" language="en_US">
43                 <synopsis>
44                         Lists PJSIP inbound registrations.
45                 </synopsis>
46                 <syntax />
47                 <description>
48                         <para>
49                         In response, <literal>InboundRegistrationDetail</literal> events showing configuration
50                         and status information are raised for all contacts, static or dynamic.  Once all events
51                         are completed an <literal>InboundRegistrationDetailComplete</literal> is issued.
52                         </para>
53                         <warning><para>
54                                 This command just dumps all coonfigured AORs with contacts, even if the contact
55                                 is a permanent one.  To really get just inbound registrations, use
56                                 <literal>PJSIPShowRegistrationInboundContactStatuses</literal>.
57                         </para>
58                         </warning>
59                 </description>
60                 <see-also>
61                         <ref type="manager" module="res_pjsip_registrar">PJSIPShowRegistrationInboundContactStatuses</ref>
62                 </see-also>
63         </manager>
64         <manager name="PJSIPShowRegistrationInboundContactStatuses" language="en_US">
65                 <synopsis>
66                         Lists ContactStatuses for PJSIP inbound registrations.
67                 </synopsis>
68                 <syntax />
69                 <description>
70                         <para>
71                         In response, <literal>ContactStatusDetail</literal> events showing status information
72                         are raised for each inbound registration (dynamic contact) object.  Once all events
73                         are completed a <literal>ContactStatusDetailComplete</literal> event is issued.
74                         </para>
75                 </description>
76         </manager>
77  ***/
78
79 static int pj_max_hostname = PJ_MAX_HOSTNAME;
80 static int pjsip_max_url_size = PJSIP_MAX_URL_SIZE;
81
82 /*! \brief Internal function which returns the expiration time for a contact */
83 static int registrar_get_expiration(const struct ast_sip_aor *aor, const pjsip_contact_hdr *contact, const pjsip_rx_data *rdata)
84 {
85         pjsip_expires_hdr *expires;
86         int expiration = aor->default_expiration;
87
88         if (contact && contact->expires != -1) {
89                 /* Expiration was provided with the contact itself */
90                 expiration = contact->expires;
91         } else if ((expires = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
92                 /* Expiration was provided using the Expires header */
93                 expiration = expires->ivalue;
94         }
95
96         /* If the value has explicitly been set to 0, do not enforce */
97         if (!expiration) {
98                 return expiration;
99         }
100
101         /* Enforce the range that we will allow for expiration */
102         if (expiration < aor->minimum_expiration) {
103                 expiration = aor->minimum_expiration;
104         } else if (expiration > aor->maximum_expiration) {
105                 expiration = aor->maximum_expiration;
106         }
107
108         return expiration;
109 }
110
111 /*! \brief Structure used for finding contact */
112 struct registrar_contact_details {
113         /*! \brief Pool used for parsing URI */
114         pj_pool_t *pool;
115         /*! \brief URI being looked for */
116         pjsip_sip_uri *uri;
117 };
118
119 /*! \brief Callback function for finding a contact */
120 static int registrar_find_contact(void *obj, void *arg, int flags)
121 {
122         struct ast_sip_contact *contact = obj;
123         const struct registrar_contact_details *details = arg;
124         pjsip_uri *contact_uri = pjsip_parse_uri(details->pool, (char*)contact->uri, strlen(contact->uri), 0);
125
126         return (pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, details->uri, contact_uri) == PJ_SUCCESS) ? CMP_MATCH : 0;
127 }
128
129 /*! \brief Internal function which validates provided Contact headers to confirm that they are acceptable, and returns number of contacts */
130 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)
131 {
132         pjsip_contact_hdr *previous = NULL;
133         pjsip_contact_hdr *contact = (pjsip_contact_hdr *)&rdata->msg_info.msg->hdr;
134         struct registrar_contact_details details = {
135                 .pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Contact Comparison", 256, 256),
136         };
137
138         if (!details.pool) {
139                 return -1;
140         }
141
142         while ((contact = (pjsip_contact_hdr *) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact->next))) {
143                 int expiration = registrar_get_expiration(aor, contact, rdata);
144                 struct ast_sip_contact *existing;
145                 char contact_uri[pjsip_max_url_size];
146
147                 if (contact->star) {
148                         /* The expiration MUST be 0 when a '*' contact is used and there must be no other contact */
149                         if (expiration != 0 || previous) {
150                                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
151                                 return -1;
152                         }
153                         /* Count all contacts to delete */
154                         *deleted = ao2_container_count(contacts);
155                         previous = contact;
156                         continue;
157                 } else if (previous && previous->star) {
158                         /* If there is a previous contact and it is a '*' this is a deal breaker */
159                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
160                         return -1;
161                 }
162                 previous = contact;
163
164                 if (!PJSIP_URI_SCHEME_IS_SIP(contact->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact->uri)) {
165                         continue;
166                 }
167
168                 details.uri = pjsip_uri_get_uri(contact->uri);
169
170                 /* pjsip_uri_print returns -1 if there's not enough room in the buffer */
171                 if (pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri)) < 0) {
172                         /* If the total length of the uri is greater than pjproject can handle, go no further */
173                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
174                         return -1;
175                 }
176
177                 if (details.uri->host.slen >= pj_max_hostname) {
178                         /* If the length of the hostname is greater than pjproject can handle, go no further */
179                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
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         /* The provided contacts are acceptable, huzzah! */
198         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
199         return 0;
200 }
201
202 /*! \brief Callback function which prunes static contacts */
203 static int registrar_prune_static(void *obj, void *arg, int flags)
204 {
205         struct ast_sip_contact *contact = obj;
206
207         return ast_tvzero(contact->expiration_time) ? CMP_MATCH : 0;
208 }
209
210 /*! \brief Internal function used to delete a contact from an AOR */
211 static int registrar_delete_contact(void *obj, void *arg, int flags)
212 {
213         struct ast_sip_contact *contact = obj;
214         const char *aor_name = arg;
215
216         ast_sip_location_delete_contact(contact);
217         if (!ast_strlen_zero(aor_name)) {
218                 ast_verb(3, "Removed contact '%s' from AOR '%s' due to request\n", contact->uri, aor_name);
219                 ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
220                                 "Contact: %s\r\n"
221                                 "AOR: %s\r\n"
222                                 "UserAgent: %s",
223                                 contact->uri,
224                                 aor_name,
225                                 contact->user_agent);
226         }
227
228         return CMP_MATCH;
229 }
230
231 /*! \brief Internal function which adds a contact to a response */
232 static int registrar_add_contact(void *obj, void *arg, int flags)
233 {
234         struct ast_sip_contact *contact = obj;
235         pjsip_tx_data *tdata = arg;
236         pjsip_contact_hdr *hdr = pjsip_contact_hdr_create(tdata->pool);
237         pj_str_t uri;
238
239         pj_strdup2_with_null(tdata->pool, &uri, contact->uri);
240         hdr->uri = pjsip_parse_uri(tdata->pool, uri.ptr, uri.slen, PJSIP_PARSE_URI_AS_NAMEADDR);
241         hdr->expires = ast_tvdiff_ms(contact->expiration_time, ast_tvnow()) / 1000;
242
243         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr);
244
245         return 0;
246 }
247
248 /*! \brief Helper function which adds a Date header to a response */
249 static void registrar_add_date_header(pjsip_tx_data *tdata)
250 {
251         char date[256];
252         struct tm tm;
253         time_t t = time(NULL);
254
255         gmtime_r(&t, &tm);
256         strftime(date, sizeof(date), "%a, %d %b %Y %T GMT", &tm);
257
258         ast_sip_add_header(tdata, "Date", date);
259 }
260
261 static const pj_str_t path_hdr_name = { "Path", 4 };
262
263 static int build_path_data(pjsip_rx_data *rdata, struct ast_str **path_str)
264 {
265         pjsip_generic_string_hdr *path_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &path_hdr_name, NULL);
266
267         if (!path_hdr) {
268                 return 0;
269         }
270
271         *path_str = ast_str_create(64);
272         if (!path_str) {
273                 return -1;
274         }
275
276         ast_str_set(path_str, 0, "%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
277
278         while ((path_hdr = (pjsip_generic_string_hdr *) pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &path_hdr_name, path_hdr->next))) {
279                 ast_str_append(path_str, 0, ",%.*s", (int)path_hdr->hvalue.slen, path_hdr->hvalue.ptr);
280         }
281
282         return 0;
283 }
284
285 static int registrar_validate_path(pjsip_rx_data *rdata, struct ast_sip_aor *aor, struct ast_str **path_str)
286 {
287         const pj_str_t path_supported_name = { "path", 4 };
288         pjsip_supported_hdr *supported_hdr;
289         int i;
290
291         if (!aor->support_path) {
292                 return 0;
293         }
294
295         if (build_path_data(rdata, path_str)) {
296                 return -1;
297         }
298
299         if (!*path_str) {
300                 return 0;
301         }
302
303         supported_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_SUPPORTED, NULL);
304         if (!supported_hdr) {
305                 return -1;
306         }
307
308         /* Find advertised path support */
309         for (i = 0; i < supported_hdr->count; i++) {
310                 if (!pj_stricmp(&supported_hdr->values[i], &path_supported_name)) {
311                         return 0;
312                 }
313         }
314
315         /* Path header present, but support not advertised */
316         return -1;
317 }
318
319 /*! Transport monitor for incoming REGISTER contacts */
320 struct contact_transport_monitor {
321         /*!
322          * \brief Sorcery contact name to remove on transport shutdown
323          * \note Stored after aor_name in space reserved when struct allocated.
324          */
325         char *contact_name;
326         /*! AOR name the contact is associated */
327         char aor_name[0];
328 };
329
330 static void register_contact_transport_shutdown_cb(void *data)
331 {
332         struct contact_transport_monitor *monitor = data;
333         struct ast_sip_contact *contact;
334         struct ast_sip_aor *aor;
335
336         aor = ast_sip_location_retrieve_aor(monitor->aor_name);
337         if (!aor) {
338                 return;
339         }
340
341         ao2_lock(aor);
342         contact = ast_sip_location_retrieve_contact(monitor->contact_name);
343         if (contact) {
344                 ast_sip_location_delete_contact(contact);
345                 ast_verb(3, "Removed contact '%s' from AOR '%s' due to transport shutdown\n",
346                         contact->uri, monitor->aor_name);
347                 ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
348                         "Contact: %s\r\n"
349                         "AOR: %s\r\n"
350                         "UserAgent: %s",
351                         contact->uri,
352                         monitor->aor_name,
353                         contact->user_agent);
354                 ao2_ref(contact, -1);
355         }
356         ao2_unlock(aor);
357         ao2_ref(aor, -1);
358 }
359
360 AST_VECTOR(excess_contact_vector, struct ast_sip_contact *);
361
362 static int vec_contact_cmp(struct ast_sip_contact *left, struct ast_sip_contact *right)
363 {
364         struct ast_sip_contact *left_contact = left;
365         struct ast_sip_contact *right_contact = right;
366
367         /* Sort from soonest to expire to last to expire */
368         return ast_tvcmp(left_contact->expiration_time, right_contact->expiration_time);
369 }
370
371 static int vec_contact_add(void *obj, void *arg, int flags)
372 {
373         struct ast_sip_contact *contact = obj;
374         struct excess_contact_vector *contact_vec = arg;
375
376         /*
377          * Performance wise, an insertion sort is fine because we
378          * shouldn't need to remove more than a handful of contacts.
379          * I expect we'll typically be removing only one contact.
380          */
381         AST_VECTOR_ADD_SORTED(contact_vec, contact, vec_contact_cmp);
382         if (AST_VECTOR_SIZE(contact_vec) == AST_VECTOR_MAX_SIZE(contact_vec)) {
383                 /*
384                  * We added a contact over the number we need to remove.
385                  * Remove the longest to expire contact from the vector
386                  * which is the last element in the vector.  It may be
387                  * the one we just added or the one we just added pushed
388                  * out an earlier contact from removal consideration.
389                  */
390                 --AST_VECTOR_SIZE(contact_vec);
391         }
392         return 0;
393 }
394
395 /*!
396  * \internal
397  * \brief Remove excess existing contacts that expire the soonest.
398  * \since 13.18.0
399  *
400  * \param contacts Container of unmodified contacts that could remove.
401  * \param to_remove Maximum number of contacts to remove.
402  *
403  * \return Nothing
404  */
405 static void remove_excess_contacts(struct ao2_container *contacts, unsigned int to_remove)
406 {
407         struct excess_contact_vector contact_vec;
408
409         /*
410          * Create a sorted vector to hold the to_remove soonest to
411          * expire contacts.  The vector has an extra space to
412          * temporarily hold the longest to expire contact that we
413          * won't remove.
414          */
415         if (AST_VECTOR_INIT(&contact_vec, to_remove + 1)) {
416                 return;
417         }
418         ao2_callback(contacts, OBJ_NODATA | OBJ_MULTIPLE, vec_contact_add, &contact_vec);
419
420         /*
421          * The vector should always be populated with the number
422          * of contacts we need to remove.  Just in case, we will
423          * remove all contacts in the vector even if the contacts
424          * container had fewer contacts than there should be.
425          */
426         ast_assert(AST_VECTOR_SIZE(&contact_vec) == to_remove);
427         to_remove = AST_VECTOR_SIZE(&contact_vec);
428
429         /* Remove the excess contacts that expire the soonest */
430         while (to_remove--) {
431                 struct ast_sip_contact *contact;
432
433                 contact = AST_VECTOR_GET(&contact_vec, to_remove);
434
435                 ast_sip_location_delete_contact(contact);
436                 ast_verb(3, "Removed contact '%s' from AOR '%s' due to remove_existing\n",
437                         contact->uri, contact->aor);
438                 ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
439                         "Contact: %s\r\n"
440                         "AOR: %s\r\n"
441                         "UserAgent: %s",
442                         contact->uri,
443                         contact->aor,
444                         contact->user_agent);
445         }
446
447         AST_VECTOR_FREE(&contact_vec);
448 }
449
450 static int register_aor_core(pjsip_rx_data *rdata,
451         struct ast_sip_endpoint *endpoint,
452         struct ast_sip_aor *aor,
453         const char *aor_name,
454         struct ao2_container *contacts)
455 {
456         static const pj_str_t USER_AGENT = { "User-Agent", 10 };
457
458         int added = 0;
459         int updated = 0;
460         int deleted = 0;
461         int contact_count;
462         pjsip_contact_hdr *contact_hdr = NULL;
463         struct registrar_contact_details details = { 0, };
464         pjsip_tx_data *tdata;
465         RAII_VAR(struct ast_str *, path_str, NULL, ast_free);
466         struct ast_sip_contact *response_contact;
467         char *user_agent = NULL;
468         pjsip_user_agent_hdr *user_agent_hdr;
469         pjsip_expires_hdr *expires_hdr;
470         pjsip_via_hdr *via_hdr;
471         pjsip_via_hdr *via_hdr_last;
472         char *via_addr = NULL;
473         int via_port = 0;
474         pjsip_cid_hdr *call_id_hdr;
475         char *call_id = NULL;
476         size_t alloc_size;
477
478         /* So we don't count static contacts against max_contacts we prune them out from the container */
479         ao2_callback(contacts, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, registrar_prune_static, NULL);
480
481         if (registrar_validate_contacts(rdata, contacts, aor, &added, &updated, &deleted)) {
482                 /* The provided Contact headers do not conform to the specification */
483                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 400, NULL, NULL, NULL);
484                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_contacts_provided");
485                 ast_log(LOG_WARNING, "Failed to validate contacts in REGISTER request from '%s'\n",
486                                 ast_sorcery_object_get_id(endpoint));
487                 return PJ_TRUE;
488         }
489
490         if (registrar_validate_path(rdata, aor, &path_str)) {
491                 /* Ensure that intervening proxies did not make invalid modifications to the request */
492                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 420, NULL, NULL, NULL);
493                 ast_log(LOG_WARNING, "Invalid modifications made to REGISTER request from '%s' by intervening proxy\n",
494                                 ast_sorcery_object_get_id(endpoint));
495                 return PJ_TRUE;
496         }
497
498         if (aor->remove_existing) {
499                 /* Cumulative number of contacts affected by this registration */
500                 contact_count = MAX(updated + added - deleted,  0);
501         } else {
502                 /* Total contacts after this registration */
503                 contact_count = ao2_container_count(contacts) + added - deleted;
504         }
505         if (contact_count > aor->max_contacts) {
506                 /* Enforce the maximum number of contacts */
507                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
508                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_exceeds_maximum_configured_contacts");
509                 ast_log(LOG_WARNING, "Registration attempt from endpoint '%s' to AOR '%s' will exceed max contacts of %u\n",
510                                 ast_sorcery_object_get_id(endpoint), aor_name, aor->max_contacts);
511                 return PJ_TRUE;
512         }
513
514         details.pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(),
515                 "Contact Comparison", 256, 256);
516         if (!details.pool) {
517                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
518                 return PJ_TRUE;
519         }
520
521         user_agent_hdr = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &USER_AGENT, NULL);
522         if (user_agent_hdr) {
523                 alloc_size = pj_strlen(&user_agent_hdr->hvalue) + 1;
524                 user_agent = ast_alloca(alloc_size);
525                 ast_copy_pj_str(user_agent, &user_agent_hdr->hvalue, alloc_size);
526         }
527
528         /* Find the first Via header */
529         via_hdr = via_hdr_last = (pjsip_via_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_VIA, NULL);
530         if (via_hdr) {
531                 /* Find the last Via header */
532                 while ( (via_hdr = (pjsip_via_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg,
533                                 PJSIP_H_VIA, via_hdr->next)) != NULL) {
534                         via_hdr_last = via_hdr;
535                 }
536                 alloc_size = pj_strlen(&via_hdr_last->sent_by.host) + 1;
537                 via_addr = ast_alloca(alloc_size);
538                 ast_copy_pj_str(via_addr, &via_hdr_last->sent_by.host, alloc_size);
539                 via_port=via_hdr_last->sent_by.port;
540         }
541
542         call_id_hdr = (pjsip_cid_hdr*) pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CALL_ID, NULL);
543         if (call_id_hdr) {
544                 alloc_size = pj_strlen(&call_id_hdr->id) + 1;
545                 call_id = ast_alloca(alloc_size);
546                 ast_copy_pj_str(call_id, &call_id_hdr->id, alloc_size);
547         }
548
549         /* Iterate each provided Contact header and add, update, or delete */
550         while ((contact_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT, contact_hdr ? contact_hdr->next : NULL))) {
551                 int expiration;
552                 char contact_uri[pjsip_max_url_size];
553                 RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
554
555                 if (contact_hdr->star) {
556                         /* A star means to unregister everything, so do so for the possible contacts */
557                         ao2_callback(contacts, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
558                                 registrar_delete_contact, (void *)aor_name);
559                         break;
560                 }
561
562                 if (!PJSIP_URI_SCHEME_IS_SIP(contact_hdr->uri) && !PJSIP_URI_SCHEME_IS_SIPS(contact_hdr->uri)) {
563                         /* This registrar only currently supports sip: and sips: URI schemes */
564                         continue;
565                 }
566
567                 expiration = registrar_get_expiration(aor, contact_hdr, rdata);
568                 details.uri = pjsip_uri_get_uri(contact_hdr->uri);
569                 pjsip_uri_print(PJSIP_URI_IN_CONTACT_HDR, details.uri, contact_uri, sizeof(contact_uri));
570
571                 contact = ao2_callback(contacts, OBJ_UNLINK, registrar_find_contact, &details);
572                 if (!contact) {
573                         int prune_on_boot = 0;
574                         pj_str_t host_name;
575
576                         /* If they are actually trying to delete a contact that does not exist... be forgiving */
577                         if (!expiration) {
578                                 ast_verb(3, "Attempted to remove non-existent contact '%s' from AOR '%s' by request\n",
579                                         contact_uri, aor_name);
580                                 continue;
581                         }
582
583                         /* Determine if the contact cannot survive a restart/boot. */
584                         if (details.uri->port == rdata->pkt_info.src_port
585                                 && !pj_strcmp(&details.uri->host,
586                                         pj_cstr(&host_name, rdata->pkt_info.src_name))
587                                 /* We have already checked if the URI scheme is sip: or sips: */
588                                 && PJSIP_TRANSPORT_IS_RELIABLE(rdata->tp_info.transport)) {
589                                 pj_str_t type_name;
590
591                                 /* Determine the transport parameter value */
592                                 if (!strcasecmp("WSS", rdata->tp_info.transport->type_name)) {
593                                         /* WSS is special, as it needs to be ws. */
594                                         pj_cstr(&type_name, "ws");
595                                 } else {
596                                         pj_cstr(&type_name, rdata->tp_info.transport->type_name);
597                                 }
598
599                                 if (!pj_stricmp(&details.uri->transport_param, &type_name)
600                                         && (endpoint->nat.rewrite_contact
601                                                 /* Websockets are always rewritten */
602                                                 || !pj_stricmp(&details.uri->transport_param,
603                                                         pj_cstr(&type_name, "ws")))) {
604                                         /*
605                                          * The contact was rewritten to the reliable transport's
606                                          * source address.  Disconnecting the transport for any
607                                          * reason invalidates the contact.
608                                          */
609                                         prune_on_boot = 1;
610                                 }
611                         }
612
613                         contact = ast_sip_location_create_contact(aor, contact_uri,
614                                 ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1)),
615                                 path_str ? ast_str_buffer(path_str) : NULL,
616                                 user_agent, via_addr, via_port, call_id, prune_on_boot, endpoint);
617                         if (!contact) {
618                                 ast_log(LOG_ERROR, "Unable to bind contact '%s' to AOR '%s'\n",
619                                         contact_uri, aor_name);
620                                 continue;
621                         }
622
623                         if (prune_on_boot) {
624                                 const char *contact_name;
625                                 struct contact_transport_monitor *monitor;
626
627                                 /*
628                                  * Monitor the transport in case it gets disconnected because
629                                  * the contact won't be valid anymore if that happens.
630                                  */
631                                 contact_name = ast_sorcery_object_get_id(contact);
632                                 monitor = ao2_alloc_options(sizeof(*monitor) + 2 + strlen(aor_name)
633                                         + strlen(contact_name), NULL, AO2_ALLOC_OPT_LOCK_NOLOCK);
634                                 if (monitor) {
635                                         strcpy(monitor->aor_name, aor_name);/* Safe */
636                                         monitor->contact_name = monitor->aor_name + strlen(aor_name) + 1;
637                                         strcpy(monitor->contact_name, contact_name);/* Safe */
638
639                                         ast_sip_transport_monitor_register(rdata->tp_info.transport,
640                                                 register_contact_transport_shutdown_cb, monitor);
641                                         ao2_ref(monitor, -1);
642                                 }
643                         }
644
645                         ast_verb(3, "Added contact '%s' to AOR '%s' with expiration of %d seconds\n",
646                                 contact_uri, aor_name, expiration);
647                         ast_test_suite_event_notify("AOR_CONTACT_ADDED",
648                                         "Contact: %s\r\n"
649                                         "AOR: %s\r\n"
650                                         "Expiration: %d\r\n"
651                                         "UserAgent: %s",
652                                         contact_uri,
653                                         aor_name,
654                                         expiration,
655                                         user_agent);
656                 } else if (expiration) {
657                         struct ast_sip_contact *contact_update;
658
659                         contact_update = ast_sorcery_copy(ast_sip_get_sorcery(), contact);
660                         if (!contact_update) {
661                                 ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
662                                         contact->uri, expiration);
663                                 continue;
664                         }
665
666                         contact_update->expiration_time = ast_tvadd(ast_tvnow(), ast_samp2tv(expiration, 1));
667                         contact_update->qualify_frequency = aor->qualify_frequency;
668                         contact_update->authenticate_qualify = aor->authenticate_qualify;
669                         if (path_str) {
670                                 ast_string_field_set(contact_update, path, ast_str_buffer(path_str));
671                         }
672                         if (user_agent) {
673                                 ast_string_field_set(contact_update, user_agent, user_agent);
674                         }
675                         if (!ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
676                                 ast_string_field_set(contact_update, reg_server, ast_config_AST_SYSTEM_NAME);
677                         }
678
679                         if (ast_sip_location_update_contact(contact_update)) {
680                                 ast_log(LOG_ERROR, "Failed to update contact '%s' expiration time to %d seconds.\n",
681                                         contact->uri, expiration);
682                                 ast_sip_location_delete_contact(contact);
683                                 continue;
684                         }
685                         ast_debug(3, "Refreshed contact '%s' on AOR '%s' with new expiration of %d seconds\n",
686                                 contact_uri, aor_name, expiration);
687                         ast_test_suite_event_notify("AOR_CONTACT_REFRESHED",
688                                         "Contact: %s\r\n"
689                                         "AOR: %s\r\n"
690                                         "Expiration: %d\r\n"
691                                         "UserAgent: %s",
692                                         contact_uri,
693                                         aor_name,
694                                         expiration,
695                                         contact_update->user_agent);
696                         ao2_cleanup(contact_update);
697                 } else {
698                         /* We want to report the user agent that was actually in the removed contact */
699                         ast_sip_location_delete_contact(contact);
700                         ast_verb(3, "Removed contact '%s' from AOR '%s' due to request\n", contact_uri, aor_name);
701                         ast_test_suite_event_notify("AOR_CONTACT_REMOVED",
702                                         "Contact: %s\r\n"
703                                         "AOR: %s\r\n"
704                                         "UserAgent: %s",
705                                         contact_uri,
706                                         aor_name,
707                                         contact->user_agent);
708                 }
709         }
710
711         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), details.pool);
712
713         /*
714          * If the AOR is configured to remove any contacts over max_contacts
715          * that have not been updated/added/deleted as a result of this
716          * REGISTER do so.
717          *
718          * The contacts container currently holds the existing contacts that
719          * were not affected by this REGISTER.
720          */
721         if (aor->remove_existing) {
722                 /* Total contacts after this registration */
723                 contact_count = ao2_container_count(contacts) + updated + added;
724                 if (contact_count > aor->max_contacts) {
725                         /* Remove excess existing contacts that expire the soonest */
726                         remove_excess_contacts(contacts, contact_count - aor->max_contacts);
727                 }
728         }
729
730         /* Re-retrieve contacts.  Caller will clean up the original container. */
731         contacts = ast_sip_location_retrieve_aor_contacts_nolock(aor);
732         if (!contacts) {
733                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
734                 return PJ_TRUE;
735         }
736         response_contact = ao2_callback(contacts, 0, NULL, NULL);
737
738         /* Send a response containing all of the contacts (including static) that are present on this AOR */
739         if (ast_sip_create_response(rdata, 200, response_contact, &tdata) != PJ_SUCCESS) {
740                 ao2_cleanup(response_contact);
741                 ao2_cleanup(contacts);
742                 return PJ_TRUE;
743         }
744         ao2_cleanup(response_contact);
745
746         /* Add the date header to the response, some UAs use this to set their date and time */
747         registrar_add_date_header(tdata);
748
749         ao2_callback(contacts, 0, registrar_add_contact, tdata);
750         ao2_cleanup(contacts);
751
752         if ((expires_hdr = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_EXPIRES, NULL))) {
753                 expires_hdr = pjsip_expires_hdr_create(tdata->pool, registrar_get_expiration(aor, NULL, rdata));
754                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)expires_hdr);
755         }
756
757         ast_sip_send_stateful_response(rdata, tdata, endpoint);
758
759         return PJ_TRUE;
760 }
761
762 static int register_aor(pjsip_rx_data *rdata,
763         struct ast_sip_endpoint *endpoint,
764         struct ast_sip_aor *aor,
765         const char *aor_name)
766 {
767         int res;
768         struct ao2_container *contacts = NULL;
769
770         ao2_lock(aor);
771         contacts = ast_sip_location_retrieve_aor_contacts_nolock(aor);
772         if (!contacts) {
773                 ao2_unlock(aor);
774                 return PJ_TRUE;
775         }
776
777         res = register_aor_core(rdata, endpoint, aor, aor_name, contacts);
778         ao2_cleanup(contacts);
779         ao2_unlock(aor);
780
781         return res;
782 }
783
784 static int match_aor(const char *aor_name, const char *id)
785 {
786         if (ast_strlen_zero(aor_name)) {
787                 return 0;
788         }
789
790         if (!strcmp(aor_name, id)) {
791                 ast_debug(3, "Matched id '%s' to aor '%s'\n", id, aor_name);
792                 return 1;
793         }
794
795         return 0;
796 }
797
798 static char *find_aor_name(const char *username, const char *domain, const char *aors)
799 {
800         char *configured_aors;
801         char *aors_buf;
802         char *aor_name;
803         char *id_domain;
804         struct ast_sip_domain_alias *alias;
805
806         id_domain = ast_alloca(strlen(username) + strlen(domain) + 2);
807         sprintf(id_domain, "%s@%s", username, domain);
808
809         aors_buf = ast_strdupa(aors);
810
811         /* Look for exact match on username@domain */
812         configured_aors = aors_buf;
813         while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
814                 if (match_aor(aor_name, id_domain)) {
815                         return ast_strdup(aor_name);
816                 }
817         }
818
819         /* If there's a domain alias, look for exact match on username@domain_alias */
820         alias = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "domain_alias", domain);
821         if (alias) {
822                 char *id_domain_alias = ast_alloca(strlen(username) + strlen(alias->domain) + 2);
823
824                 sprintf(id_domain, "%s@%s", username, alias->domain);
825                 ao2_cleanup(alias);
826
827                 configured_aors = strcpy(aors_buf, aors);/* Safe */
828                 while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
829                         if (match_aor(aor_name, id_domain_alias)) {
830                                 return ast_strdup(aor_name);
831                         }
832                 }
833         }
834
835         if (ast_strlen_zero(username)) {
836                 /* No username, no match */
837                 return NULL;
838         }
839
840         /* Look for exact match on username only */
841         configured_aors = strcpy(aors_buf, aors);/* Safe */
842         while ((aor_name = ast_strip(strsep(&configured_aors, ",")))) {
843                 if (match_aor(aor_name, username)) {
844                         return ast_strdup(aor_name);
845                 }
846         }
847
848         return NULL;
849 }
850
851 static struct ast_sip_aor *find_registrar_aor(struct pjsip_rx_data *rdata, struct ast_sip_endpoint *endpoint)
852 {
853         struct ast_sip_aor *aor = NULL;
854         char *aor_name = NULL;
855         char *domain_name;
856         char *username = NULL;
857         int i;
858
859         for (i = 0; i < AST_VECTOR_SIZE(&endpoint->ident_method_order); ++i) {
860                 pjsip_sip_uri *uri;
861                 pjsip_authorization_hdr *header = NULL;
862
863                 switch (AST_VECTOR_GET(&endpoint->ident_method_order, i)) {
864                 case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME:
865                         uri = pjsip_uri_get_uri(rdata->msg_info.to->uri);
866
867                         domain_name = ast_alloca(uri->host.slen + 1);
868                         ast_copy_pj_str(domain_name, &uri->host, uri->host.slen + 1);
869                         username = ast_alloca(uri->user.slen + 1);
870                         ast_copy_pj_str(username, &uri->user, uri->user.slen + 1);
871
872                         /*
873                          * We may want to match without any user options getting
874                          * in the way.
875                          */
876                         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(username);
877
878                         aor_name = find_aor_name(username, domain_name, endpoint->aors);
879                         if (aor_name) {
880                                 ast_debug(3, "Matched aor '%s' by To username\n", aor_name);
881                         }
882                         break;
883                 case AST_SIP_ENDPOINT_IDENTIFY_BY_AUTH_USERNAME:
884                         while ((header = pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_AUTHORIZATION,
885                                 header ? header->next : NULL))) {
886                                 if (header && !pj_stricmp2(&header->scheme, "digest")) {
887                                         username = ast_alloca(header->credential.digest.username.slen + 1);
888                                         ast_copy_pj_str(username, &header->credential.digest.username, header->credential.digest.username.slen + 1);
889                                         domain_name = ast_alloca(header->credential.digest.realm.slen + 1);
890                                         ast_copy_pj_str(domain_name, &header->credential.digest.realm, header->credential.digest.realm.slen + 1);
891
892                                         aor_name = find_aor_name(username, domain_name, endpoint->aors);
893                                         if (aor_name) {
894                                                 ast_debug(3, "Matched aor '%s' by Authentication username\n", aor_name);
895                                                 break;
896                                         }
897                                 }
898                         }
899                         break;
900                 default:
901                         continue;
902                 }
903
904                 if (aor_name) {
905                         break;
906                 }
907         }
908
909         if (ast_strlen_zero(aor_name) || !(aor = ast_sip_location_retrieve_aor(aor_name))) {
910                 /* The provided AOR name was not found (be it within the configuration or sorcery itself) */
911                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 404, NULL, NULL, NULL);
912                 ast_sip_report_req_no_support(endpoint, rdata, "registrar_requested_aor_not_found");
913                 ast_log(LOG_WARNING, "AOR '%s' not found for endpoint '%s'\n",
914                         username ?: "", ast_sorcery_object_get_id(endpoint));
915         }
916         ast_free(aor_name);
917         return aor;
918 }
919
920 static pj_bool_t registrar_on_rx_request(struct pjsip_rx_data *rdata)
921 {
922         RAII_VAR(struct ast_sip_endpoint *, endpoint,
923                  ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
924         struct ast_sip_aor *aor;
925         const char *aor_name;
926
927         if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_register_method) || !endpoint) {
928                 return PJ_FALSE;
929         }
930
931         if (ast_strlen_zero(endpoint->aors)) {
932                 /* Short circuit early if the endpoint has no AORs configured on it, which means no registration possible */
933                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
934                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_attempt_without_configured_aors");
935                 ast_log(LOG_WARNING, "Endpoint '%s' has no configured AORs\n", ast_sorcery_object_get_id(endpoint));
936                 return PJ_TRUE;
937         }
938
939         if (!PJSIP_URI_SCHEME_IS_SIP(rdata->msg_info.to->uri) && !PJSIP_URI_SCHEME_IS_SIPS(rdata->msg_info.to->uri)) {
940                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 416, NULL, NULL, NULL);
941                 ast_sip_report_failed_acl(endpoint, rdata, "registrar_invalid_uri_in_to_received");
942                 ast_log(LOG_WARNING, "Endpoint '%s' attempted to register to an AOR with a non-SIP URI\n", ast_sorcery_object_get_id(endpoint));
943                 return PJ_TRUE;
944         }
945
946         aor = find_registrar_aor(rdata, endpoint);
947         if (!aor) {
948                 /* We've already responded about not finding an AOR. */
949                 return PJ_TRUE;
950         }
951
952         aor_name = ast_sorcery_object_get_id(aor);
953
954         if (!aor->max_contacts) {
955                 /* Registration is not permitted for this AOR */
956                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 403, NULL, NULL, NULL);
957                 ast_sip_report_req_no_support(endpoint, rdata, "registrar_attempt_without_registration_permitted");
958                 ast_log(LOG_WARNING, "AOR '%s' has no configured max_contacts. Endpoint '%s' unable to register\n",
959                         aor_name, ast_sorcery_object_get_id(endpoint));
960         } else {
961                 register_aor(rdata, endpoint, aor, aor_name);
962         }
963         ao2_ref(aor, -1);
964         return PJ_TRUE;
965 }
966
967 /* function pointer to callback needs to be within the module
968    in order to avoid problems with an undefined symbol */
969 static int sip_contact_to_str(void *acp, void *arg, int flags)
970 {
971         return ast_sip_contact_to_str(acp, arg, flags);
972 }
973
974 static int ami_registrations_aor(void *obj, void *arg, int flags)
975 {
976         struct ast_sip_aor *aor = obj;
977         struct ast_sip_ami *ami = arg;
978         int *count = ami->arg;
979         RAII_VAR(struct ast_str *, buf,
980                  ast_sip_create_ami_event("InboundRegistrationDetail", ami), ast_free);
981
982         if (!buf) {
983                 return -1;
984         }
985
986         ast_sip_sorcery_object_to_ami(aor, &buf);
987         ast_str_append(&buf, 0, "Contacts: ");
988         ast_sip_for_each_contact(aor, sip_contact_to_str, &buf);
989         ast_str_append(&buf, 0, "\r\n");
990
991         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
992         (*count)++;
993         return 0;
994 }
995
996 static int ami_registrations_endpoint(void *obj, void *arg, int flags)
997 {
998         struct ast_sip_endpoint *endpoint = obj;
999         return ast_sip_for_each_aor(
1000                 endpoint->aors, ami_registrations_aor, arg);
1001 }
1002
1003 static int ami_registrations_endpoints(void *arg)
1004 {
1005         RAII_VAR(struct ao2_container *, endpoints,
1006                  ast_sip_get_endpoints(), ao2_cleanup);
1007
1008         if (!endpoints) {
1009                 return 0;
1010         }
1011
1012         ao2_callback(endpoints, OBJ_NODATA, ami_registrations_endpoint, arg);
1013         return 0;
1014 }
1015
1016 static int ami_show_registrations(struct mansession *s, const struct message *m)
1017 {
1018         int count = 0;
1019         struct ast_sip_ami ami = { .s = s, .m = m, .arg = &count, .action_id = astman_get_header(m, "ActionID"), };
1020
1021         astman_send_listack(s, m, "Following are Events for each Inbound registration",
1022                 "start");
1023
1024         ami_registrations_endpoints(&ami);
1025
1026         astman_send_list_complete_start(s, m, "InboundRegistrationDetailComplete", count);
1027         astman_send_list_complete_end(s);
1028         return 0;
1029 }
1030
1031 static int ami_show_registration_contact_statuses(struct mansession *s, const struct message *m)
1032 {
1033         int count = 0;
1034         struct ast_sip_ami ami = { .s = s, .m = m, .arg = NULL, .action_id = astman_get_header(m, "ActionID"), };
1035         struct ao2_container *contacts = ast_sorcery_retrieve_by_fields(
1036                 ast_sip_get_sorcery(), "contact", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1037         struct ao2_iterator i;
1038         struct ast_sip_contact *contact;
1039
1040         astman_send_listack(s, m, "Following are ContactStatusEvents for each Inbound "
1041                             "registration", "start");
1042
1043         if (contacts) {
1044                 i = ao2_iterator_init(contacts, 0);
1045                 while ((contact = ao2_iterator_next(&i))) {
1046                         struct ast_sip_contact_wrapper wrapper;
1047
1048                         wrapper.aor_id = (char *)contact->aor;
1049                         wrapper.contact = contact;
1050                         wrapper.contact_id = (char *)ast_sorcery_object_get_id(contact);
1051
1052                         ast_sip_format_contact_ami(&wrapper, &ami, 0);
1053                         count++;
1054
1055                         ao2_ref(contact, -1);
1056                 }
1057                 ao2_iterator_destroy(&i);
1058                 ao2_ref(contacts, -1);
1059         }
1060
1061         astman_send_list_complete_start(s, m, "ContactStatusDetailComplete", count);
1062         astman_send_list_complete_end(s);
1063         return 0;
1064 }
1065
1066 #define AMI_SHOW_REGISTRATION_CONTACT_STATUSES "PJSIPShowRegistrationInboundContactStatuses"
1067 #define AMI_SHOW_REGISTRATIONS "PJSIPShowRegistrationsInbound"
1068
1069 static pjsip_module registrar_module = {
1070         .name = { "Registrar", 9 },
1071         .id = -1,
1072         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1073         .on_rx_request = registrar_on_rx_request,
1074 };
1075
1076 static int load_module(void)
1077 {
1078         const pj_str_t STR_REGISTER = { "REGISTER", 8 };
1079
1080         CHECK_PJPROJECT_MODULE_LOADED();
1081
1082         ast_pjproject_get_buildopt("PJ_MAX_HOSTNAME", "%d", &pj_max_hostname);
1083         /* As of pjproject 2.4.5, PJSIP_MAX_URL_SIZE isn't exposed yet but we try anyway. */
1084         ast_pjproject_get_buildopt("PJSIP_MAX_URL_SIZE", "%d", &pjsip_max_url_size);
1085
1086         CHECK_PJSIP_MODULE_LOADED();
1087
1088         if (ast_sip_register_service(&registrar_module)) {
1089                 return AST_MODULE_LOAD_DECLINE;
1090         }
1091
1092         if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW, NULL, 1, &STR_REGISTER) != PJ_SUCCESS) {
1093                 ast_sip_unregister_service(&registrar_module);
1094                 return AST_MODULE_LOAD_DECLINE;
1095         }
1096
1097         ast_manager_register_xml(AMI_SHOW_REGISTRATIONS, EVENT_FLAG_SYSTEM,
1098                                  ami_show_registrations);
1099         ast_manager_register_xml(AMI_SHOW_REGISTRATION_CONTACT_STATUSES, EVENT_FLAG_SYSTEM,
1100                                  ami_show_registration_contact_statuses);
1101
1102         return AST_MODULE_LOAD_SUCCESS;
1103 }
1104
1105 static int unload_module(void)
1106 {
1107         ast_manager_unregister(AMI_SHOW_REGISTRATIONS);
1108         ast_manager_unregister(AMI_SHOW_REGISTRATION_CONTACT_STATUSES);
1109         ast_sip_unregister_service(&registrar_module);
1110         ast_sip_transport_monitor_unregister_all(register_contact_transport_shutdown_cb);
1111         return 0;
1112 }
1113
1114 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Registrar Support",
1115         .support_level = AST_MODULE_SUPPORT_CORE,
1116         .load = load_module,
1117         .unload = unload_module,
1118         .load_pri = AST_MODPRI_CHANNEL_DEPEND - 3,
1119 );