res_pjsip_transport_websocket: Fix security events and simplify implementation.
[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 "include/res_pjsip_private.h"
32
33 #define DEFAULT_LANGUAGE "en"
34 #define DEFAULT_ENCODING "text/plain"
35 #define QUALIFIED_BUCKETS 211
36
37 static int qualify_contact(struct ast_sip_contact *contact);
38
39 /*!
40  * \internal
41  * \brief Create a ast_sip_contact_status object.
42  */
43 static void *contact_status_alloc(const char *name)
44 {
45         struct ast_sip_contact_status *status = ast_sorcery_generic_alloc(sizeof(*status), NULL);
46
47         if (!status) {
48                 ast_log(LOG_ERROR, "Unable to allocate ast_sip_contact_status\n");
49                 return NULL;
50         }
51
52         status->status = UNAVAILABLE;
53
54         return status;
55 }
56
57 /*!
58  * \internal
59  * \brief Retrieve a ast_sip_contact_status object from sorcery creating
60  *        one if not found.
61  */
62 static struct ast_sip_contact_status *find_or_create_contact_status(const struct ast_sip_contact *contact)
63 {
64         struct ast_sip_contact_status *status = ast_sorcery_retrieve_by_id(
65                 ast_sip_get_sorcery(), CONTACT_STATUS,
66                 ast_sorcery_object_get_id(contact));
67
68         if (status) {
69                 return status;
70         }
71
72         if (!(status = ast_sorcery_alloc(
73                       ast_sip_get_sorcery(), CONTACT_STATUS,
74                       ast_sorcery_object_get_id(contact)))) {
75
76                 ast_log(LOG_ERROR, "Unable to create ast_sip_contact_status for contact %s\n",
77                         contact->uri);
78                 return NULL;
79         }
80
81         if (ast_sorcery_create(ast_sip_get_sorcery(), status)) {
82                 ast_log(LOG_ERROR, "Unable to persist ast_sip_contact_status for contact %s\n",
83                         contact->uri);
84                 return NULL;
85         }
86
87         return status;
88 }
89
90 /*!
91  * \internal
92  * \brief Update an ast_sip_contact_status's elements.
93  */
94 static void update_contact_status(const struct ast_sip_contact *contact,
95                                   enum ast_sip_contact_status_type value)
96 {
97         RAII_VAR(struct ast_sip_contact_status *, status,
98                  find_or_create_contact_status(contact), ao2_cleanup);
99
100         RAII_VAR(struct ast_sip_contact_status *, update, ast_sorcery_alloc(
101                       ast_sip_get_sorcery(), CONTACT_STATUS,
102                       ast_sorcery_object_get_id(status)), ao2_cleanup);
103
104         if (!update) {
105                 ast_log(LOG_ERROR, "Unable to create update ast_sip_contact_status for contact %s\n",
106                         contact->uri);
107                 return;
108         }
109
110         update->status = value;
111
112         /* if the contact is available calculate the rtt as
113            the diff between the last start time and "now" */
114         update->rtt = update->status ?
115                 ast_tvdiff_us(ast_tvnow(), status->rtt_start) : 0;
116
117         update->rtt_start = ast_tv(0, 0);
118
119         if (ast_sorcery_update(ast_sip_get_sorcery(), update)) {
120                 ast_log(LOG_ERROR, "Unable to update ast_sip_contact_status for contact %s\n",
121                         contact->uri);
122         }
123 }
124
125 /*!
126  * \internal
127  * \brief Initialize the start time on a contact status so the round
128  *        trip time can be calculated upon a valid response.
129  */
130 static void init_start_time(const struct ast_sip_contact *contact)
131 {
132         RAII_VAR(struct ast_sip_contact_status *, status,
133                  find_or_create_contact_status(contact), ao2_cleanup);
134
135         RAII_VAR(struct ast_sip_contact_status *, update, ast_sorcery_alloc(
136                       ast_sip_get_sorcery(), CONTACT_STATUS,
137                       ast_sorcery_object_get_id(status)), ao2_cleanup);
138
139         if (!update) {
140                 ast_log(LOG_ERROR, "Unable to create update ast_sip_contact_status for contact %s\n",
141                         contact->uri);
142                 return;
143         }
144
145         update->rtt_start = ast_tvnow();
146
147         if (ast_sorcery_update(ast_sip_get_sorcery(), update)) {
148                 ast_log(LOG_ERROR, "Unable to update ast_sip_contact_status for contact %s\n",
149                         contact->uri);
150         }
151 }
152
153 /*!
154  * \internal
155  * \brief For an endpoint try to match on a given contact.
156  */
157 static int on_endpoint(void *obj, void *arg, int flags)
158 {
159         struct ast_sip_endpoint *endpoint = obj;
160         char *aor_name, *aors;
161
162         if (!arg || ast_strlen_zero(endpoint->aors)) {
163                 return 0;
164         }
165
166         aors = ast_strdupa(endpoint->aors);
167
168         while ((aor_name = strsep(&aors, ","))) {
169                 RAII_VAR(struct ast_sip_aor *, aor,
170                          ast_sip_location_retrieve_aor(aor_name), ao2_cleanup);
171                 RAII_VAR(struct ao2_container *, contacts, NULL, ao2_cleanup);
172
173                 if (!aor || !(contacts = ast_sip_location_retrieve_aor_contacts(aor))) {
174                         continue;
175                 }
176
177                 if (ao2_find(contacts, arg, OBJ_NODATA | OBJ_POINTER)) {
178                         return CMP_MATCH;
179                 }
180         }
181
182         return 0;
183 }
184
185 /*!
186  * \internal
187  * \brief Find endpoints associated with the given contact.
188  */
189 static struct ao2_container *find_endpoints(struct ast_sip_contact *contact)
190 {
191         RAII_VAR(struct ao2_container *, endpoints,
192                  ast_sip_get_endpoints(), ao2_cleanup);
193
194         return ao2_callback(endpoints, OBJ_MULTIPLE, on_endpoint, contact);
195 }
196
197 /*!
198  * \internal
199  * \brief Receive an response to the qualify contact request.
200  */
201 static void qualify_contact_cb(void *token, pjsip_event *e)
202 {
203         RAII_VAR(struct ast_sip_contact *, contact, token, ao2_cleanup);
204         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
205         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
206
207         pjsip_transaction *tsx = e->body.tsx_state.tsx;
208         pjsip_rx_data *challenge = e->body.tsx_state.src.rdata;
209         pjsip_tx_data *tdata;
210
211         switch(e->body.tsx_state.type) {
212         case PJSIP_EVENT_TRANSPORT_ERROR:
213         case PJSIP_EVENT_TIMER:
214                 update_contact_status(contact, UNAVAILABLE);
215                 return;
216         default:
217                 break;
218         }
219
220         if (!contact->authenticate_qualify || (tsx->status_code != 401 &&
221                                                tsx->status_code != 407)) {
222                 update_contact_status(contact, AVAILABLE);
223                 return;
224         }
225
226         /* try to find endpoints that are associated with the contact */
227         if (!(endpoints = find_endpoints(contact))) {
228                 ast_log(LOG_ERROR, "No endpoints found for contact %s, cannot authenticate",
229                         contact->uri);
230                 return;
231         }
232
233         /* find "first" endpoint in order to authenticate - actually any
234            endpoint should do that matched on the contact */
235         endpoint = ao2_callback(endpoints, 0, NULL, NULL);
236
237         if (!ast_sip_create_request_with_auth(&endpoint->outbound_auths,
238                                               challenge, tsx, &tdata)) {
239                 pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(), tdata,
240                                          -1, NULL, NULL);
241         }
242 }
243
244 /*!
245  * \internal
246  * \brief Attempt to qualify the contact
247  *
248  * \detail Sends a SIP OPTIONS request to the given contact in order to make
249  *         sure that contact is available.
250  */
251 static int qualify_contact(struct ast_sip_contact *contact)
252 {
253         pjsip_tx_data *tdata;
254
255         if (ast_sip_create_request("OPTIONS", NULL, NULL, contact->uri, &tdata)) {
256                 ast_log(LOG_ERROR, "Unable to create request to qualify contact %s\n",
257                         contact->uri);
258                 return -1;
259         }
260
261         init_start_time(contact);
262
263         ao2_ref(contact, +1);
264         if (pjsip_endpt_send_request(ast_sip_get_pjsip_endpoint(),
265                                      tdata, -1, contact, qualify_contact_cb) != PJ_SUCCESS) {
266                 /* The callback will be called so we don't need to drop the contact ref*/
267                 ast_log(LOG_ERROR, "Unable to send request to qualify contact %s\n",
268                         contact->uri);
269                 return -1;
270         }
271
272         return 0;
273 }
274
275 /*!
276  * \internal
277  * \brief Scheduling context for sending QUALIFY request at specified intervals.
278  */
279 static struct ast_sched_context *sched;
280
281 /*!
282  * \internal
283  * \brief Container to hold all actively scheduled qualifies.
284  */
285 static struct ao2_container *sched_qualifies;
286
287 /*!
288  * \internal
289  * \brief Structure to hold qualify contact scheduling information.
290  */
291 struct sched_data {
292         /*! The scheduling id */
293         int id;
294         /*! The the contact being checked */
295         struct ast_sip_contact *contact;
296 };
297
298 /*!
299  * \internal
300  * \brief Destroy the scheduled data and remove from scheduler.
301  */
302 static void sched_data_destructor(void *obj)
303 {
304         struct sched_data *data = obj;
305         ao2_cleanup(data->contact);
306 }
307 /*!
308  * \internal
309  * \brief Create the scheduling data object.
310  */
311 static struct sched_data *sched_data_create(struct ast_sip_contact *contact)
312 {
313         struct sched_data *data = ao2_alloc(sizeof(*data), sched_data_destructor);
314
315         if (!data) {
316                 ast_log(LOG_ERROR, "Unable to create schedule qualify data\n");
317                 return NULL;
318         }
319
320         data->contact = contact;
321         ao2_ref(data->contact, +1);
322
323         return data;
324 }
325
326 /*!
327  * \internal
328  * \brief Send a qualify contact request within a threaded task.
329  */
330 static int qualify_contact_task(void *obj)
331 {
332         RAII_VAR(struct ast_sip_contact *, contact, obj, ao2_cleanup);
333         return qualify_contact(contact);
334 }
335
336 /*!
337  * \internal
338  * \brief Send a scheduled qualify contact request.
339  */
340 static int qualify_contact_sched(const void *obj)
341 {
342         struct sched_data *data = (struct sched_data *)obj;
343
344         ao2_ref(data->contact, +1);
345         if (ast_sip_push_task(NULL, qualify_contact_task, data->contact)) {
346                 ao2_ref(data->contact, -1);
347                 ao2_cleanup(data);
348                 return 0;
349         }
350
351         return data->contact->qualify_frequency * 1000;
352 }
353
354 /*!
355  * \internal
356  * \brief Set up a scheduled qualify contact check.
357  */
358 static void schedule_qualify(struct ast_sip_contact *contact)
359 {
360         RAII_VAR(struct sched_data *, data, sched_data_create(contact), ao2_cleanup);
361
362         if (!data) {
363                 return;
364         }
365
366         ao2_ref(data, +1);
367         if ((data->id = ast_sched_add_variable(
368                     sched, contact->qualify_frequency * 1000,
369                     qualify_contact_sched, data, 1)) < 0) {
370
371                 ao2_ref(data, -1);
372                 ast_log(LOG_ERROR, "Unable to schedule qualify for contact %s\n",
373                         contact->uri);
374                 return;
375         }
376
377         ao2_link(sched_qualifies, data);
378 }
379
380 /*!
381  * \internal
382  * \brief Remove the contact from the scheduler.
383  */
384 static void unschedule_qualify(struct ast_sip_contact *contact)
385 {
386         RAII_VAR(struct sched_data *, data, ao2_find(
387                          sched_qualifies, contact, OBJ_UNLINK), ao2_cleanup);
388
389         if (!data) {
390                 return;
391         }
392
393         AST_SCHED_DEL_UNREF(sched, data->id, ao2_cleanup(data));
394 }
395
396 /*!
397  * \internal
398  * \brief Qualify the given contact and set up scheduling if configured.
399  */
400 static void qualify_and_schedule(struct ast_sip_contact *contact)
401 {
402         unschedule_qualify(contact);
403
404         if (contact->qualify_frequency) {
405                 ao2_ref(contact, +1);
406                 ast_sip_push_task(NULL, qualify_contact_task, contact);
407
408                 schedule_qualify(contact);
409         }
410 }
411
412 /*!
413  * \internal
414  * \brief A new contact has been created make sure it is available.
415  */
416 static void contact_created(const void *obj)
417 {
418         qualify_and_schedule((struct ast_sip_contact *)obj);
419 }
420
421 /*!
422  * \internal
423  * \brief A contact has been deleted remove status tracking.
424  */
425 static void contact_deleted(const void *obj)
426 {
427         struct ast_sip_contact *contact = (struct ast_sip_contact *)obj;
428         RAII_VAR(struct ast_sip_contact_status *, status, NULL, ao2_cleanup);
429
430         unschedule_qualify(contact);
431
432         if (!(status = ast_sorcery_retrieve_by_id(
433                       ast_sip_get_sorcery(), CONTACT_STATUS,
434                       ast_sorcery_object_get_id(contact)))) {
435                 return;
436         }
437
438         if (ast_sorcery_delete(ast_sip_get_sorcery(), status)) {
439                 ast_log(LOG_ERROR, "Unable to delete ast_sip_contact_status for contact %s\n",
440                         contact->uri);
441         }
442 }
443
444 struct ast_sorcery_observer contact_observer = {
445         .created = contact_created,
446         .deleted = contact_deleted
447 };
448
449 static pj_bool_t options_start(void)
450 {
451         if (!(sched = ast_sched_context_create()) ||
452             ast_sched_start_thread(sched)) {
453                 return -1;
454         }
455
456         return PJ_SUCCESS;
457 }
458
459 static pj_bool_t options_stop(void)
460 {
461         ast_sorcery_observer_remove(ast_sip_get_sorcery(), "contact", &contact_observer);
462
463         ao2_t_ref(sched_qualifies, -1, "Remove scheduled qualifies on module stop");
464
465         if (sched) {
466                 ast_sched_context_destroy(sched);
467         }
468
469         return PJ_SUCCESS;
470 }
471
472 static pj_status_t send_options_response(pjsip_rx_data *rdata, int code)
473 {
474         pjsip_endpoint *endpt = ast_sip_get_pjsip_endpoint();
475         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
476         pjsip_transaction *trans = pjsip_rdata_get_tsx(rdata);
477         pjsip_tx_data *tdata;
478         const pjsip_hdr *hdr;
479         pjsip_response_addr res_addr;
480         pj_status_t status;
481
482         /* Make the response object */
483         if ((status = pjsip_endpt_create_response(
484                      endpt, rdata, code, NULL, &tdata) != PJ_SUCCESS)) {
485                 ast_log(LOG_ERROR, "Unable to create response (%d)\n", status);
486                 return status;
487         }
488
489         /* Add appropriate headers */
490         if ((hdr = pjsip_endpt_get_capability(endpt, PJSIP_H_ACCEPT, NULL))) {
491                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr));
492         }
493         if ((hdr = pjsip_endpt_get_capability(endpt, PJSIP_H_ALLOW, NULL))) {
494                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr));
495         }
496         if ((hdr = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, NULL))) {
497                 pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)pjsip_hdr_clone(tdata->pool, hdr));
498         }
499
500         /*
501          * XXX TODO: pjsip doesn't care a lot about either of these headers -
502          * while it provides specific methods to create them, they are defined
503          * to be the standard string header creation. We never did add them
504          * in chan_sip, although RFC 3261 says they SHOULD. Hard coded here.
505          */
506         ast_sip_add_header(tdata, "Accept-Encoding", DEFAULT_ENCODING);
507         ast_sip_add_header(tdata, "Accept-Language", DEFAULT_LANGUAGE);
508
509         if (dlg && trans) {
510                 status = pjsip_dlg_send_response(dlg, trans, tdata);
511         } else {
512                 /* Get where to send request. */
513                 if ((status = pjsip_get_response_addr(
514                              tdata->pool, rdata, &res_addr)) != PJ_SUCCESS) {
515                         ast_log(LOG_ERROR, "Unable to get response address (%d)\n",
516                                 status);
517
518                         pjsip_tx_data_dec_ref(tdata);
519                         return status;
520                 }
521                 status = pjsip_endpt_send_response(endpt, &res_addr, tdata,
522                                                    NULL, NULL);
523         }
524
525         if (status != PJ_SUCCESS) {
526                 ast_log(LOG_ERROR, "Unable to send response (%d)\n", status);
527         }
528
529         return status;
530 }
531
532 static pj_bool_t options_on_rx_request(pjsip_rx_data *rdata)
533 {
534         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
535         pjsip_uri *ruri;
536         pjsip_sip_uri *sip_ruri;
537         char exten[AST_MAX_EXTENSION];
538
539         if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method,
540                              &pjsip_options_method)) {
541                 return PJ_FALSE;
542         }
543
544         if (!(endpoint = ast_pjsip_rdata_get_endpoint(rdata))) {
545                 return PJ_FALSE;
546         }
547
548         ruri = rdata->msg_info.msg->line.req.uri;
549         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
550                 send_options_response(rdata, 416);
551                 return -1;
552         }
553
554         sip_ruri = pjsip_uri_get_uri(ruri);
555         ast_copy_pj_str(exten, &sip_ruri->user, sizeof(exten));
556
557         if (ast_shutting_down()) {
558                 send_options_response(rdata, 503);
559         } else if (!ast_exists_extension(NULL, endpoint->context, exten, 1, NULL)) {
560                 send_options_response(rdata, 404);
561         } else {
562                 send_options_response(rdata, 200);
563         }
564         return PJ_TRUE;
565 }
566
567 static pjsip_module options_module = {
568         .name = {"Options Module", 14},
569         .id = -1,
570         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
571         .start = options_start,
572         .stop = options_stop,
573         .on_rx_request = options_on_rx_request,
574 };
575
576 /*!
577  * \internal
578  * \brief Send qualify request to the given contact.
579  */
580 static int cli_on_contact(void *obj, void *arg, int flags)
581 {
582         struct ast_sip_contact *contact = obj;
583         int *cli_fd = arg;
584         ast_cli(*cli_fd, " contact %s\n", contact->uri);
585         qualify_contact(contact);
586         return 0;
587 }
588
589 /*!
590  * \brief Data pushed to threadpool to qualify endpoints from the CLI
591  */
592 struct qualify_data {
593         /*! Endpoint that is being qualified */
594         struct ast_sip_endpoint *endpoint;
595         /*! CLI File descriptor for printing messages */
596         int cli_fd;
597 };
598
599 static struct qualify_data *qualify_data_alloc(struct ast_sip_endpoint *endpoint, int cli_fd)
600 {
601         struct qualify_data *qual_data;
602
603         qual_data = ast_malloc(sizeof(*qual_data));
604         if (!qual_data) {
605                 return NULL;
606         }
607
608         qual_data->endpoint = ao2_bump(endpoint);
609         qual_data->cli_fd = cli_fd;
610         return qual_data;
611 }
612
613 static void qualify_data_destroy(struct qualify_data *qual_data)
614 {
615         ao2_cleanup(qual_data->endpoint);
616         ast_free(qual_data);
617 }
618
619 /*!
620  * \internal
621  * \brief For an endpoint iterate over and qualify all aors/contacts
622  */
623 static int cli_qualify_contacts(void *data)
624 {
625         char *aor_name, *aors;
626         RAII_VAR(struct qualify_data *, qual_data, data, qualify_data_destroy);
627         struct ast_sip_endpoint *endpoint = qual_data->endpoint;
628         int cli_fd = qual_data->cli_fd;
629         const char *endpoint_name = ast_sorcery_object_get_id(endpoint);
630
631         if (ast_strlen_zero(endpoint->aors)) {
632                 ast_cli(cli_fd, "Endpoint %s has no AoR's configured\n",
633                         endpoint_name);
634                 return 0;
635         }
636
637         aors = ast_strdupa(endpoint->aors);
638
639         while ((aor_name = strsep(&aors, ","))) {
640                 RAII_VAR(struct ast_sip_aor *, aor,
641                          ast_sip_location_retrieve_aor(aor_name), ao2_cleanup);
642                 RAII_VAR(struct ao2_container *, contacts, NULL, ao2_cleanup);
643
644                 if (!aor || !(contacts = ast_sip_location_retrieve_aor_contacts(aor))) {
645                         continue;
646                 }
647
648                 ast_cli(cli_fd, "Sending qualify to endpoint %s\n", endpoint_name);
649                 ao2_callback(contacts, OBJ_NODATA, cli_on_contact, &cli_fd);
650         }
651         return 0;
652 }
653
654 static char *cli_qualify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
655 {
656         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
657         const char *endpoint_name;
658         struct qualify_data *qual_data;
659
660         switch (cmd) {
661         case CLI_INIT:
662                 e->command = "pjsip qualify";
663                 e->usage =
664                         "Usage: pjsip qualify <endpoint>\n"
665                         "       Send a SIP OPTIONS request to all contacts on the endpoint.\n";
666                 return NULL;
667         case CLI_GENERATE:
668                 return NULL;
669         }
670
671         if (a->argc != 3) {
672                 return CLI_SHOWUSAGE;
673         }
674
675         endpoint_name = a->argv[2];
676
677         if (!(endpoint = ast_sorcery_retrieve_by_id(
678                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
679                 ast_cli(a->fd, "Unable to retrieve endpoint %s\n", endpoint_name);
680                 return CLI_FAILURE;
681         }
682
683         qual_data = qualify_data_alloc(endpoint, a->fd);
684         if (!qual_data) {
685                 return CLI_FAILURE;
686         }
687
688         if (ast_sip_push_task(NULL, cli_qualify_contacts, qual_data)) {
689                 qualify_data_destroy(qual_data);
690                 return CLI_FAILURE;
691         }
692
693         return CLI_SUCCESS;
694 }
695
696 /*!
697  * \internal
698  * \brief Send qualify request to the given contact.
699  */
700 static int ami_contact_cb(void *obj, void *arg, int flags)
701 {
702         struct ast_sip_contact *contact = obj;
703         ao2_ref(contact, +1);
704         if (ast_sip_push_task(NULL, qualify_contact_task, contact)) {
705                 ao2_cleanup(contact);
706         }
707         return 0;
708 }
709
710 static int ami_sip_qualify(struct mansession *s, const struct message *m)
711 {
712         const char *endpoint_name = astman_get_header(m, "Endpoint");
713         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
714         char *aor_name, *aors;
715
716         if (ast_strlen_zero(endpoint_name)) {
717                 astman_send_error(s, m, "Endpoint parameter missing.");
718                 return 0;
719         }
720
721         endpoint = ast_sorcery_retrieve_by_id(
722                 ast_sip_get_sorcery(),
723                 "endpoint",
724                 endpoint_name);
725         if (!endpoint) {
726                 astman_send_error(s, m, "Unable to retrieve endpoint\n");
727                 return 0;
728         }
729
730         /* send a qualify for all contacts registered with the endpoint */
731         if (ast_strlen_zero(endpoint->aors)) {
732                 astman_send_error(s, m, "No AoRs configured for endpoint\n");
733                 return 0;
734         }
735
736         aors = ast_strdupa(endpoint->aors);
737
738         while ((aor_name = strsep(&aors, ","))) {
739                 RAII_VAR(struct ast_sip_aor *, aor,
740                          ast_sip_location_retrieve_aor(aor_name), ao2_cleanup);
741                 RAII_VAR(struct ao2_container *, contacts, NULL, ao2_cleanup);
742
743                 if (!aor || !(contacts = ast_sip_location_retrieve_aor_contacts(aor))) {
744                         continue;
745                 }
746
747                 ao2_callback(contacts, OBJ_NODATA, ami_contact_cb, NULL);
748         }
749
750         astman_send_ack(s, m, "Endpoint found, will qualify");
751         return 0;
752 }
753
754 static struct ast_cli_entry cli_options[] = {
755         AST_CLI_DEFINE(cli_qualify, "Send an OPTIONS request to a PJSIP endpoint")
756 };
757
758 static int sched_qualifies_hash_fn(const void *obj, int flags)
759 {
760         const struct sched_data *data = obj;
761
762         return ast_str_hash(ast_sorcery_object_get_id(data->contact));
763 }
764
765 static int sched_qualifies_cmp_fn(void *obj, void *arg, int flags)
766 {
767         struct sched_data *data = obj;
768
769         return !strcmp(ast_sorcery_object_get_id(data->contact),
770                        ast_sorcery_object_get_id(arg));
771 }
772
773 int ast_sip_initialize_sorcery_qualify(struct ast_sorcery *sorcery)
774 {
775         /* initialize sorcery ast_sip_contact_status resource */
776         ast_sorcery_apply_default(sorcery, CONTACT_STATUS, "memory", NULL);
777
778         if (ast_sorcery_internal_object_register(sorcery, CONTACT_STATUS,
779                                         contact_status_alloc, NULL, NULL)) {
780                 ast_log(LOG_ERROR, "Unable to register ast_sip_contact_status in sorcery\n");
781                 return -1;
782         }
783
784         ast_sorcery_object_field_register_nodoc(sorcery, CONTACT_STATUS, "rtt", "0", OPT_UINT_T,
785                                           1, FLDSET(struct ast_sip_contact_status, status));
786         ast_sorcery_object_field_register_nodoc(sorcery, CONTACT_STATUS, "rtt", "0", OPT_UINT_T,
787                                           1, FLDSET(struct ast_sip_contact_status, rtt));
788
789         return 0;
790 }
791
792 static int qualify_and_schedule_cb(void *obj, void *arg, int flags)
793 {
794         struct ast_sip_contact *contact = obj;
795         struct ast_sip_aor *aor = arg;
796
797         contact->qualify_frequency = aor->qualify_frequency;
798         qualify_and_schedule(contact);
799
800         return 0;
801 }
802
803 /*!
804  * \internal
805  * \brief Qualify and schedule an endpoint's permanent contacts
806  *
807  * \detail For the given endpoint retrieve its list of aors, qualify all
808  *         permanent contacts, and schedule for checks if configured.
809  */
810 static int qualify_and_schedule_permanent_cb(void *obj, void *arg, int flags)
811 {
812         struct ast_sip_endpoint *endpoint = obj;
813         char *aor_name, *aors;
814
815         if (ast_strlen_zero(endpoint->aors)) {
816                 return 0;
817         }
818
819         aors = ast_strdupa(endpoint->aors);
820
821         while ((aor_name = strsep(&aors, ","))) {
822                 RAII_VAR(struct ast_sip_aor *, aor,
823                          ast_sip_location_retrieve_aor(aor_name), ao2_cleanup);
824
825                 if (!aor || !aor->permanent_contacts) {
826                         continue;
827                 }
828                 ao2_callback(aor->permanent_contacts, OBJ_NODATA, qualify_and_schedule_cb, aor);
829         }
830
831         return 0;
832 }
833
834 static void qualify_and_schedule_permanent(void)
835 {
836         RAII_VAR(struct ao2_container *, endpoints,
837                  ast_sip_get_endpoints(), ao2_cleanup);
838
839         ao2_callback(endpoints, OBJ_NODATA,
840                      qualify_and_schedule_permanent_cb, NULL);
841 }
842
843 int ast_res_pjsip_init_options_handling(int reload)
844 {
845         const pj_str_t STR_OPTIONS = { "OPTIONS", 7 };
846
847         if (sched_qualifies) {
848                 ao2_t_ref(sched_qualifies, -1, "Remove old scheduled qualifies");
849         }
850
851         if (!(sched_qualifies = ao2_t_container_alloc(
852                 QUALIFIED_BUCKETS, sched_qualifies_hash_fn, sched_qualifies_cmp_fn,
853                 "Create container for scheduled qualifies"))) {
854
855                 return -1;
856         }
857
858         if (reload) {
859                 qualify_and_schedule_permanent();
860                 return 0;
861         }
862
863         if (pjsip_endpt_register_module(ast_sip_get_pjsip_endpoint(), &options_module) != PJ_SUCCESS) {
864                 options_stop();
865                 return -1;
866         }
867
868         if (pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_ALLOW, NULL, 1, &STR_OPTIONS) != PJ_SUCCESS) {
869                 pjsip_endpt_unregister_module(ast_sip_get_pjsip_endpoint(), &options_module);
870                 return -1;
871         }
872
873         if (ast_sorcery_observer_add(ast_sip_get_sorcery(), "contact", &contact_observer)) {
874                 ast_log(LOG_WARNING, "Unable to add contact observer\n");
875                 return -1;
876         }
877
878         qualify_and_schedule_permanent();
879         ast_cli_register_multiple(cli_options, ARRAY_LEN(cli_options));
880         ast_manager_register2("PJSIPQualify", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, ami_sip_qualify, NULL, NULL, NULL);
881
882         return 0;
883 }
884
885 void ast_res_pjsip_cleanup_options_handling(void)
886 {
887         ast_cli_unregister_multiple(cli_options, ARRAY_LEN(cli_options));
888         ast_manager_unregister("PJSIPQualify");
889 }