Fixes for OS X
[asterisk/asterisk.git] / res / res_pjsip / pjsip_options.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Matt Jordan <mjordan@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 #include "asterisk.h"
20
21 #include <pjsip.h>
22 #include <pjsip_ua.h>
23 #include <pjlib.h>
24
25 #include "asterisk/res_pjsip.h"
26 #include "asterisk/channel.h"
27 #include "asterisk/pbx.h"
28 #include "asterisk/astobj2.h"
29 #include "asterisk/cli.h"
30 #include "asterisk/time.h"
31 #include "asterisk/test.h"
32 #include "include/res_pjsip_private.h"
33
34 #define DEFAULT_LANGUAGE "en"
35 #define DEFAULT_ENCODING "text/plain"
36 #define QUALIFIED_BUCKETS 211
37
38 static const char *status_map [] = {
39         [UNAVAILABLE] = "Unreachable",
40         [AVAILABLE] = "Reachable",
41         [UNKNOWN] = "Unknown",
42         [CREATED] = "Created",
43         [REMOVED] = "Removed",
44
45 };
46
47 static const char *short_status_map [] = {
48         [UNAVAILABLE] = "Unavail",
49         [AVAILABLE] = "Avail",
50         [UNKNOWN] = "Unknown",
51         [CREATED] = "Created",
52         [REMOVED] = "Removed",
53 };
54
55 const char *ast_sip_get_contact_status_label(const enum ast_sip_contact_status_type status)
56 {
57         return status_map[status];
58 }
59
60 const char *ast_sip_get_contact_short_status_label(const enum ast_sip_contact_status_type status)
61 {
62         return short_status_map[status];
63 }
64
65 /*!
66  * \internal
67  * \brief Create a ast_sip_contact_status object.
68  */
69 static void *contact_status_alloc(const char *name)
70 {
71         struct ast_sip_contact_status *status = ast_sorcery_generic_alloc(sizeof(*status), NULL);
72
73         if (!status) {
74                 ast_log(LOG_ERROR, "Unable to allocate ast_sip_contact_status\n");
75                 return NULL;
76         }
77
78         status->status = UNKNOWN;
79
80         return status;
81 }
82
83 /*!
84  * \brief Retrieve a ast_sip_contact_status object from sorcery creating
85  *        one if not found.
86  */
87 struct ast_sip_contact_status *ast_res_pjsip_find_or_create_contact_status(const struct ast_sip_contact *contact)
88 {
89         struct ast_sip_contact_status *status;
90
91         status = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), CONTACT_STATUS,
92                 ast_sorcery_object_get_id(contact));
93         if (status) {
94                 return status;
95         }
96
97         status = ast_sorcery_alloc(ast_sip_get_sorcery(), CONTACT_STATUS,
98                 ast_sorcery_object_get_id(contact));
99         if (!status) {
100                 ast_log(LOG_ERROR, "Unable to create ast_sip_contact_status for contact %s\n",
101                         contact->uri);
102                 return NULL;
103         }
104
105         status->status = UNKNOWN;
106         status->rtt_start = ast_tv(0, 0);
107         status->rtt = 0;
108
109         if (ast_sorcery_create(ast_sip_get_sorcery(), status)) {
110                 ast_log(LOG_ERROR, "Unable to persist ast_sip_contact_status for contact %s\n",
111                         contact->uri);
112                 ao2_ref(status, -1);
113                 return NULL;
114         }
115
116         return status;
117 }
118
119 /*!
120  * \internal
121  * \brief Update an ast_sip_contact_status's elements.
122  */
123 static void update_contact_status(const struct ast_sip_contact *contact,
124         enum ast_sip_contact_status_type value)
125 {
126         struct ast_sip_contact_status *status;
127         struct ast_sip_contact_status *update;
128
129         status = ast_res_pjsip_find_or_create_contact_status(contact);
130         if (!status) {
131                 ast_log(LOG_ERROR, "Unable to find ast_sip_contact_status for contact %s\n",
132                         contact->uri);
133                 return;
134         }
135
136         update = ast_sorcery_alloc(ast_sip_get_sorcery(), CONTACT_STATUS,
137                 ast_sorcery_object_get_id(status));
138         if (!update) {
139                 ast_log(LOG_ERROR, "Unable to allocate ast_sip_contact_status for contact %s\n",
140                         contact->uri);
141                 return;
142         }
143
144         update->last_status = status->status;
145         update->status = value;
146
147         /* if the contact is available calculate the rtt as
148            the diff between the last start time and "now" */
149         update->rtt = update->status == AVAILABLE && status->rtt_start.tv_sec > 0 ?
150                 ast_tvdiff_us(ast_tvnow(), status->rtt_start) : 0;
151
152         update->rtt_start = ast_tv(0, 0);
153
154         ast_test_suite_event_notify("AOR_CONTACT_QUALIFY_RESULT",
155                 "Contact: %s\r\n"
156                         "Status: %s\r\n"
157                         "RTT: %" PRId64,
158                 ast_sorcery_object_get_id(update),
159                 ast_sip_get_contact_status_label(update->status),
160                 update->rtt);
161
162         if (ast_sorcery_update(ast_sip_get_sorcery(), update)) {
163                 ast_log(LOG_ERROR, "Unable to update ast_sip_contact_status for contact %s\n",
164                         contact->uri);
165         }
166
167         ao2_ref(status, -1);
168         ao2_ref(update, -1);
169 }
170
171 /*!
172  * \internal
173  * \brief Initialize the start time on a contact status so the round
174  *        trip time can be calculated upon a valid response.
175  */
176 static void init_start_time(const struct ast_sip_contact *contact)
177 {
178         struct ast_sip_contact_status *status;
179         struct ast_sip_contact_status *update;
180
181         status = ast_res_pjsip_find_or_create_contact_status(contact);
182         if (!status) {
183                 ast_log(LOG_ERROR, "Unable to find ast_sip_contact_status for contact %s\n",
184                         contact->uri);
185                 return;
186         }
187
188         update = ast_sorcery_alloc(ast_sip_get_sorcery(), CONTACT_STATUS,
189                 ast_sorcery_object_get_id(status));
190         if (!update) {
191                 ast_log(LOG_ERROR, "Unable to copy ast_sip_contact_status for contact %s\n",
192                         contact->uri);
193                 return;
194         }
195
196         update->status = status->status;
197         update->last_status = status->last_status;
198         update->rtt = status->rtt;
199         update->rtt_start = ast_tvnow();
200
201         if (ast_sorcery_update(ast_sip_get_sorcery(), update)) {
202                 ast_log(LOG_ERROR, "Unable to update ast_sip_contact_status for contact %s\n",
203                         contact->uri);
204         }
205
206         ao2_ref(status, -1);
207         ao2_ref(update, -1);
208 }
209
210 /*!
211  * \internal
212  * \brief Match a container contact object with the contact sorcery id looking for.
213  *
214  * \param obj pointer to the (user-defined part) of an object.
215  * \param arg callback argument from ao2_callback()
216  * \param flags flags from ao2_callback()
217  *
218  * \return Values are a combination of enum _cb_results.
219  */
220 static int match_contact_id(void *obj, void *arg, int flags)
221 {
222         struct ast_sip_contact *contact = obj;
223         const char *looking_for = arg;
224
225         return strcmp(ast_sorcery_object_get_id(contact), looking_for) ? 0 : CMP_MATCH;
226 }
227
228 /*!
229  * \internal
230  * \brief For an endpoint try to match the given contact sorcery id.
231  */
232 static int on_endpoint(void *obj, void *arg, int flags)
233 {
234         struct ast_sip_endpoint *endpoint = obj;
235         struct ast_sip_contact *contact;
236         char *looking_for = arg;
237         char *aor_name;
238         char *aors;
239
240         if (!arg || ast_strlen_zero(endpoint->aors)) {
241                 return 0;
242         }
243
244         aors = ast_strdupa(endpoint->aors);
245         while ((aor_name = strsep(&aors, ","))) {
246                 struct ast_sip_aor *aor;
247                 struct ao2_container *contacts;
248
249                 aor = ast_sip_location_retrieve_aor(aor_name);
250                 if (!aor) {
251                         continue;
252                 }
253
254                 contacts = ast_sip_location_retrieve_aor_contacts(aor);
255                 ao2_ref(aor, -1);
256                 if (!contacts) {
257                         continue;
258                 }
259
260                 contact = ao2_callback(contacts, 0, match_contact_id, looking_for);
261                 ao2_ref(contacts, -1);
262                 if (contact) {
263                         ao2_ref(contact, -1);
264                         return CMP_MATCH;
265                 }
266         }
267
268         return 0;
269 }
270
271 /*!
272  * \internal
273  * \brief Find an endpoint associated with the given contact.
274  */
275 static struct ast_sip_endpoint *find_an_endpoint(struct ast_sip_contact *contact)
276 {
277         char *looking_for = (char *) ast_sorcery_object_get_id(contact);
278         struct ao2_container *endpoints = ast_sip_get_endpoints();
279         struct ast_sip_endpoint *endpoint;
280
281         endpoint = ao2_callback(endpoints, 0, on_endpoint, looking_for);
282         ao2_ref(endpoints, -1);
283         return endpoint;
284 }
285
286 /*!
287  * \internal
288  * \brief Receive a response to the qualify contact request.
289  */
290 static void qualify_contact_cb(void *token, pjsip_event *e)
291 {
292         struct ast_sip_contact *contact = token;
293
294         switch(e->body.tsx_state.type) {
295         default:
296                 ast_log(LOG_ERROR, "Unexpected PJSIP event %u\n", e->body.tsx_state.type);
297                 /* Fall through */
298         case PJSIP_EVENT_TRANSPORT_ERROR:
299         case PJSIP_EVENT_TIMER:
300                 update_contact_status(contact, UNAVAILABLE);
301                 break;
302         case PJSIP_EVENT_RX_MSG:
303                 update_contact_status(contact, AVAILABLE);
304                 break;
305         }
306         ao2_cleanup(contact);
307 }
308
309 /*!
310  * \internal
311  * \brief Attempt to qualify the contact
312  *
313  * \details Sends a SIP OPTIONS request to the given contact in order to make
314  *         sure that contact is available.
315  */
316 static int qualify_contact(struct ast_sip_endpoint *endpoint, struct ast_sip_contact *contact)
317 {
318         pjsip_tx_data *tdata;
319         RAII_VAR(struct ast_sip_endpoint *, endpoint_local, NULL, ao2_cleanup);
320
321         if (contact->authenticate_qualify) {
322                 endpoint_local = ao2_bump(endpoint);
323                 if (!endpoint_local) {
324                         /*
325                          * Find the "first" endpoint to completely qualify the contact - any
326                          * endpoint that is associated with the contact should do.
327                          */
328                         endpoint_local = find_an_endpoint(contact);
329                         if (!endpoint_local) {
330                                 ast_log(LOG_ERROR, "Unable to find an endpoint to qualify contact %s\n",
331                                         contact->uri);
332                                 return -1;
333                         }
334                 }
335         }
336
337         if (ast_sip_create_request("OPTIONS", NULL, NULL, NULL, contact, &tdata)) {
338                 ast_log(LOG_ERROR, "Unable to create request to qualify contact %s\n",
339                         contact->uri);
340                 return -1;
341         }
342
343         /* If an outbound proxy is specified set it on this request */
344         if (!ast_strlen_zero(contact->outbound_proxy) &&
345                 ast_sip_set_outbound_proxy(tdata, contact->outbound_proxy)) {
346                 pjsip_tx_data_dec_ref(tdata);
347                 ast_log(LOG_ERROR, "Unable to apply outbound proxy on request to qualify contact %s\n",
348                         contact->uri);
349                 return -1;
350         }
351
352         init_start_time(contact);
353
354         ao2_ref(contact, +1);
355         if (ast_sip_send_out_of_dialog_request(tdata, endpoint_local, (int)(contact->qualify_timeout * 1000), contact, qualify_contact_cb)
356                 != PJ_SUCCESS) {
357                 ast_log(LOG_ERROR, "Unable to send request to qualify contact %s\n",
358                         contact->uri);
359                 update_contact_status(contact, UNAVAILABLE);
360                 ao2_ref(contact, -1);
361                 return -1;
362         }
363
364         return 0;
365 }
366
367 /*!
368  * \internal
369  * \brief Scheduling context for sending QUALIFY request at specified intervals.
370  */
371 static struct ast_sched_context *sched;
372
373 /*!
374  * \internal
375  * \brief Container to hold all actively scheduled qualifies.
376  */
377 static struct ao2_container *sched_qualifies;
378
379 /*!
380  * \internal
381  * \brief Structure to hold qualify contact scheduling information.
382  */
383 struct sched_data {
384         /*! The scheduling id */
385         int id;
386         /*! The the contact being checked */
387         struct ast_sip_contact *contact;
388 };
389
390 /*!
391  * \internal
392  * \brief Destroy the scheduled data and remove from scheduler.
393  */
394 static void sched_data_destructor(void *obj)
395 {
396         struct sched_data *data = obj;
397
398         ao2_cleanup(data->contact);
399 }
400 /*!
401  * \internal
402  * \brief Create the scheduling data object.
403  */
404 static struct sched_data *sched_data_create(struct ast_sip_contact *contact)
405 {
406         struct sched_data *data;
407
408         data = ao2_t_alloc(sizeof(*data), sched_data_destructor, contact->uri);
409         if (!data) {
410                 ast_log(LOG_ERROR, "Unable to create schedule qualify data for contact %s\n",
411                         contact->uri);
412                 return NULL;
413         }
414
415         data->contact = contact;
416         ao2_ref(data->contact, +1);
417
418         return data;
419 }
420
421 /*!
422  * \internal
423  * \brief Send a qualify contact request within a threaded task.
424  */
425 static int qualify_contact_task(void *obj)
426 {
427         struct ast_sip_contact *contact = obj;
428         int res;
429
430         res = qualify_contact(NULL, contact);
431         ao2_ref(contact, -1);
432         return res;
433 }
434
435 /*!
436  * \internal
437  * \brief Send a scheduled qualify contact request.
438  */
439 static int qualify_contact_sched(const void *obj)
440 {
441         struct sched_data *data = (struct sched_data *) obj;
442
443         ao2_ref(data->contact, +1);
444         if (ast_sip_push_task(NULL, qualify_contact_task, data->contact)) {
445                 ao2_ref(data->contact, -1);
446         }
447
448         /*
449          * Always reschedule rather than have a potential race cleaning
450          * up the data object ref between self deletion and an external
451          * deletion.
452          */
453         return data->contact->qualify_frequency * 1000;
454 }
455
456 /*!
457  * \internal
458  * \brief Set up a scheduled qualify contact check.
459  */
460 static void schedule_qualify(struct ast_sip_contact *contact, int initial_interval)
461 {
462         struct sched_data *data;
463
464         data = sched_data_create(contact);
465         if (!data) {
466                 return;
467         }
468
469         ast_assert(contact->qualify_frequency != 0);
470
471         ao2_t_ref(data, +1, "Ref for qualify_contact_sched() scheduler entry");
472         data->id = ast_sched_add_variable(sched, initial_interval,
473                 qualify_contact_sched, data, 1);
474         if (data->id < 0) {
475                 ao2_t_ref(data, -1, "Cleanup failed scheduler add");
476                 ast_log(LOG_ERROR, "Unable to schedule qualify for contact %s\n",
477                         contact->uri);
478         } else if (!ao2_link(sched_qualifies, data)) {
479                 AST_SCHED_DEL_UNREF(sched, data->id,
480                         ao2_t_ref(data, -1, "Cleanup scheduler for failed ao2_link"));
481         }
482         ao2_t_ref(data, -1, "Done setting up scheduler entry");
483 }
484
485 /*!
486  * \internal
487  * \brief Remove the contact from the scheduler.
488  */
489 static void unschedule_qualify(struct ast_sip_contact *contact)
490 {
491         struct sched_data *data;
492
493         data = ao2_find(sched_qualifies, contact, OBJ_UNLINK | OBJ_SEARCH_KEY);
494         if (!data) {
495                 return;
496         }
497
498         AST_SCHED_DEL_UNREF(sched, data->id,
499                 ao2_t_ref(data, -1, "Delete scheduler entry ref"));
500         ao2_t_ref(data, -1, "Done with ao2_find ref");
501 }
502
503 /*!
504  * \internal
505  * \brief Qualify the given contact and set up scheduling if configured.
506  */
507 static void qualify_and_schedule(struct ast_sip_contact *contact)
508 {
509         unschedule_qualify(contact);
510
511         if (contact->qualify_frequency) {
512                 ao2_ref(contact, +1);
513                 if (ast_sip_push_task(NULL, qualify_contact_task, contact)) {
514                         ao2_ref(contact, -1);
515                 }
516
517                 schedule_qualify(contact, contact->qualify_frequency * 1000);
518         } else {
519                 update_contact_status(contact, UNKNOWN);
520         }
521 }
522
523 /*!
524  * \internal
525  * \brief A new contact has been created make sure it is available.
526  */
527 static void contact_created(const void *obj)
528 {
529         qualify_and_schedule((struct ast_sip_contact *) obj);
530 }
531
532 /*!
533  * \internal
534  * \brief A contact has been deleted remove status tracking.
535  */
536 static void contact_deleted(const void *obj)
537 {
538         struct ast_sip_contact *contact = (struct ast_sip_contact *) obj;
539         struct ast_sip_contact_status *status;
540
541         unschedule_qualify(contact);
542
543         status = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), CONTACT_STATUS,
544                 ast_sorcery_object_get_id(contact));
545         if (!status) {
546                 return;
547         }
548
549         if (ast_sorcery_delete(ast_sip_get_sorcery(), status)) {
550                 ast_log(LOG_ERROR, "Unable to delete ast_sip_contact_status for contact %s\n",
551                         contact->uri);
552         }
553         ao2_ref(status, -1);
554 }
555
556 static const struct ast_sorcery_observer contact_observer = {
557         .created = contact_created,
558         .deleted = contact_deleted
559 };
560
561 static pj_bool_t options_start(void)
562 {
563         sched = ast_sched_context_create();
564         if (!sched) {
565                 return -1;
566         }
567         if (ast_sched_start_thread(sched)) {
568                 ast_sched_context_destroy(sched);
569                 sched = NULL;
570                 return -1;
571         }
572
573         if (ast_sorcery_observer_add(ast_sip_get_sorcery(), "contact", &contact_observer)) {
574                 ast_log(LOG_WARNING, "Unable to add contact observer\n");
575                 ast_sched_context_destroy(sched);
576                 sched = NULL;
577                 return -1;
578         }
579
580         return PJ_SUCCESS;
581 }
582
583 static int sched_qualifies_empty(void *obj, void *arg, int flags)
584 {
585         ao2_t_ref(obj, -1, "Release ref held by destroyed scheduler context.");
586         return CMP_MATCH;
587 }
588
589 static pj_bool_t options_stop(void)
590 {
591         ast_sorcery_observer_remove(ast_sip_get_sorcery(), "contact", &contact_observer);
592
593         if (sched) {
594                 ast_sched_context_destroy(sched);
595                 sched = NULL;
596         }
597
598         /* Empty the container of scheduling data refs. */
599         ao2_callback(sched_qualifies, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
600                 sched_qualifies_empty, NULL);
601
602         return PJ_SUCCESS;
603 }
604
605 static pj_status_t send_options_response(pjsip_rx_data *rdata, int code)
606 {
607         pjsip_endpoint *endpt = ast_sip_get_pjsip_endpoint();
608         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
609         pjsip_transaction *trans = pjsip_rdata_get_tsx(rdata);
610         pjsip_tx_data *tdata;
611         const pjsip_hdr *hdr;
612         pj_status_t status;
613
614         /* Make the response object */
615         if ((status = ast_sip_create_response(rdata, code, NULL, &tdata) != PJ_SUCCESS)) {
616                 ast_log(LOG_ERROR, "Unable to create response (%d)\n", status);
617                 return status;
618         }
619
620         /* Add appropriate headers */
621         if ((hdr = pjsip_endpt_get_capability(endpt, PJSIP_H_ACCEPT, NULL))) {
622                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr));
623         }
624         if ((hdr = pjsip_endpt_get_capability(endpt, PJSIP_H_ALLOW, NULL))) {
625                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr));
626         }
627         if ((hdr = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, NULL))) {
628                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr));
629         }
630
631         /*
632          * XXX TODO: pjsip doesn't care a lot about either of these headers -
633          * while it provides specific methods to create them, they are defined
634          * to be the standard string header creation. We never did add them
635          * in chan_sip, although RFC 3261 says they SHOULD. Hard coded here.
636          */
637         ast_sip_add_header(tdata, "Accept-Encoding", DEFAULT_ENCODING);
638         ast_sip_add_header(tdata, "Accept-Language", DEFAULT_LANGUAGE);
639
640         if (dlg && trans) {
641                 status = pjsip_dlg_send_response(dlg, trans, tdata);
642         } else {
643                 struct ast_sip_endpoint *endpoint;
644
645                 endpoint = ast_pjsip_rdata_get_endpoint(rdata);
646                 status = ast_sip_send_stateful_response(rdata, tdata, endpoint);
647                 ao2_cleanup(endpoint);
648         }
649
650         if (status != PJ_SUCCESS) {
651                 ast_log(LOG_ERROR, "Unable to send response (%d)\n", status);
652         }
653
654         return status;
655 }
656
657 static pj_bool_t options_on_rx_request(pjsip_rx_data *rdata)
658 {
659         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
660         pjsip_uri *ruri;
661         pjsip_sip_uri *sip_ruri;
662         char exten[AST_MAX_EXTENSION];
663
664         if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method,
665                              &pjsip_options_method)) {
666                 return PJ_FALSE;
667         }
668
669         if (!(endpoint = ast_pjsip_rdata_get_endpoint(rdata))) {
670                 return PJ_FALSE;
671         }
672
673         ruri = rdata->msg_info.msg->line.req.uri;
674         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
675                 send_options_response(rdata, 416);
676                 return PJ_TRUE;
677         }
678
679         sip_ruri = pjsip_uri_get_uri(ruri);
680         ast_copy_pj_str(exten, &sip_ruri->user, sizeof(exten));
681
682         if (ast_shutting_down()) {
683                 /*
684                  * Not taking any new calls at this time.
685                  * Likely a server availability OPTIONS poll.
686                  */
687                 send_options_response(rdata, 503);
688         } else if (!ast_strlen_zero(exten) && !ast_exists_extension(NULL, endpoint->context, exten, 1, NULL)) {
689                 send_options_response(rdata, 404);
690         } else {
691                 send_options_response(rdata, 200);
692         }
693         return PJ_TRUE;
694 }
695
696 static pjsip_module options_module = {
697         .name = {"Options Module", 14},
698         .id = -1,
699         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
700         .start = options_start,
701         .stop = options_stop,
702         .on_rx_request = options_on_rx_request,
703 };
704
705 /*!
706  * \internal
707  * \brief Send qualify request to the given contact.
708  */
709 static int cli_on_contact(void *obj, void *arg, void *data, int flags)
710 {
711         struct ast_sip_contact *contact = obj;
712         struct ast_sip_endpoint *endpoint = data;
713         int *cli_fd = arg;
714
715         ast_cli(*cli_fd, " contact %s\n", contact->uri);
716         qualify_contact(endpoint, contact);
717         return 0;
718 }
719
720 /*!
721  * \brief Data pushed to threadpool to qualify endpoints from the CLI
722  */
723 struct qualify_data {
724         /*! Endpoint that is being qualified */
725         struct ast_sip_endpoint *endpoint;
726         /*! CLI File descriptor for printing messages */
727         int cli_fd;
728 };
729
730 static struct qualify_data *qualify_data_alloc(struct ast_sip_endpoint *endpoint, int cli_fd)
731 {
732         struct qualify_data *qual_data;
733
734         qual_data = ast_malloc(sizeof(*qual_data));
735         if (!qual_data) {
736                 return NULL;
737         }
738
739         qual_data->endpoint = ao2_bump(endpoint);
740         qual_data->cli_fd = cli_fd;
741         return qual_data;
742 }
743
744 static void qualify_data_destroy(struct qualify_data *qual_data)
745 {
746         ao2_cleanup(qual_data->endpoint);
747         ast_free(qual_data);
748 }
749
750 /*!
751  * \internal
752  * \brief For an endpoint iterate over and qualify all aors/contacts
753  */
754 static int cli_qualify_contacts(void *data)
755 {
756         char *aors;
757         char *aor_name;
758         RAII_VAR(struct qualify_data *, qual_data, data, qualify_data_destroy);
759         struct ast_sip_endpoint *endpoint = qual_data->endpoint;
760         int cli_fd = qual_data->cli_fd;
761         const char *endpoint_name = ast_sorcery_object_get_id(endpoint);
762
763         if (ast_strlen_zero(endpoint->aors)) {
764                 ast_cli(cli_fd, "Endpoint %s has no AoR's configured\n",
765                         endpoint_name);
766                 return 0;
767         }
768
769         aors = ast_strdupa(endpoint->aors);
770         while ((aor_name = strsep(&aors, ","))) {
771                 struct ast_sip_aor *aor;
772                 struct ao2_container *contacts;
773
774                 aor = ast_sip_location_retrieve_aor(aor_name);
775                 if (!aor) {
776                         continue;
777                 }
778
779                 contacts = ast_sip_location_retrieve_aor_contacts(aor);
780                 if (contacts) {
781                         ast_cli(cli_fd, "Sending qualify to endpoint %s\n", endpoint_name);
782                         ao2_callback_data(contacts, OBJ_NODATA, cli_on_contact, &cli_fd, endpoint);
783                         ao2_ref(contacts, -1);
784                 }
785
786                 ao2_ref(aor, -1);
787         }
788         return 0;
789 }
790
791 static char *cli_qualify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
792 {
793         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
794         const char *endpoint_name;
795         struct qualify_data *qual_data;
796
797         switch (cmd) {
798         case CLI_INIT:
799                 e->command = "pjsip qualify";
800                 e->usage =
801                         "Usage: pjsip qualify <endpoint>\n"
802                         "       Send a SIP OPTIONS request to all contacts on the endpoint.\n";
803                 return NULL;
804         case CLI_GENERATE:
805                 return NULL;
806         }
807
808         if (a->argc != 3) {
809                 return CLI_SHOWUSAGE;
810         }
811
812         endpoint_name = a->argv[2];
813
814         if (!(endpoint = ast_sorcery_retrieve_by_id(
815                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
816                 ast_cli(a->fd, "Unable to retrieve endpoint %s\n", endpoint_name);
817                 return CLI_FAILURE;
818         }
819
820         qual_data = qualify_data_alloc(endpoint, a->fd);
821         if (!qual_data) {
822                 return CLI_FAILURE;
823         }
824
825         if (ast_sip_push_task(NULL, cli_qualify_contacts, qual_data)) {
826                 qualify_data_destroy(qual_data);
827                 return CLI_FAILURE;
828         }
829
830         return CLI_SUCCESS;
831 }
832
833 /*!
834  * \internal
835  * \brief Send qualify request to the given contact.
836  */
837 static int ami_contact_cb(void *obj, void *arg, int flags)
838 {
839         struct ast_sip_contact *contact = obj;
840
841         ao2_ref(contact, +1);
842         if (ast_sip_push_task(NULL, qualify_contact_task, contact)) {
843                 ao2_ref(contact, -1);
844         }
845         return 0;
846 }
847
848 static int ami_sip_qualify(struct mansession *s, const struct message *m)
849 {
850         const char *endpoint_name = astman_get_header(m, "Endpoint");
851         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
852         char *aors;
853         char *aor_name;
854
855         if (ast_strlen_zero(endpoint_name)) {
856                 astman_send_error(s, m, "Endpoint parameter missing.");
857                 return 0;
858         }
859
860         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
861                 endpoint_name);
862         if (!endpoint) {
863                 astman_send_error(s, m, "Unable to retrieve endpoint\n");
864                 return 0;
865         }
866
867         /* send a qualify for all contacts registered with the endpoint */
868         if (ast_strlen_zero(endpoint->aors)) {
869                 astman_send_error(s, m, "No AoRs configured for endpoint\n");
870                 return 0;
871         }
872
873         aors = ast_strdupa(endpoint->aors);
874         while ((aor_name = strsep(&aors, ","))) {
875                 struct ast_sip_aor *aor;
876                 struct ao2_container *contacts;
877
878                 aor = ast_sip_location_retrieve_aor(aor_name);
879                 if (!aor) {
880                         continue;
881                 }
882
883                 contacts = ast_sip_location_retrieve_aor_contacts(aor);
884                 if (contacts) {
885                         ao2_callback(contacts, OBJ_NODATA, ami_contact_cb, NULL);
886                         ao2_ref(contacts, -1);
887                 }
888
889                 ao2_ref(aor, -1);
890         }
891
892         astman_send_ack(s, m, "Endpoint found, will qualify");
893         return 0;
894 }
895
896 static struct ast_cli_entry cli_options[] = {
897         AST_CLI_DEFINE(cli_qualify, "Send an OPTIONS request to a PJSIP endpoint")
898 };
899
900 static int sched_qualifies_hash_fn(const void *obj, int flags)
901 {
902         const struct sched_data *object;
903         const struct ast_sip_contact *key;
904
905         switch (flags & OBJ_SEARCH_MASK) {
906         case OBJ_SEARCH_KEY:
907                 key = obj;
908                 break;
909         case OBJ_SEARCH_OBJECT:
910                 object = obj;
911                 key = object->contact;
912                 break;
913         default:
914                 /* Hash can only work on something with a full key. */
915                 ast_assert(0);
916                 return 0;
917         }
918         return ast_str_hash(ast_sorcery_object_get_id(key));
919 }
920
921 static int sched_qualifies_cmp_fn(void *obj, void *arg, int flags)
922 {
923         const struct sched_data *object_left = obj;
924         const struct sched_data *object_right = arg;
925         struct ast_sip_contact *right_key = arg;
926         int cmp;
927
928         switch (flags & OBJ_SEARCH_MASK) {
929         case OBJ_SEARCH_OBJECT:
930                 right_key = object_right->contact;
931                 /* Fall through */
932         case OBJ_SEARCH_KEY:
933                 cmp = strcmp(ast_sorcery_object_get_id(object_left->contact),
934                         ast_sorcery_object_get_id(right_key));
935                 break;
936         case OBJ_SEARCH_PARTIAL_KEY:
937                 /* Not supported by container. */
938                 ast_assert(0);
939                 return 0;
940         default:
941                 /*
942                  * What arg points to is specific to this traversal callback
943                  * and has no special meaning to astobj2.
944                  */
945                 cmp = 0;
946                 break;
947         }
948         if (cmp) {
949                 return 0;
950         }
951         /*
952          * At this point the traversal callback is identical to a sorted
953          * container.
954          */
955         return CMP_MATCH;
956 }
957
958 static int rtt_start_handler(const struct aco_option *opt,
959         struct ast_variable *var, void *obj)
960 {
961         struct ast_sip_contact_status *status = obj;
962         long int sec, usec;
963
964         if (sscanf(var->value, "%ld.%06ld", &sec, &usec) != 2) {
965                 return -1;
966         }
967
968         status->rtt_start = ast_tv(sec, usec);
969
970         return 0;
971 }
972
973 static int rtt_start_to_str(const void *obj, const intptr_t *args, char **buf)
974 {
975         const struct ast_sip_contact_status *status = obj;
976
977         if (ast_asprintf(buf, "%ld.%06ld", (long)status->rtt_start.tv_sec, (long)status->rtt_start.tv_usec) == -1) {
978                 return -1;
979         }
980
981         return 0;
982 }
983
984 int ast_sip_initialize_sorcery_qualify(void)
985 {
986         struct ast_sorcery *sorcery = ast_sip_get_sorcery();
987
988         /* initialize sorcery ast_sip_contact_status resource */
989         ast_sorcery_apply_default(sorcery, CONTACT_STATUS, "memory", NULL);
990
991         if (ast_sorcery_internal_object_register(sorcery, CONTACT_STATUS,
992                                         contact_status_alloc, NULL, NULL)) {
993                 ast_log(LOG_ERROR, "Unable to register ast_sip_contact_status in sorcery\n");
994                 return -1;
995         }
996
997         ast_sorcery_object_field_register_nodoc(sorcery, CONTACT_STATUS, "last_status",
998                 "0", OPT_UINT_T, 1, FLDSET(struct ast_sip_contact_status, last_status));
999         ast_sorcery_object_field_register_nodoc(sorcery, CONTACT_STATUS, "status",
1000                 "0", OPT_UINT_T, 1, FLDSET(struct ast_sip_contact_status, status));
1001         ast_sorcery_object_field_register_custom_nodoc(sorcery, CONTACT_STATUS, "rtt_start",
1002                 "0.0", rtt_start_handler, rtt_start_to_str, NULL, 0, 0);
1003         ast_sorcery_object_field_register_nodoc(sorcery, CONTACT_STATUS, "rtt",
1004                 "0", OPT_UINT_T, 1, FLDSET(struct ast_sip_contact_status, rtt));
1005
1006         return 0;
1007 }
1008
1009 static int qualify_and_schedule_cb(void *obj, void *arg, int flags)
1010 {
1011         struct ast_sip_contact *contact = obj;
1012         struct ast_sip_aor *aor = arg;
1013         int initial_interval;
1014         int max_time = ast_sip_get_max_initial_qualify_time();
1015
1016         contact->qualify_frequency = aor->qualify_frequency;
1017         contact->qualify_timeout = aor->qualify_timeout;
1018         contact->authenticate_qualify = aor->authenticate_qualify;
1019
1020         /* Delay initial qualification by a random fraction of the specified interval */
1021         if (max_time && max_time < contact->qualify_frequency) {
1022                 initial_interval = max_time;
1023         } else {
1024                 initial_interval = contact->qualify_frequency;
1025         }
1026
1027         initial_interval = (int)((initial_interval * 1000) * ast_random_double());
1028
1029         if (contact->qualify_frequency) {
1030                 schedule_qualify(contact, initial_interval);
1031         } else {
1032                 update_contact_status(contact, UNKNOWN);
1033         }
1034
1035         return 0;
1036 }
1037
1038 /*!
1039  * \internal
1040  * \brief Qualify and schedule an endpoint's contacts
1041  *
1042  * \details For the given endpoint retrieve its list of aors, qualify all
1043  *         contacts, and schedule for checks if configured.
1044  */
1045 static int qualify_and_schedule_all_cb(void *obj, void *arg, int flags)
1046 {
1047         struct ast_sip_endpoint *endpoint = obj;
1048         char *aors;
1049         char *aor_name;
1050
1051         if (ast_strlen_zero(endpoint->aors)) {
1052                 return 0;
1053         }
1054
1055         aors = ast_strdupa(endpoint->aors);
1056         while ((aor_name = strsep(&aors, ","))) {
1057                 struct ast_sip_aor *aor;
1058                 struct ao2_container *contacts;
1059
1060                 aor = ast_sip_location_retrieve_aor(aor_name);
1061                 if (!aor) {
1062                         continue;
1063                 }
1064
1065                 contacts = ast_sip_location_retrieve_aor_contacts(aor);
1066                 if (contacts) {
1067                         ao2_callback(contacts, OBJ_NODATA, qualify_and_schedule_cb, aor);
1068                         ao2_ref(contacts, -1);
1069                 }
1070
1071                 ao2_ref(aor, -1);
1072         }
1073
1074         return 0;
1075 }
1076
1077 /*!
1078  * \internal
1079  * \brief Unschedule all existing contacts
1080  */
1081 static int unschedule_all_cb(void *obj, void *arg, int flags)
1082 {
1083         struct sched_data *data = obj;
1084
1085         AST_SCHED_DEL_UNREF(sched, data->id, ao2_ref(data, -1));
1086
1087         return CMP_MATCH;
1088 }
1089
1090 static void qualify_and_schedule_all(void)
1091 {
1092         struct ao2_container *endpoints = ast_sip_get_endpoints();
1093
1094         ao2_callback(sched_qualifies, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK, unschedule_all_cb, NULL);
1095
1096         if (!endpoints) {
1097                 return;
1098         }
1099
1100         ao2_callback(endpoints, OBJ_NODATA, qualify_and_schedule_all_cb, NULL);
1101         ao2_ref(endpoints, -1);
1102 }
1103
1104 static int format_contact_status(void *obj, void *arg, int flags)
1105 {
1106         struct ast_sip_contact_wrapper *wrapper = obj;
1107         struct ast_sip_contact *contact = wrapper->contact;
1108         struct ast_sip_ami *ami = arg;
1109         struct ast_sip_contact_status *status;
1110         struct ast_str *buf;
1111         const struct ast_sip_endpoint *endpoint = ami->arg;
1112
1113         buf = ast_sip_create_ami_event("ContactStatusDetail", ami);
1114         if (!buf) {
1115                 return -1;
1116         }
1117
1118         status = ast_sorcery_retrieve_by_id(
1119                 ast_sip_get_sorcery(), CONTACT_STATUS,
1120                 ast_sorcery_object_get_id(contact));
1121
1122         ast_str_append(&buf, 0, "AOR: %s\r\n", wrapper->aor_id);
1123         ast_str_append(&buf, 0, "URI: %s\r\n", contact->uri);
1124         ast_str_append(&buf, 0, "Status: %s\r\n", ast_sip_get_contact_status_label(status->status));
1125         if (status->status == UNKNOWN) {
1126                 ast_str_append(&buf, 0, "RoundtripUsec: N/A\r\n");
1127         } else {
1128                 ast_str_append(&buf, 0, "RoundtripUsec: %" PRId64 "\r\n", status->rtt);
1129         }
1130         ast_str_append(&buf, 0, "EndpointName: %s\r\n",
1131                         ast_sorcery_object_get_id(endpoint));
1132         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1133         ami->count++;
1134         
1135         ast_free(buf);
1136         ao2_cleanup(status);
1137         return 0;
1138 }
1139
1140 static int format_contact_status_for_aor(void *obj, void *arg, int flags)
1141 {
1142         struct ast_sip_aor *aor = obj;
1143
1144         return ast_sip_for_each_contact(aor, format_contact_status, arg);
1145 }
1146
1147 static int format_ami_contact_status(const struct ast_sip_endpoint *endpoint,
1148                 struct ast_sip_ami *ami)
1149 {
1150         ami->arg = (void *)endpoint;
1151         return ast_sip_for_each_aor(endpoint->aors, format_contact_status_for_aor, ami);
1152 }
1153
1154 static struct ast_sip_endpoint_formatter contact_status_formatter = {
1155         .format_ami = format_ami_contact_status
1156 };
1157
1158 int ast_res_pjsip_init_options_handling(int reload)
1159 {
1160         static const pj_str_t STR_OPTIONS = { "OPTIONS", 7 };
1161
1162         if (reload) {
1163                 qualify_and_schedule_all();
1164                 return 0;
1165         }
1166
1167         sched_qualifies = ao2_t_container_alloc(QUALIFIED_BUCKETS,
1168                 sched_qualifies_hash_fn, sched_qualifies_cmp_fn,
1169                 "Create container for scheduled qualifies");
1170         if (!sched_qualifies) {
1171                 return -1;
1172         }
1173
1174         if (pjsip_endpt_register_module(ast_sip_get_pjsip_endpoint(), &options_module) != PJ_SUCCESS) {
1175                 ao2_cleanup(sched_qualifies);
1176                 sched_qualifies = NULL;
1177                 return -1;
1178         }
1179
1180         if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW,
1181                 NULL, 1, &STR_OPTIONS) != PJ_SUCCESS) {
1182                 pjsip_endpt_unregister_module(ast_sip_get_pjsip_endpoint(), &options_module);
1183                 ao2_cleanup(sched_qualifies);
1184                 sched_qualifies = NULL;
1185                 return -1;
1186         }
1187
1188         internal_sip_register_endpoint_formatter(&contact_status_formatter);
1189         ast_manager_register_xml("PJSIPQualify", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_sip_qualify);
1190         ast_cli_register_multiple(cli_options, ARRAY_LEN(cli_options));
1191
1192         qualify_and_schedule_all();
1193
1194         return 0;
1195 }
1196
1197 void ast_res_pjsip_cleanup_options_handling(void)
1198 {
1199         ast_cli_unregister_multiple(cli_options, ARRAY_LEN(cli_options));
1200         ast_manager_unregister("PJSIPQualify");
1201         internal_sip_unregister_endpoint_formatter(&contact_status_formatter);
1202
1203         pjsip_endpt_unregister_module(ast_sip_get_pjsip_endpoint(), &options_module);
1204         ao2_cleanup(sched_qualifies);
1205         sched_qualifies = NULL;
1206 }