pjsip_scheduler.c: Fix some corner cases.
[asterisk/asterisk.git] / res / res_pjsip / pjsip_configuration.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
24 #include "asterisk/res_pjsip.h"
25 #include "include/res_pjsip_private.h"
26 #include "asterisk/res_pjsip_cli.h"
27 #include "asterisk/acl.h"
28 #include "asterisk/manager.h"
29 #include "asterisk/astobj2.h"
30 #include "asterisk/utils.h"
31 #include "asterisk/sorcery.h"
32 #include "asterisk/callerid.h"
33 #include "asterisk/test.h"
34 #include "asterisk/statsd.h"
35 #include "asterisk/pbx.h"
36 #include "asterisk/stream.h"
37
38 /*! \brief Number of buckets for persistent endpoint information */
39 #define PERSISTENT_BUCKETS 53
40
41 /*! \brief Persistent endpoint information */
42 struct sip_persistent_endpoint {
43         /*! \brief Asterisk endpoint itself */
44         struct ast_endpoint *endpoint;
45         /*! \brief AORs that we should react to */
46         char *aors;
47 };
48
49 /*! \brief Container for persistent endpoint information */
50 static struct ao2_container *persistent_endpoints;
51
52 static struct ast_sorcery *sip_sorcery;
53
54 /*! \brief Hashing function for persistent endpoint information */
55 static int persistent_endpoint_hash(const void *obj, const int flags)
56 {
57         const struct sip_persistent_endpoint *persistent = obj;
58         const char *id = (flags & OBJ_KEY ? obj : ast_endpoint_get_resource(persistent->endpoint));
59
60         return ast_str_hash(id);
61 }
62
63 /*! \brief Comparison function for persistent endpoint information */
64 static int persistent_endpoint_cmp(void *obj, void *arg, int flags)
65 {
66         const struct sip_persistent_endpoint *persistent1 = obj;
67         const struct sip_persistent_endpoint *persistent2 = arg;
68         const char *id = (flags & OBJ_KEY ? arg : ast_endpoint_get_resource(persistent2->endpoint));
69
70         return !strcmp(ast_endpoint_get_resource(persistent1->endpoint), id) ? CMP_MATCH | CMP_STOP : 0;
71 }
72
73 /*! \brief Internal function for changing the state of an endpoint */
74 static void endpoint_update_state(struct ast_endpoint *endpoint, enum ast_endpoint_state state)
75 {
76         struct ast_json *blob;
77         char *regcontext;
78
79         /* If there was no state change, don't publish anything. */
80         if (ast_endpoint_get_state(endpoint) == state) {
81                 return;
82         }
83
84         regcontext = ast_sip_get_regcontext();
85
86         if (state == AST_ENDPOINT_ONLINE) {
87                 ast_endpoint_set_state(endpoint, AST_ENDPOINT_ONLINE);
88                 blob = ast_json_pack("{s: s}", "peer_status", "Reachable");
89
90                 if (!ast_strlen_zero(regcontext)) {
91                         if (!ast_exists_extension(NULL, regcontext, ast_endpoint_get_resource(endpoint), 1, NULL)) {
92                                 ast_add_extension(regcontext, 1, ast_endpoint_get_resource(endpoint), 1, NULL, NULL,
93                                         "Noop", ast_strdup(ast_endpoint_get_resource(endpoint)), ast_free_ptr, "SIP");
94                         }
95                 }
96
97                 ast_verb(2, "Endpoint %s is now Reachable\n", ast_endpoint_get_resource(endpoint));
98         } else {
99                 ast_endpoint_set_state(endpoint, AST_ENDPOINT_OFFLINE);
100                 blob = ast_json_pack("{s: s}", "peer_status", "Unreachable");
101
102                 if (!ast_strlen_zero(regcontext)) {
103                         struct pbx_find_info q = { .stacklen = 0 };
104
105                         if (pbx_find_extension(NULL, NULL, &q, regcontext, ast_endpoint_get_resource(endpoint), 1, NULL, "", E_MATCH)) {
106                                 ast_context_remove_extension(regcontext, ast_endpoint_get_resource(endpoint), 1, NULL);
107                         }
108                 }
109
110                 ast_verb(2, "Endpoint %s is now Unreachable\n", ast_endpoint_get_resource(endpoint));
111         }
112
113         ast_free(regcontext);
114
115         ast_endpoint_blob_publish(endpoint, ast_endpoint_state_type(), blob);
116         ast_json_unref(blob);
117         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_endpoint_get_resource(endpoint));
118 }
119
120 static void endpoint_publish_contact_status(struct ast_endpoint *endpoint, struct ast_sip_contact_status *contact)
121 {
122         struct ast_json *blob;
123         char rtt[32];
124
125         snprintf(rtt, sizeof(rtt), "%" PRId64, contact->rtt);
126         blob = ast_json_pack("{s: s, s: s, s: s, s: s, s: s}",
127                 "contact_status", ast_sip_get_contact_status_label(contact->status),
128                 "aor", contact->aor,
129                 "uri", contact->uri,
130                 "roundtrip_usec", rtt,
131                 "endpoint_name", ast_endpoint_get_resource(endpoint));
132         if (blob) {
133                 ast_endpoint_blob_publish(endpoint, ast_endpoint_contact_state_type(), blob);
134                 ast_json_unref(blob);
135         }
136 }
137
138 /*! \brief Callback function for publishing the status of an endpoint */
139 static int persistent_endpoint_publish_status(void *obj, void *arg, int flags)
140 {
141         struct sip_persistent_endpoint *persistent = obj;
142         struct ast_endpoint *endpoint = persistent->endpoint;
143         struct ast_sip_contact_status *status = arg;
144
145         /* If the status' aor isn't one of the endpoint's, we skip */
146         if (!strstr(persistent->aors, status->aor)) {
147                 return 0;
148         }
149
150         endpoint_publish_contact_status(endpoint, status);
151         return 0;
152 }
153
154 /*! \brief Callback function for changing the state of an endpoint */
155 static int persistent_endpoint_update_state(void *obj, void *arg, int flags)
156 {
157         struct sip_persistent_endpoint *persistent = obj;
158         struct ast_endpoint *endpoint = persistent->endpoint;
159         struct ast_sip_contact_status *status = arg;
160         struct ao2_container *contacts;
161         struct ao2_iterator iter;
162         struct ast_sip_contact *contact;
163         enum ast_endpoint_state state = AST_ENDPOINT_OFFLINE;
164
165         /* If the status' aor isn't one of the endpoint's, we skip */
166         if (!strstr(persistent->aors, status->aor)) {
167                 return 0;
168         }
169
170         endpoint_publish_contact_status(endpoint, status);
171
172         /* Find all the contacts for this endpoint.  If ANY are available,
173          * mark the endpoint as ONLINE.
174          */
175         contacts = ast_sip_location_retrieve_contacts_from_aor_list(persistent->aors);
176         if (contacts) {
177                 iter = ao2_iterator_init(contacts, 0);
178                 while (state == AST_ENDPOINT_OFFLINE && (contact = ao2_iterator_next(&iter))) {
179                         struct ast_sip_contact_status *contact_status;
180                         const char *contact_id = ast_sorcery_object_get_id(contact);
181
182                         contact_status = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(),
183                                 CONTACT_STATUS, contact_id);
184                         if (contact_status && contact_status->status != UNAVAILABLE) {
185                                 state = AST_ENDPOINT_ONLINE;
186                         }
187                         ao2_cleanup(contact_status);
188                         ao2_ref(contact, -1);
189                 }
190                 ao2_iterator_destroy(&iter);
191                 ao2_ref(contacts, -1);
192         }
193
194         endpoint_update_state(endpoint, state);
195
196         return 0;
197 }
198
199 /*! \brief Function called when a contact is created */
200 static void persistent_endpoint_contact_created_observer(const void *object)
201 {
202         const struct ast_sip_contact *contact = object;
203         struct ast_sip_contact_status *contact_status;
204
205         contact_status = ast_sorcery_alloc(ast_sip_get_sorcery(), CONTACT_STATUS,
206                 ast_sorcery_object_get_id(contact));
207         if (!contact_status) {
208                 ast_log(LOG_ERROR, "Unable to create ast_sip_contact_status for contact %s/%s\n",
209                         contact->aor, contact->uri);
210                 return;
211         }
212         ast_string_field_set(contact_status, uri, contact->uri);
213
214         contact_status->status = CREATED;
215
216         ast_verb(2, "Contact %s/%s has been created\n", contact->aor, contact->uri);
217
218         ao2_callback(persistent_endpoints, OBJ_NODATA, persistent_endpoint_update_state, contact_status);
219         ao2_cleanup(contact_status);
220 }
221
222 /*! \brief Function called when a contact is deleted */
223 static void persistent_endpoint_contact_deleted_observer(const void *object)
224 {
225         const struct ast_sip_contact *contact = object;
226         struct ast_sip_contact_status *contact_status;
227
228         contact_status = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), CONTACT_STATUS, ast_sorcery_object_get_id(contact));
229         if (!contact_status) {
230                 ast_log(LOG_ERROR, "Unable to find ast_sip_contact_status for contact %s/%s\n",
231                         contact->aor, contact->uri);
232                 return;
233         }
234
235         ast_verb(2, "Contact %s/%s has been deleted\n", contact->aor, contact->uri);
236         ast_statsd_log_string_va("PJSIP.contacts.states.%s", AST_STATSD_GAUGE,
237                 "-1", 1.0, ast_sip_get_contact_status_label(contact_status->status));
238         ast_statsd_log_string_va("PJSIP.contacts.states.%s", AST_STATSD_GAUGE,
239                 "+1", 1.0, ast_sip_get_contact_status_label(REMOVED));
240
241         ao2_callback(persistent_endpoints, OBJ_NODATA, persistent_endpoint_update_state, contact_status);
242         ast_sorcery_delete(ast_sip_get_sorcery(), contact_status);
243         ao2_cleanup(contact_status);
244 }
245
246 /*! \brief Observer for contacts so state can be updated on respective endpoints */
247 static const struct ast_sorcery_observer state_contact_observer = {
248         .created = persistent_endpoint_contact_created_observer,
249         .deleted = persistent_endpoint_contact_deleted_observer,
250 };
251
252 /*! \brief Function called when a contact_status is updated */
253 static void persistent_endpoint_contact_status_observer(const void *object)
254 {
255         struct ast_sip_contact_status *contact_status = (struct ast_sip_contact_status *)object;
256
257         if (contact_status->refresh) {
258                 /* We are only re-publishing the contact status. */
259                 ao2_callback(persistent_endpoints, OBJ_NODATA,
260                         persistent_endpoint_publish_status, contact_status);
261                 return;
262         }
263
264         /* If rtt_start is set (this is the outgoing OPTIONS), ignore. */
265         if (contact_status->rtt_start.tv_sec > 0) {
266                 return;
267         }
268
269         if (contact_status->status != contact_status->last_status) {
270                 ast_verb(3, "Contact %s/%s is now %s.  RTT: %.3f msec\n",
271                         contact_status->aor, contact_status->uri,
272                         ast_sip_get_contact_status_label(contact_status->status),
273                         contact_status->rtt / 1000.0);
274
275                 ast_statsd_log_string_va("PJSIP.contacts.states.%s", AST_STATSD_GAUGE,
276                         "-1", 1.0, ast_sip_get_contact_status_label(contact_status->last_status));
277                 ast_statsd_log_string_va("PJSIP.contacts.states.%s", AST_STATSD_GAUGE,
278                         "+1", 1.0, ast_sip_get_contact_status_label(contact_status->status));
279
280                 ast_test_suite_event_notify("AOR_CONTACT_UPDATE",
281                         "Contact: %s\r\n"
282                         "Status: %s",
283                         ast_sorcery_object_get_id(contact_status),
284                         ast_sip_get_contact_status_label(contact_status->status));
285
286                 ao2_callback(persistent_endpoints, OBJ_NODATA, persistent_endpoint_update_state,
287                         contact_status);
288         } else {
289                 ast_debug(3, "Contact %s/%s status didn't change: %s, RTT: %.3f msec\n",
290                         contact_status->aor, contact_status->uri,
291                         ast_sip_get_contact_status_label(contact_status->status),
292                         contact_status->rtt / 1000.0);
293         }
294
295         ast_statsd_log_full_va("PJSIP.contacts.%s.rtt", AST_STATSD_TIMER,
296                 contact_status->status != AVAILABLE ? -1 : contact_status->rtt / 1000,
297                 1.0,
298                 ast_sorcery_object_get_id(contact_status));
299 }
300
301 /*! \brief Observer for contacts so state can be updated on respective endpoints */
302 static const struct ast_sorcery_observer state_contact_status_observer = {
303         .updated = persistent_endpoint_contact_status_observer,
304 };
305
306 static void endpoint_deleted_observer(const void *object)
307 {
308         const struct ast_sip_endpoint *endpoint = object;
309
310         ao2_find(persistent_endpoints, ast_endpoint_get_resource(endpoint->persistent),
311                 OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
312 }
313
314 static const struct ast_sorcery_observer endpoint_observers = {
315         .deleted = endpoint_deleted_observer,
316 };
317
318 static int endpoint_acl_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
319 {
320         struct ast_sip_endpoint *endpoint = obj;
321         int error = 0;
322         int ignore;
323
324         if (ast_strlen_zero(var->value)) return 0;
325
326         if (!strncmp(var->name, "contact_", 8)) {
327                 ast_append_acl(var->name + 8, var->value, &endpoint->contact_acl, &error, &ignore);
328         } else {
329                 ast_append_acl(var->name, var->value, &endpoint->acl, &error, &ignore);
330         }
331
332         return error;
333 }
334
335 static int acl_to_str(const void *obj, const intptr_t *args, char **buf)
336 {
337         const struct ast_sip_endpoint *endpoint = obj;
338         struct ast_acl_list *acl_list;
339         struct ast_acl *first_acl;
340
341         if (endpoint && !ast_acl_list_is_empty(acl_list=endpoint->acl)) {
342                 AST_LIST_LOCK(acl_list);
343                 first_acl = AST_LIST_FIRST(acl_list);
344                 if (ast_strlen_zero(first_acl->name)) {
345                         *buf = "deny/permit";
346                 } else {
347                         *buf = first_acl->name;
348                 }
349                 AST_LIST_UNLOCK(acl_list);
350         }
351
352         *buf = ast_strdup(*buf);
353         return 0;
354 }
355
356 static int contact_acl_to_str(const void *obj, const intptr_t *args, char **buf)
357 {
358         const struct ast_sip_endpoint *endpoint = obj;
359         struct ast_acl_list *acl_list;
360         struct ast_acl *first_acl;
361
362         if (endpoint && !ast_acl_list_is_empty(acl_list=endpoint->contact_acl)) {
363                 AST_LIST_LOCK(acl_list);
364                 first_acl = AST_LIST_FIRST(acl_list);
365                 if (ast_strlen_zero(first_acl->name)) {
366                         *buf = "deny/permit";
367                 } else {
368                         *buf = first_acl->name;
369                 }
370                 AST_LIST_UNLOCK(acl_list);
371         }
372
373         *buf = ast_strdup(*buf);
374         return 0;
375 }
376
377 static int dtmf_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
378 {
379         struct ast_sip_endpoint *endpoint = obj;
380         int dtmf = ast_sip_str_to_dtmf(var->value);
381
382         if (dtmf == -1) {
383                 return -1;
384         }
385
386         endpoint->dtmf = dtmf;
387         return 0;
388 }
389
390 static int dtmf_to_str(const void *obj, const intptr_t *args, char **buf)
391 {
392         const struct ast_sip_endpoint *endpoint = obj;
393         char dtmf_str[20];
394         int result = -1;
395
396         result = ast_sip_dtmf_to_str(endpoint->dtmf, dtmf_str, sizeof(dtmf_str));
397
398         if (result == 0) {
399                 *buf = ast_strdup(dtmf_str);
400         } else {
401                 *buf = ast_strdup("none");
402         }
403         return 0;
404 }
405
406 static int prack_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
407 {
408         struct ast_sip_endpoint *endpoint = obj;
409
410         /* clear all */
411         endpoint->extensions.flags &= ~(PJSIP_INV_SUPPORT_100REL | PJSIP_INV_REQUIRE_100REL);
412
413         if (ast_true(var->value)) {
414                 endpoint->extensions.flags |= PJSIP_INV_SUPPORT_100REL;
415         } else if (!strcasecmp(var->value, "required")) {
416                 endpoint->extensions.flags |= PJSIP_INV_REQUIRE_100REL;
417         } else if (!ast_false(var->value)){
418                 return -1;
419         }
420
421         return 0;
422 }
423
424 static int prack_to_str(const void *obj, const intptr_t *args, char **buf)
425 {
426         const struct ast_sip_endpoint *endpoint = obj;
427
428         if (endpoint->extensions.flags & PJSIP_INV_REQUIRE_100REL) {
429                 *buf = "required";
430         } else if (endpoint->extensions.flags & PJSIP_INV_SUPPORT_100REL) {
431                 *buf = "yes";
432         } else {
433                 *buf = "no";
434         }
435
436         *buf = ast_strdup(*buf);
437         return 0;
438 }
439
440 static int timers_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
441 {
442         struct ast_sip_endpoint *endpoint = obj;
443
444         /* clear all */
445         endpoint->extensions.flags &= ~(PJSIP_INV_SUPPORT_TIMER | PJSIP_INV_REQUIRE_TIMER
446                                         | PJSIP_INV_ALWAYS_USE_TIMER);
447
448         /* set only the specified flag and let pjsip normalize if needed */
449         if (ast_true(var->value)) {
450                 endpoint->extensions.flags |= PJSIP_INV_SUPPORT_TIMER;
451         } else if (!strcasecmp(var->value, "required")) {
452                 endpoint->extensions.flags |= PJSIP_INV_REQUIRE_TIMER;
453         } else if (!strcasecmp(var->value, "always") || !strcasecmp(var->value, "forced")) {
454                 endpoint->extensions.flags |= PJSIP_INV_ALWAYS_USE_TIMER;
455         } else if (!ast_false(var->value)) {
456                 return -1;
457         }
458
459         return 0;
460 }
461
462 static int timers_to_str(const void *obj, const intptr_t *args, char **buf)
463 {
464         const struct ast_sip_endpoint *endpoint = obj;
465
466         if (endpoint->extensions.flags & PJSIP_INV_ALWAYS_USE_TIMER) {
467                 *buf = "always";
468         } else if (endpoint->extensions.flags & PJSIP_INV_REQUIRE_TIMER) {
469                 *buf = "required";
470         } else if (endpoint->extensions.flags & PJSIP_INV_SUPPORT_TIMER) {
471                 *buf = "yes";
472         } else {
473                 *buf = "no";
474         }
475
476         *buf = ast_strdup(*buf);
477         return 0;
478 }
479
480 void ast_sip_auth_vector_destroy(struct ast_sip_auth_vector *auths)
481 {
482         int i;
483         size_t size;
484
485         if (!auths) {
486                 return;
487         }
488
489         size = AST_VECTOR_SIZE(auths);
490
491         for (i = 0; i < size; ++i) {
492                 const char *name = AST_VECTOR_REMOVE_UNORDERED(auths, 0);
493                 ast_free((char *) name);
494         }
495         AST_VECTOR_FREE(auths);
496 }
497
498 int ast_sip_auth_vector_init(struct ast_sip_auth_vector *auths, const char *value)
499 {
500         char *auth_names = ast_strdupa(value);
501         char *val;
502
503         ast_assert(auths != NULL);
504
505         if (AST_VECTOR_SIZE(auths)) {
506                 ast_sip_auth_vector_destroy(auths);
507         }
508         if (AST_VECTOR_INIT(auths, 1)) {
509                 return -1;
510         }
511
512         while ((val = ast_strip(strsep(&auth_names, ",")))) {
513                 if (ast_strlen_zero(val)) {
514                         continue;
515                 }
516
517                 val = ast_strdup(val);
518                 if (!val) {
519                         goto failure;
520                 }
521                 if (AST_VECTOR_APPEND(auths, val)) {
522                         ast_free(val);
523
524                         goto failure;
525                 }
526         }
527         return 0;
528
529 failure:
530         ast_sip_auth_vector_destroy(auths);
531         return -1;
532 }
533
534 static int inbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
535 {
536         struct ast_sip_endpoint *endpoint = obj;
537
538         return ast_sip_auth_vector_init(&endpoint->inbound_auths, var->value);
539 }
540
541 static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
542 {
543         struct ast_sip_endpoint *endpoint = obj;
544
545         return ast_sip_auth_vector_init(&endpoint->outbound_auths, var->value);
546 }
547
548 int ast_sip_auths_to_str(const struct ast_sip_auth_vector *auths, char **buf)
549 {
550         if (!auths || !AST_VECTOR_SIZE(auths)) {
551                 return 0;
552         }
553
554         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
555                 return -1;
556         }
557
558         /* I feel like accessing the vector's elem array directly is cheating...*/
559         ast_join_delim(*buf, MAX_OBJECT_FIELD, auths->elems, AST_VECTOR_SIZE(auths), ',');
560         return 0;
561 }
562
563 static int inbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
564 {
565         const struct ast_sip_endpoint *endpoint = obj;
566         return ast_sip_auths_to_str(&endpoint->inbound_auths, buf);
567 }
568
569 static int outbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
570 {
571         const struct ast_sip_endpoint *endpoint = obj;
572         return ast_sip_auths_to_str(&endpoint->outbound_auths, buf);
573 }
574
575 /*!
576  * \internal
577  * \brief Convert identify_by method to string.
578  *
579  * \param method Method value to convert to string
580  *
581  * \return String representation.
582  */
583 static const char *sip_endpoint_identifier_type2str(enum ast_sip_endpoint_identifier_type method)
584 {
585         const char *str = "<unknown>";
586
587         switch (method) {
588         case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME:
589                 str = "username";
590                 break;
591         case AST_SIP_ENDPOINT_IDENTIFY_BY_AUTH_USERNAME:
592                 str = "auth_username";
593                 break;
594         case AST_SIP_ENDPOINT_IDENTIFY_BY_IP:
595                 str = "ip";
596                 break;
597         case AST_SIP_ENDPOINT_IDENTIFY_BY_HEADER:
598                 str = "header";
599                 break;
600         }
601         return str;
602 }
603
604 /*!
605  * \internal
606  * \brief Convert string to an endpoint identifier token.
607  *
608  * \param str String to convert
609  *
610  * \retval enum ast_sip_endpoint_identifier_type token value on success.
611  * \retval -1 on failure.
612  */
613 static int sip_endpoint_identifier_str2type(const char *str)
614 {
615         int method;
616
617         if (!strcasecmp(str, "username")) {
618                 method = AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME;
619         } else if (!strcasecmp(str, "auth_username")) {
620                 method = AST_SIP_ENDPOINT_IDENTIFY_BY_AUTH_USERNAME;
621         } else if (!strcasecmp(str, "ip")) {
622                 method = AST_SIP_ENDPOINT_IDENTIFY_BY_IP;
623         } else if (!strcasecmp(str, "header")) {
624                 method = AST_SIP_ENDPOINT_IDENTIFY_BY_HEADER;
625         } else {
626                 method = -1;
627         }
628         return method;
629 }
630
631 static int ident_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
632 {
633         struct ast_sip_endpoint *endpoint = obj;
634         char *idents = ast_strdupa(var->value);
635         char *val;
636         int method;
637
638         /*
639          * If there's already something in the vector when we get here,
640          * it's the default value so we need to clean it out.
641          */
642         if (AST_VECTOR_SIZE(&endpoint->ident_method_order)) {
643                 AST_VECTOR_RESET(&endpoint->ident_method_order, AST_VECTOR_ELEM_CLEANUP_NOOP);
644                 endpoint->ident_method = 0;
645         }
646
647         while ((val = ast_strip(strsep(&idents, ",")))) {
648                 if (ast_strlen_zero(val)) {
649                         continue;
650                 }
651
652                 method = sip_endpoint_identifier_str2type(val);
653                 if (method == -1) {
654                         ast_log(LOG_ERROR, "Unrecognized identification method %s specified for endpoint %s\n",
655                                         val, ast_sorcery_object_get_id(endpoint));
656                         AST_VECTOR_RESET(&endpoint->ident_method_order, AST_VECTOR_ELEM_CLEANUP_NOOP);
657                         endpoint->ident_method = 0;
658                         return -1;
659                 }
660                 if (endpoint->ident_method & method) {
661                         /* We are already indentifying by this method.  No need to do it again. */
662                         continue;
663                 }
664
665                 endpoint->ident_method |= method;
666                 AST_VECTOR_APPEND(&endpoint->ident_method_order, method);
667         }
668
669         return 0;
670 }
671
672 static int ident_to_str(const void *obj, const intptr_t *args, char **buf)
673 {
674         const struct ast_sip_endpoint *endpoint = obj;
675         int methods;
676         int idx;
677         int buf_used = 0;
678         int buf_size = MAX_OBJECT_FIELD;
679
680         methods = AST_VECTOR_SIZE(&endpoint->ident_method_order);
681         if (!methods) {
682                 return 0;
683         }
684
685         *buf = ast_malloc(buf_size);
686         if (!*buf) {
687                 return -1;
688         }
689
690         for (idx = 0; idx < methods; ++idx) {
691                 enum ast_sip_endpoint_identifier_type method;
692                 const char *method_str;
693
694                 method = AST_VECTOR_GET(&endpoint->ident_method_order, idx);
695                 method_str = sip_endpoint_identifier_type2str(method);
696
697                 /* Should never have an "<unknown>" method string */
698                 ast_assert(strcmp(method_str, "<unknown>"));
699                 if (!strcmp(method_str, "<unknown>")) {
700                         continue;
701                 }
702
703                 buf_used += snprintf(*buf + buf_used, buf_size - buf_used, "%s%s",
704                         method_str, idx < methods - 1 ? "," : "");
705                 if (buf_size <= buf_used) {
706                         /* Need more room than available, truncating. */
707                         *(*buf + (buf_size - 1)) = '\0';
708                         ast_log(LOG_WARNING, "Truncated identify_by string: %s\n", *buf);
709                         break;
710                 }
711         }
712
713         return 0;
714 }
715
716 static int redirect_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
717 {
718         struct ast_sip_endpoint *endpoint = obj;
719
720         if (!strcasecmp(var->value, "user")) {
721                 endpoint->redirect_method = AST_SIP_REDIRECT_USER;
722         } else if (!strcasecmp(var->value, "uri_core")) {
723                 endpoint->redirect_method = AST_SIP_REDIRECT_URI_CORE;
724         } else if (!strcasecmp(var->value, "uri_pjsip")) {
725                 endpoint->redirect_method = AST_SIP_REDIRECT_URI_PJSIP;
726         } else {
727                 ast_log(LOG_ERROR, "Unrecognized redirect method %s specified for endpoint %s\n",
728                         var->value, ast_sorcery_object_get_id(endpoint));
729                 return -1;
730         }
731
732         return 0;
733 }
734
735 static int direct_media_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
736 {
737         struct ast_sip_endpoint *endpoint = obj;
738
739         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
740                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
741         } else if (!strcasecmp(var->value, "update")) {
742                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
743         } else {
744                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
745                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
746                 return -1;
747         }
748         return 0;
749 }
750
751 static const char *id_configuration_refresh_methods[] = {
752         [AST_SIP_SESSION_REFRESH_METHOD_INVITE] = "invite",
753         [AST_SIP_SESSION_REFRESH_METHOD_UPDATE] = "update"
754 };
755
756 static int direct_media_method_to_str(const void *obj, const intptr_t *args, char **buf)
757 {
758         const struct ast_sip_endpoint *endpoint = obj;
759         if (ARRAY_IN_BOUNDS(endpoint->id.refresh_method, id_configuration_refresh_methods)) {
760                 *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
761         }
762         return 0;
763 }
764
765 static int connected_line_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
766 {
767         struct ast_sip_endpoint *endpoint = obj;
768
769         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
770                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
771         } else if (!strcasecmp(var->value, "update")) {
772                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
773         } else {
774                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
775                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
776                 return -1;
777         }
778         return 0;
779 }
780
781 static int connected_line_method_to_str(const void *obj, const intptr_t *args, char **buf)
782 {
783         const struct ast_sip_endpoint *endpoint = obj;
784         *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
785         return 0;
786 }
787
788 static int direct_media_glare_mitigation_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
789 {
790         struct ast_sip_endpoint *endpoint = obj;
791
792         if (!strcasecmp(var->value, "none")) {
793                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE;
794         } else if (!strcasecmp(var->value, "outgoing")) {
795                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING;
796         } else if (!strcasecmp(var->value, "incoming")) {
797                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING;
798         } else {
799                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
800                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
801                 return -1;
802         }
803
804         return 0;
805 }
806
807 static const char *direct_media_glare_mitigation_map[] = {
808         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE] = "none",
809         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING] = "outgoing",
810         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING] = "incoming"
811 };
812
813 static int direct_media_glare_mitigation_to_str(const void *obj, const intptr_t *args, char **buf)
814 {
815         const struct ast_sip_endpoint *endpoint = obj;
816         if (ARRAY_IN_BOUNDS(endpoint->media.direct_media.glare_mitigation, direct_media_glare_mitigation_map)) {
817                 *buf = ast_strdup(direct_media_glare_mitigation_map[endpoint->media.direct_media.glare_mitigation]);
818         }
819
820         return 0;
821 }
822
823 static int caller_id_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
824 {
825         struct ast_sip_endpoint *endpoint = obj;
826         char cid_name[80] = { '\0' };
827         char cid_num[80] = { '\0' };
828
829         ast_callerid_split(var->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
830         if (!ast_strlen_zero(cid_name)) {
831                 endpoint->id.self.name.str = ast_strdup(cid_name);
832                 if (!endpoint->id.self.name.str) {
833                         return -1;
834                 }
835                 endpoint->id.self.name.valid = 1;
836         }
837         if (!ast_strlen_zero(cid_num)) {
838                 endpoint->id.self.number.str = ast_strdup(cid_num);
839                 if (!endpoint->id.self.number.str) {
840                         return -1;
841                 }
842                 endpoint->id.self.number.valid = 1;
843         }
844         return 0;
845 }
846
847 static int caller_id_to_str(const void *obj, const intptr_t *args, char **buf)
848 {
849         const struct ast_sip_endpoint *endpoint = obj;
850         const char *name = S_COR(endpoint->id.self.name.valid,
851                                  endpoint->id.self.name.str, NULL);
852         const char *number = S_COR(endpoint->id.self.number.valid,
853                                    endpoint->id.self.number.str, NULL);
854
855         /* make sure size is at least 10 - that should cover the "<unknown>"
856            case as well as any additional formatting characters added in
857            the name and/or number case. */
858         int size = 10;
859         size += name ? strlen(name) : 0;
860         size += number ? strlen(number) : 0;
861
862         if (!(*buf = ast_calloc(size + 1, sizeof(char)))) {
863                 return -1;
864         }
865
866         ast_callerid_merge(*buf, size + 1, name, number, NULL);
867         return 0;
868 }
869
870 static int caller_id_privacy_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
871 {
872         struct ast_sip_endpoint *endpoint = obj;
873         int callingpres = ast_parse_caller_presentation(var->value);
874         if (callingpres == -1 && sscanf(var->value, "%d", &callingpres) != 1) {
875                 return -1;
876         }
877         endpoint->id.self.number.presentation = callingpres;
878         endpoint->id.self.name.presentation = callingpres;
879         return 0;
880 }
881
882 static int caller_id_privacy_to_str(const void *obj, const intptr_t *args, char **buf)
883 {
884         const struct ast_sip_endpoint *endpoint = obj;
885         const char *presentation = ast_named_caller_presentation(
886                 endpoint->id.self.name.presentation);
887
888         *buf = ast_strdup(presentation);
889         return 0;
890 }
891
892 static int caller_id_tag_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
893 {
894         struct ast_sip_endpoint *endpoint = obj;
895         endpoint->id.self.tag = ast_strdup(var->value);
896         return endpoint->id.self.tag ? 0 : -1;
897 }
898
899 static int caller_id_tag_to_str(const void *obj, const intptr_t *args, char **buf)
900 {
901         const struct ast_sip_endpoint *endpoint = obj;
902         *buf = ast_strdup(endpoint->id.self.tag);
903         return 0;
904 }
905
906 static int media_encryption_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
907 {
908         struct ast_sip_endpoint *endpoint = obj;
909
910         if (!strcasecmp("no", var->value)) {
911                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
912         } else if (!strcasecmp("sdes", var->value)) {
913                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_SDES;
914         } else if (!strcasecmp("dtls", var->value)) {
915                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_DTLS;
916                 return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, "dtlsenable", "yes");
917         } else {
918                 return -1;
919         }
920
921         return 0;
922 }
923
924 static const char *media_encryption_map[] = {
925         [AST_SIP_MEDIA_TRANSPORT_INVALID] = "invalid",
926         [AST_SIP_MEDIA_ENCRYPT_NONE] = "no",
927         [AST_SIP_MEDIA_ENCRYPT_SDES] = "sdes",
928         [AST_SIP_MEDIA_ENCRYPT_DTLS] = "dtls",
929 };
930
931 static int media_encryption_to_str(const void *obj, const intptr_t *args, char **buf)
932 {
933         const struct ast_sip_endpoint *endpoint = obj;
934         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.encryption, media_encryption_map)) {
935                 *buf = ast_strdup(media_encryption_map[
936                                           endpoint->media.rtp.encryption]);
937         }
938         return 0;
939 }
940
941 static int group_handler(const struct aco_option *opt,
942                          struct ast_variable *var, void *obj)
943 {
944         struct ast_sip_endpoint *endpoint = obj;
945
946         if (!strncmp(var->name, "call_group", 10)) {
947                 endpoint->pickup.callgroup = ast_get_group(var->value);
948         } else if (!strncmp(var->name, "pickup_group", 12)) {
949                 endpoint->pickup.pickupgroup = ast_get_group(var->value);
950         } else {
951                 return -1;
952         }
953
954         return 0;
955 }
956
957 static int callgroup_to_str(const void *obj, const intptr_t *args, char **buf)
958 {
959         const struct ast_sip_endpoint *endpoint = obj;
960
961         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
962                 return -1;
963         }
964
965         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.callgroup);
966         return 0;
967 }
968
969 static int pickupgroup_to_str(const void *obj, const intptr_t *args, char **buf)
970 {
971         const struct ast_sip_endpoint *endpoint = obj;
972
973         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
974                 return -1;
975         }
976
977         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.pickupgroup);
978         return 0;
979 }
980
981 static int named_groups_handler(const struct aco_option *opt,
982                                 struct ast_variable *var, void *obj)
983 {
984         struct ast_sip_endpoint *endpoint = obj;
985
986         if (!strncmp(var->name, "named_call_group", 16)) {
987                 if (ast_strlen_zero(var->value)) {
988                         endpoint->pickup.named_callgroups =
989                                 ast_unref_namedgroups(endpoint->pickup.named_callgroups);
990                 } else if (!(endpoint->pickup.named_callgroups =
991                       ast_get_namedgroups(var->value))) {
992                         return -1;
993                 }
994         } else if (!strncmp(var->name, "named_pickup_group", 18)) {
995                 if (ast_strlen_zero(var->value)) {
996                         endpoint->pickup.named_pickupgroups =
997                                 ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
998                 } else if (!(endpoint->pickup.named_pickupgroups =
999                       ast_get_namedgroups(var->value))) {
1000                         return -1;
1001                 }
1002         } else {
1003                 return -1;
1004         }
1005
1006         return 0;
1007 }
1008
1009 static int named_callgroups_to_str(const void *obj, const intptr_t *args, char **buf)
1010 {
1011         const struct ast_sip_endpoint *endpoint = obj;
1012         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
1013
1014         ast_print_namedgroups(&str, endpoint->pickup.named_callgroups);
1015         *buf = ast_strdup(ast_str_buffer(str));
1016         return 0;
1017 }
1018
1019 static int named_pickupgroups_to_str(const void *obj, const intptr_t *args, char **buf)
1020 {
1021         const struct ast_sip_endpoint *endpoint = obj;
1022         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
1023
1024         ast_print_namedgroups(&str, endpoint->pickup.named_pickupgroups);
1025         *buf = ast_strdup(ast_str_buffer(str));
1026         return 0;
1027 }
1028
1029 static int dtls_handler(const struct aco_option *opt,
1030                          struct ast_variable *var, void *obj)
1031 {
1032         struct ast_sip_endpoint *endpoint = obj;
1033         char *name = ast_strdupa(var->name);
1034         char *front = NULL;
1035         char *back = NULL;
1036         char *buf = name;
1037
1038         /* strip out underscores in the name */
1039         front = strtok_r(buf, "_", &back);
1040         while (front) {
1041                 int size = strlen(front);
1042                 ast_copy_string(buf, front, size + 1);
1043                 buf += size;
1044                 front = strtok_r(NULL, "_", &back);
1045         }
1046
1047         return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, name, var->value);
1048 }
1049
1050 static int dtlsverify_to_str(const void *obj, const intptr_t *args, char **buf)
1051 {
1052         const struct ast_sip_endpoint *endpoint = obj;
1053         *buf = ast_strdup(AST_YESNO(endpoint->media.rtp.dtls_cfg.verify));
1054         return 0;
1055 }
1056
1057 static int dtlsrekey_to_str(const void *obj, const intptr_t *args, char **buf)
1058 {
1059         const struct ast_sip_endpoint *endpoint = obj;
1060
1061         return ast_asprintf(
1062                 buf, "%u", endpoint->media.rtp.dtls_cfg.rekey) >=0 ? 0 : -1;
1063 }
1064
1065 static int dtlsautogeneratecert_to_str(const void *obj, const intptr_t *args, char **buf)
1066 {
1067         const struct ast_sip_endpoint *endpoint = obj;
1068         *buf = ast_strdup(AST_YESNO(endpoint->media.rtp.dtls_cfg.ephemeral_cert));
1069         return 0;
1070 }
1071
1072 static int dtlscertfile_to_str(const void *obj, const intptr_t *args, char **buf)
1073 {
1074         const struct ast_sip_endpoint *endpoint = obj;
1075         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.certfile);
1076         return 0;
1077 }
1078
1079 static int dtlsprivatekey_to_str(const void *obj, const intptr_t *args, char **buf)
1080 {
1081         const struct ast_sip_endpoint *endpoint = obj;
1082         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.pvtfile);
1083         return 0;
1084 }
1085
1086 static int dtlscipher_to_str(const void *obj, const intptr_t *args, char **buf)
1087 {
1088         const struct ast_sip_endpoint *endpoint = obj;
1089         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cipher);
1090         return 0;
1091 }
1092
1093 static int dtlscafile_to_str(const void *obj, const intptr_t *args, char **buf)
1094 {
1095         const struct ast_sip_endpoint *endpoint = obj;
1096         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cafile);
1097         return 0;
1098 }
1099
1100 static int dtlscapath_to_str(const void *obj, const intptr_t *args, char **buf)
1101 {
1102         const struct ast_sip_endpoint *endpoint = obj;
1103         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.capath);
1104         return 0;
1105 }
1106
1107 static const char *ast_rtp_dtls_setup_map[] = {
1108         [AST_RTP_DTLS_SETUP_ACTIVE] = "active",
1109         [AST_RTP_DTLS_SETUP_PASSIVE] = "passive",
1110         [AST_RTP_DTLS_SETUP_ACTPASS] = "actpass",
1111         [AST_RTP_DTLS_SETUP_HOLDCONN] = "holdconn",
1112 };
1113
1114 static int dtlssetup_to_str(const void *obj, const intptr_t *args, char **buf)
1115 {
1116         const struct ast_sip_endpoint *endpoint = obj;
1117         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.default_setup, ast_rtp_dtls_setup_map)) {
1118                 *buf = ast_strdup(ast_rtp_dtls_setup_map[endpoint->media.rtp.dtls_cfg.default_setup]);
1119         }
1120         return 0;
1121 }
1122
1123 static const char *ast_rtp_dtls_fingerprint_map[] = {
1124         [AST_RTP_DTLS_HASH_SHA256] = "SHA-256",
1125         [AST_RTP_DTLS_HASH_SHA1] = "SHA-1",
1126 };
1127
1128 static int dtlsfingerprint_to_str(const void *obj, const intptr_t *args, char **buf)
1129 {
1130         const struct ast_sip_endpoint *endpoint = obj;
1131         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.hash, ast_rtp_dtls_fingerprint_map)) {
1132                 *buf = ast_strdup(ast_rtp_dtls_fingerprint_map[endpoint->media.rtp.dtls_cfg.hash]);
1133         }
1134         return 0;
1135 }
1136
1137 static int t38udptl_ec_handler(const struct aco_option *opt,
1138         struct ast_variable *var, void *obj)
1139 {
1140         struct ast_sip_endpoint *endpoint = obj;
1141
1142         if (!strcmp(var->value, "none")) {
1143                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_NONE;
1144         } else if (!strcmp(var->value, "fec")) {
1145                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_FEC;
1146         } else if (!strcmp(var->value, "redundancy")) {
1147                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_REDUNDANCY;
1148         } else {
1149                 return -1;
1150         }
1151
1152         return 0;
1153 }
1154
1155 static const char *ast_t38_ec_modes_map[] = {
1156         [UDPTL_ERROR_CORRECTION_NONE] = "none",
1157         [UDPTL_ERROR_CORRECTION_FEC] = "fec",
1158         [UDPTL_ERROR_CORRECTION_REDUNDANCY] = "redundancy"
1159 };
1160
1161 static int t38udptl_ec_to_str(const void *obj, const intptr_t *args, char **buf)
1162 {
1163         const struct ast_sip_endpoint *endpoint = obj;
1164         if (ARRAY_IN_BOUNDS(endpoint->media.t38.error_correction, ast_t38_ec_modes_map)) {
1165                 *buf = ast_strdup(ast_t38_ec_modes_map[
1166                                           endpoint->media.t38.error_correction]);
1167         }
1168         return 0;
1169 }
1170
1171 static int tos_handler(const struct aco_option *opt,
1172         struct ast_variable *var, void *obj)
1173 {
1174         struct ast_sip_endpoint *endpoint = obj;
1175         unsigned int value;
1176
1177         if (ast_str2tos(var->value, &value)) {
1178                 ast_log(LOG_ERROR, "Error configuring endpoint '%s' - Could not "
1179                         "interpret '%s' value '%s'\n",
1180                         ast_sorcery_object_get_id(endpoint), var->name, var->value);
1181                 return -1;
1182         }
1183
1184         if (!strcmp(var->name, "tos_audio")) {
1185                 endpoint->media.tos_audio = value;
1186         } else if (!strcmp(var->name, "tos_video")) {
1187                 endpoint->media.tos_video = value;
1188         } else {
1189                 /* If we reach this point, someone called the tos_handler when they shouldn't have. */
1190                 ast_assert(0);
1191                 return -1;
1192         }
1193         return 0;
1194 }
1195
1196 static int tos_audio_to_str(const void *obj, const intptr_t *args, char **buf)
1197 {
1198         const struct ast_sip_endpoint *endpoint = obj;
1199
1200         if (ast_asprintf(buf, "%u", endpoint->media.tos_audio) == -1) {
1201                 return -1;
1202         }
1203         return 0;
1204 }
1205
1206 static int tos_video_to_str(const void *obj, const intptr_t *args, char **buf)
1207 {
1208         const struct ast_sip_endpoint *endpoint = obj;
1209
1210         if (ast_asprintf(buf, "%u", endpoint->media.tos_video) == -1) {
1211                 return -1;
1212         }
1213         return 0;
1214 }
1215
1216 static int from_user_handler(const struct aco_option *opt,
1217         struct ast_variable *var, void *obj)
1218 {
1219         struct ast_sip_endpoint *endpoint = obj;
1220         /* Valid non-alphanumeric characters for URI */
1221         char *valid_uri_marks = "-._~%!$&'()*+,;=:";
1222         const char *val;
1223
1224         for (val = var->value; *val; val++) {
1225                 if (!isalpha(*val) && !isdigit(*val) && !strchr(valid_uri_marks, *val)) {
1226                         ast_log(LOG_ERROR, "Error configuring endpoint '%s' - '%s' field "
1227                         "contains invalid character '%c'\n",
1228                         ast_sorcery_object_get_id(endpoint), var->name, *val);
1229                         return -1;
1230                 }
1231         }
1232
1233         ast_string_field_set(endpoint, fromuser, var->value);
1234
1235         return 0;
1236 }
1237
1238 static int from_user_to_str(const void *obj, const intptr_t *args, char **buf)
1239 {
1240         const struct ast_sip_endpoint *endpoint = obj;
1241
1242         *buf = ast_strdup(endpoint->fromuser);
1243
1244         return 0;
1245 }
1246
1247 static int set_var_handler(const struct aco_option *opt,
1248         struct ast_variable *var, void *obj)
1249 {
1250         struct ast_sip_endpoint *endpoint = obj;
1251         struct ast_variable *new_var;
1252         char *name;
1253         char *val;
1254
1255         if (ast_strlen_zero(var->value)) {
1256                 return 0;
1257         }
1258
1259         name = ast_strdupa(var->value);
1260         val = strchr(name, '=');
1261
1262         if (!val) {
1263                 return -1;
1264         }
1265
1266         *val++ = '\0';
1267
1268         if (!(new_var = ast_variable_new(name, val, ""))) {
1269                 return -1;
1270         }
1271
1272         ast_variable_list_append(&endpoint->channel_vars, new_var);
1273
1274         return 0;
1275 }
1276
1277 static int set_var_to_str(const void *obj, const intptr_t *args, char **buf)
1278 {
1279         struct ast_str *str = ast_str_create(MAX_OBJECT_FIELD);
1280         const struct ast_sip_endpoint *endpoint = obj;
1281         struct ast_variable *var;
1282
1283         for (var = endpoint->channel_vars; var; var = var->next) {
1284                 ast_str_append(&str, 0, "%s=%s,", var->name, var->value);
1285         }
1286
1287         *buf = ast_strdup(ast_str_truncate(str, -1));
1288         ast_free(str);
1289         return 0;
1290 }
1291
1292 static int set_var_to_vl(const void *obj, struct ast_variable **fields)
1293 {
1294         const struct ast_sip_endpoint *endpoint = obj;
1295         if (endpoint->channel_vars) {
1296                 *fields = ast_variables_dup(endpoint->channel_vars);
1297         }
1298         return 0;
1299 }
1300
1301 static int voicemail_extension_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1302 {
1303         struct ast_sip_endpoint *endpoint = obj;
1304
1305         endpoint->subscription.mwi.voicemail_extension = ast_strdup(var->value);
1306
1307         return endpoint->subscription.mwi.voicemail_extension ? 0 : -1;
1308 }
1309
1310 static int voicemail_extension_to_str(const void *obj, const intptr_t *args, char **buf)
1311 {
1312         const struct ast_sip_endpoint *endpoint = obj;
1313
1314         *buf = ast_strdup(endpoint->subscription.mwi.voicemail_extension);
1315
1316         return 0;
1317 }
1318
1319 static int contact_user_handler(const struct aco_option *opt,
1320         struct ast_variable *var, void *obj)
1321 {
1322         struct ast_sip_endpoint *endpoint = obj;
1323
1324         endpoint->contact_user = ast_strdup(var->value);
1325         if (!endpoint->contact_user) {
1326                 return -1;
1327         }
1328
1329         return 0;
1330 }
1331
1332 static int contact_user_to_str(const void *obj, const intptr_t *args, char **buf)
1333 {
1334         const struct ast_sip_endpoint *endpoint = obj;
1335
1336         *buf = ast_strdup(endpoint->contact_user);
1337         if (!(*buf)) {
1338                 return -1;
1339         }
1340
1341         return 0;
1342 }
1343
1344 static void *sip_nat_hook_alloc(const char *name)
1345 {
1346         return ast_sorcery_generic_alloc(sizeof(struct ast_sip_nat_hook), NULL);
1347 }
1348
1349 /*! \brief Destructor function for persistent endpoint information */
1350 static void persistent_endpoint_destroy(void *obj)
1351 {
1352         struct sip_persistent_endpoint *persistent = obj;
1353
1354         ast_endpoint_shutdown(persistent->endpoint);
1355         ast_free(persistent->aors);
1356 }
1357
1358 int ast_sip_persistent_endpoint_update_state(const char *endpoint_name, enum ast_endpoint_state state)
1359 {
1360         struct sip_persistent_endpoint *persistent;
1361
1362         ao2_lock(persistent_endpoints);
1363         persistent = ao2_find(persistent_endpoints, endpoint_name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
1364         if (persistent) {
1365                 endpoint_update_state(persistent->endpoint, state);
1366                 ao2_ref(persistent, -1);
1367         }
1368         ao2_unlock(persistent_endpoints);
1369         return persistent ? 0 : -1;
1370 }
1371
1372 /*! \brief Internal function which finds (or creates) persistent endpoint information */
1373 static struct ast_endpoint *persistent_endpoint_find_or_create(const struct ast_sip_endpoint *endpoint)
1374 {
1375         RAII_VAR(struct sip_persistent_endpoint *, persistent, NULL, ao2_cleanup);
1376         SCOPED_AO2LOCK(lock, persistent_endpoints);
1377
1378         persistent = ao2_find(persistent_endpoints, ast_sorcery_object_get_id(endpoint),
1379                 OBJ_SEARCH_KEY | OBJ_NOLOCK);
1380         if (!persistent) {
1381                 persistent = ao2_alloc_options(sizeof(*persistent), persistent_endpoint_destroy,
1382                         AO2_ALLOC_OPT_LOCK_NOLOCK);
1383                 if (!persistent) {
1384                         return NULL;
1385                 }
1386
1387                 persistent->endpoint = ast_endpoint_create("PJSIP",
1388                         ast_sorcery_object_get_id(endpoint));
1389                 if (!persistent->endpoint) {
1390                         return NULL;
1391                 }
1392
1393                 persistent->aors = ast_strdup(endpoint->aors);
1394                 if (!persistent->aors) {
1395                         return NULL;
1396                 }
1397
1398                 ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_OFFLINE);
1399
1400                 ao2_link_flags(persistent_endpoints, persistent, OBJ_NOLOCK);
1401         } else if (strcmp(persistent->aors, endpoint->aors)) {
1402                 char *new_aors = ast_strdup(endpoint->aors);
1403
1404                 /* make sure we don't NULL persistent->aors if allocation fails. */
1405                 if (new_aors) {
1406                         ast_free(persistent->aors);
1407                         persistent->aors = new_aors;
1408                 }
1409         }
1410
1411         ao2_ref(persistent->endpoint, +1);
1412         return persistent->endpoint;
1413 }
1414
1415 /*! \brief Callback function for when an object is finalized */
1416 static int sip_endpoint_apply_handler(const struct ast_sorcery *sorcery, void *obj)
1417 {
1418         struct ast_sip_endpoint *endpoint = obj;
1419
1420         if (!(endpoint->persistent = persistent_endpoint_find_or_create(endpoint))) {
1421                 return -1;
1422         }
1423
1424         if (endpoint->extensions.timer.min_se < 90) {
1425                 ast_log(LOG_ERROR, "Session timer minimum expires time must be 90 or greater on endpoint '%s'\n",
1426                         ast_sorcery_object_get_id(endpoint));
1427                 return -1;
1428         } else if (endpoint->extensions.timer.sess_expires < endpoint->extensions.timer.min_se) {
1429                 ast_log(LOG_ERROR, "Session timer expires must be greater than minimum session expires time on endpoint '%s'\n",
1430                         ast_sorcery_object_get_id(endpoint));
1431                 return -1;
1432         }
1433
1434         if (ast_rtp_dtls_cfg_validate(&endpoint->media.rtp.dtls_cfg)) {
1435                 return -1;
1436         }
1437
1438         endpoint->media.topology = ast_stream_topology_create_from_format_cap(endpoint->media.codecs);
1439         if (!endpoint->media.topology) {
1440                 return -1;
1441         }
1442
1443         endpoint->media.rtcp_mux |= endpoint->media.bundle;
1444
1445         /*
1446          * If webrtc has been enabled then enable those attributes, and default
1447          * some, that are needed in order for webrtc to work.
1448          */
1449         endpoint->media.bundle |= endpoint->media.webrtc;
1450         endpoint->media.rtcp_mux |= endpoint->media.webrtc;
1451         endpoint->media.rtp.use_avpf |= endpoint->media.webrtc;
1452         endpoint->media.rtp.ice_support |= endpoint->media.webrtc;
1453         endpoint->media.rtp.use_received_transport |= endpoint->media.webrtc;
1454
1455         if (endpoint->media.webrtc) {
1456                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_DTLS;
1457                 endpoint->media.rtp.dtls_cfg.enabled = 1;
1458                 endpoint->media.rtp.dtls_cfg.default_setup = AST_RTP_DTLS_SETUP_ACTPASS;
1459                 endpoint->media.rtp.dtls_cfg.verify = AST_RTP_DTLS_VERIFY_FINGERPRINT;
1460
1461                 if (ast_strlen_zero(endpoint->media.rtp.dtls_cfg.certfile)) {
1462                         /* If no certificate has been specified, try to automatically create one */
1463                         endpoint->media.rtp.dtls_cfg.ephemeral_cert = 1;
1464                 }
1465         }
1466
1467         return 0;
1468 }
1469
1470 const char *ast_sip_get_device_state(const struct ast_sip_endpoint *endpoint)
1471 {
1472         char device[MAX_OBJECT_FIELD];
1473
1474         snprintf(device, MAX_OBJECT_FIELD, "PJSIP/%s", ast_sorcery_object_get_id(endpoint));
1475         return ast_devstate2str(ast_device_state(device));
1476 }
1477
1478 struct ast_endpoint_snapshot *ast_sip_get_endpoint_snapshot(
1479         const struct ast_sip_endpoint *endpoint)
1480 {
1481         return ast_endpoint_latest_snapshot(
1482                 ast_endpoint_get_tech(endpoint->persistent),
1483                 ast_endpoint_get_resource(endpoint->persistent));
1484 }
1485
1486 int ast_sip_for_each_channel_snapshot(
1487         const struct ast_endpoint_snapshot *endpoint_snapshot,
1488         ao2_callback_fn on_channel_snapshot, void *arg)
1489 {
1490         int num, num_channels = endpoint_snapshot->num_channels;
1491
1492         if (!on_channel_snapshot || !num_channels) {
1493                 return 0;
1494         }
1495
1496         for (num = 0; num < num_channels; ++num) {
1497                 RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1498                 int res;
1499
1500                 snapshot = ast_channel_snapshot_get_latest(endpoint_snapshot->channel_ids[num]);
1501                 if (!snapshot) {
1502                         continue;
1503                 }
1504
1505                 res = on_channel_snapshot(snapshot, arg, 0);
1506                 if (res) {
1507                         return -1;
1508                 }
1509         }
1510         return 0;
1511 }
1512
1513 int ast_sip_for_each_channel(
1514         const struct ast_sip_endpoint *endpoint,
1515         ao2_callback_fn on_channel_snapshot, void *arg)
1516 {
1517         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1518         return ast_sip_for_each_channel_snapshot(endpoint_snapshot, on_channel_snapshot, arg);
1519 }
1520
1521 static int active_channels_to_str_cb(void *object, void *arg, int flags)
1522 {
1523         const struct ast_channel_snapshot *snapshot = object;
1524         struct ast_str **buf = arg;
1525         ast_str_append(buf, 0, "%s,", snapshot->name);
1526         return 0;
1527 }
1528
1529 static void active_channels_to_str(const struct ast_sip_endpoint *endpoint,
1530                                    struct ast_str **str)
1531 {
1532
1533         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot,
1534                  ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1535
1536         if (endpoint_snapshot) {
1537                 return;
1538         }
1539
1540         ast_sip_for_each_channel_snapshot(endpoint_snapshot,
1541                                           active_channels_to_str_cb, str);
1542         ast_str_truncate(*str, -1);
1543 }
1544
1545 #define AMI_DEFAULT_STR_SIZE 512
1546
1547 struct ast_str *ast_sip_create_ami_event(const char *event, struct ast_sip_ami *ami)
1548 {
1549         struct ast_str *buf = ast_str_create(AMI_DEFAULT_STR_SIZE);
1550
1551         if (!(buf)) {
1552                 astman_send_error_va(ami->s, ami->m, "Unable create event "
1553                                      "for %s\n", event);
1554                 return NULL;
1555         }
1556
1557         ast_str_set(&buf, 0, "Event: %s\r\n", event);
1558         if (!ast_strlen_zero(ami->action_id)) {
1559                 ast_str_append(&buf, 0, "ActionID: %s\r\n", ami->action_id);
1560         }
1561         return buf;
1562 }
1563
1564 static void sip_sorcery_object_ami_set_type_name(const void *obj, struct ast_str **buf)
1565 {
1566         ast_str_append(buf, 0, "ObjectType: %s\r\n",
1567                        ast_sorcery_object_get_type(obj));
1568         ast_str_append(buf, 0, "ObjectName: %s\r\n",
1569                        ast_sorcery_object_get_id(obj));
1570 }
1571
1572 int ast_sip_sorcery_object_to_ami(const void *obj, struct ast_str **buf)
1573 {
1574         RAII_VAR(struct ast_variable *, objset, ast_sorcery_objectset_create2(
1575                          ast_sip_get_sorcery(), obj, AST_HANDLER_ONLY_STRING), ast_variables_destroy);
1576         struct ast_variable *i;
1577
1578         if (!objset) {
1579                 return -1;
1580         }
1581
1582         sip_sorcery_object_ami_set_type_name(obj, buf);
1583
1584         for (i = objset; i; i = i->next) {
1585                 RAII_VAR(char *, camel, ast_to_camel_case(i->name), ast_free);
1586                 ast_str_append(buf, 0, "%s: %s\r\n", camel, i->value);
1587         }
1588
1589         return 0;
1590 }
1591
1592 static int sip_endpoints_aors_ami(void *obj, void *arg, int flags)
1593 {
1594         struct ast_sip_aor *aor = obj;
1595         struct ast_str **buf = arg;
1596
1597         ast_str_append(buf, 0, "Contacts: ");
1598         ast_sip_for_each_contact(aor, ast_sip_contact_to_str, arg);
1599         ast_str_append(buf, 0, "\r\n");
1600
1601         return 0;
1602 }
1603
1604 static int sip_endpoint_to_ami(const struct ast_sip_endpoint *endpoint,
1605                                struct ast_str **buf)
1606 {
1607         if (ast_sip_sorcery_object_to_ami(endpoint, buf)) {
1608                 return -1;
1609         }
1610
1611         ast_str_append(buf, 0, "DeviceState: %s\r\n",
1612                        ast_sip_get_device_state(endpoint));
1613
1614         ast_str_append(buf, 0, "ActiveChannels: ");
1615         active_channels_to_str(endpoint, buf);
1616         ast_str_append(buf, 0, "\r\n");
1617
1618         return 0;
1619 }
1620
1621 static int format_ami_endpoint(const struct ast_sip_endpoint *endpoint,
1622                                struct ast_sip_ami *ami)
1623 {
1624         RAII_VAR(struct ast_str *, buf,
1625                  ast_sip_create_ami_event("EndpointDetail", ami), ast_free);
1626
1627         if (!buf) {
1628                 return -1;
1629         }
1630
1631         sip_endpoint_to_ami(endpoint, &buf);
1632         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1633         return 0;
1634 }
1635
1636 #define AMI_SHOW_ENDPOINTS "PJSIPShowEndpoints"
1637 #define AMI_SHOW_ENDPOINT "PJSIPShowEndpoint"
1638
1639 static int ami_show_endpoint(struct mansession *s, const struct message *m)
1640 {
1641         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"),
1642                 .count = 0, };
1643         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1644         const char *endpoint_name = astman_get_header(m, "Endpoint");
1645         int count = 0;
1646
1647         if (ast_strlen_zero(endpoint_name)) {
1648                 astman_send_error_va(s, m, "%s requires an endpoint name\n",
1649                         AMI_SHOW_ENDPOINT);
1650                 return 0;
1651         }
1652
1653         if (!strncasecmp(endpoint_name, "pjsip/", 6)) {
1654                 endpoint_name += 6;
1655         }
1656
1657         if (!(endpoint = ast_sorcery_retrieve_by_id(
1658                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1659                 astman_send_error_va(s, m, "Unable to retrieve endpoint %s\n",
1660                         endpoint_name);
1661                 return 0;
1662         }
1663
1664         astman_send_listack(s, m, "Following are Events for each object associated with the Endpoint",
1665                 "start");
1666
1667         /* the endpoint detail needs to always come first so apply as such */
1668         if (format_ami_endpoint(endpoint, &ami) ||
1669             ast_sip_format_endpoint_ami(endpoint, &ami, &count)) {
1670                 astman_send_error_va(s, m, "Unable to format endpoint %s\n",
1671                         endpoint_name);
1672         }
1673
1674         astman_send_list_complete_start(s, m, "EndpointDetailComplete", ami.count + 1);
1675         astman_send_list_complete_end(s);
1676
1677         return 0;
1678 }
1679
1680 static int format_str_append_auth(const struct ast_sip_auth_vector *auths,
1681                                   struct ast_str **buf)
1682 {
1683         char *str = NULL;
1684         if (ast_sip_auths_to_str(auths, &str)) {
1685                 return -1;
1686         }
1687         ast_str_append(buf, 0, "%s", str ? str : "");
1688         ast_free(str);
1689         return 0;
1690 }
1691
1692 static int format_ami_endpoints(void *obj, void *arg, int flags)
1693 {
1694
1695         struct ast_sip_endpoint *endpoint = obj;
1696         struct ast_sip_ami *ami = arg;
1697         RAII_VAR(struct ast_str *, buf,
1698                  ast_sip_create_ami_event("EndpointList", ami), ast_free);
1699
1700         if (!buf) {
1701                 return CMP_STOP;
1702         }
1703
1704         sip_sorcery_object_ami_set_type_name(endpoint, &buf);
1705         ast_str_append(&buf, 0, "Transport: %s\r\n",
1706                        endpoint->transport);
1707         ast_str_append(&buf, 0, "Aor: %s\r\n",
1708                        endpoint->aors);
1709
1710         ast_str_append(&buf, 0, "Auths: ");
1711         format_str_append_auth(&endpoint->inbound_auths, &buf);
1712         ast_str_append(&buf, 0, "\r\n");
1713
1714         ast_str_append(&buf, 0, "OutboundAuths: ");
1715         format_str_append_auth(&endpoint->outbound_auths, &buf);
1716         ast_str_append(&buf, 0, "\r\n");
1717
1718         ast_sip_for_each_aor(endpoint->aors,
1719                              sip_endpoints_aors_ami, &buf);
1720
1721         ast_str_append(&buf, 0, "DeviceState: %s\r\n",
1722                        ast_sip_get_device_state(endpoint));
1723
1724         ast_str_append(&buf, 0, "ActiveChannels: ");
1725         active_channels_to_str(endpoint, &buf);
1726         ast_str_append(&buf, 0, "\r\n");
1727
1728         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1729         return 0;
1730 }
1731
1732 static int ami_show_endpoints(struct mansession *s, const struct message *m)
1733 {
1734         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
1735         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
1736         int num;
1737
1738         endpoints = ast_sip_get_endpoints();
1739         if (!endpoints) {
1740                 astman_send_error(s, m, "Could not get endpoints\n");
1741                 return 0;
1742         }
1743
1744         if (!(num = ao2_container_count(endpoints))) {
1745                 astman_send_error(s, m, "No endpoints found\n");
1746                 return 0;
1747         }
1748
1749         astman_send_listack(s, m, "A listing of Endpoints follows, presented as EndpointList events",
1750                 "start");
1751
1752         ao2_callback(endpoints, OBJ_NODATA, format_ami_endpoints, &ami);
1753
1754         astman_send_list_complete_start(s, m, "EndpointListComplete", num);
1755         astman_send_list_complete_end(s);
1756         return 0;
1757 }
1758
1759 static struct ao2_container *cli_endpoint_get_container(const char *regex)
1760 {
1761         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
1762         struct ao2_container *s_container;
1763
1764         container = ast_sorcery_retrieve_by_regex(sip_sorcery, "endpoint", regex);
1765         if (!container) {
1766                 return NULL;
1767         }
1768
1769         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
1770                 (void *)ast_sorcery_object_id_sort, (void *)ast_sorcery_object_id_compare);
1771         if (!s_container) {
1772                 return NULL;
1773         }
1774
1775         if (ao2_container_dup(s_container, container, 0)) {
1776                 ao2_ref(s_container, -1);
1777                 return NULL;
1778         }
1779
1780         return s_container;
1781 }
1782
1783 static int cli_endpoint_iterate(void *obj, ao2_callback_fn callback, void *args)
1784 {
1785         ao2_callback(obj, OBJ_NODATA, callback, args);
1786
1787         return 0;
1788 }
1789
1790 static void *cli_endpoint_retrieve_by_id(const char *id)
1791 {
1792         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", id);
1793 }
1794
1795 static void cli_endpoint_print_child_header(char *type, struct ast_sip_cli_context *context)
1796 {
1797         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1798
1799         formatter_entry = ast_sip_lookup_cli_formatter(type);
1800         if (formatter_entry) {
1801                 formatter_entry->print_header(NULL, context, 0);
1802         }
1803 }
1804
1805 static int cli_endpoint_print_header(void *obj, void *arg, int flags)
1806 {
1807         struct ast_sip_cli_context *context = arg;
1808
1809         ast_assert(context->output_buffer != NULL);
1810
1811         ast_str_append(&context->output_buffer, 0,
1812                         " Endpoint:  <Endpoint/CID.....................................>  <State.....>  <Channels.>\n");
1813
1814         if (context->recurse) {
1815                 context->indent_level++;
1816                 cli_endpoint_print_child_header("auth", context);
1817                 cli_endpoint_print_child_header("aor", context);
1818                 cli_endpoint_print_child_header("transport", context);
1819                 cli_endpoint_print_child_header("identify", context);
1820                 cli_endpoint_print_child_header("channel", context);
1821                 context->indent_level--;
1822         }
1823
1824         return 0;
1825 }
1826
1827 static void cli_endpoint_print_child_body(char *type, const void *obj, struct ast_sip_cli_context *context)
1828 {
1829         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1830
1831         formatter_entry = ast_sip_lookup_cli_formatter(type);
1832         if (formatter_entry) {
1833                 formatter_entry->iterate((void *)obj, formatter_entry->print_body, context);
1834         }
1835 }
1836
1837 static int cli_endpoint_print_body(void *obj, void *arg, int flags)
1838 {
1839         struct ast_sip_endpoint *endpoint = obj;
1840         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1841         struct ast_sip_cli_context *context = arg;
1842         const char *id = ast_sorcery_object_get_id(endpoint);
1843         char *print_name = NULL;
1844         int print_name_len;
1845         char *number = S_COR(endpoint->id.self.number.valid,
1846                 endpoint->id.self.number.str, NULL);
1847         int indent;
1848         int flexwidth;
1849
1850         ast_assert(context->output_buffer != NULL);
1851
1852         if (number) {
1853                 print_name_len = strlen(id) + strlen(number) + 2;
1854                 print_name = ast_alloca(print_name_len);
1855                 snprintf(print_name, print_name_len, "%s/%s", id, number);
1856         }
1857
1858         indent = CLI_INDENT_TO_SPACES(context->indent_level);
1859         flexwidth = CLI_LAST_TABSTOP - indent - 2;
1860
1861         ast_str_append(&context->output_buffer, 0, "%*s:  %-*.*s  %-12.12s  %d of %.0f\n",
1862                 indent, "Endpoint",
1863                 flexwidth, flexwidth, print_name ? print_name : id,
1864                 ast_sip_get_device_state(endpoint),
1865                 endpoint_snapshot->num_channels,
1866                 (double) endpoint->devicestate_busy_at ? endpoint->devicestate_busy_at :
1867                                                                                                                 INFINITY
1868                                                                                                                 );
1869
1870         if (context->recurse) {
1871                 context->indent_level++;
1872
1873                 context->auth_direction = "Out";
1874                 cli_endpoint_print_child_body("auth", &endpoint->outbound_auths, context);
1875                 context->auth_direction = "In";
1876                 cli_endpoint_print_child_body("auth", &endpoint->inbound_auths, context);
1877
1878                 cli_endpoint_print_child_body("aor", endpoint->aors, context);
1879                 cli_endpoint_print_child_body("transport", endpoint, context);
1880                 cli_endpoint_print_child_body("identify", endpoint, context);
1881                 cli_endpoint_print_child_body("channel", endpoint, context);
1882
1883                 context->indent_level--;
1884
1885                 if (context->indent_level == 0) {
1886                         ast_str_append(&context->output_buffer, 0, "\n");
1887                 }
1888         }
1889
1890         if (context->show_details || (context->show_details_only_level_0 && context->indent_level == 0)) {
1891                 ast_str_append(&context->output_buffer, 0, "\n");
1892                 ast_sip_cli_print_sorcery_objectset(endpoint, context, 0);
1893         }
1894
1895         return 0;
1896 }
1897
1898 static struct ast_cli_entry cli_commands[] = {
1899         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "List PJSIP Endpoints",
1900                 .command = "pjsip list endpoints",
1901                 .usage = "Usage: pjsip list endpoints [ like <pattern> ]\n"
1902                                 "       List the configured PJSIP endpoints\n"
1903                                 "       Optional regular expression pattern is used to filter the list.\n"),
1904         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoints",
1905                 .command = "pjsip show endpoints",
1906                 .usage = "Usage: pjsip show endpoints [ like <pattern> ]\n"
1907                                 "       List(detailed) the configured PJSIP endpoints\n"
1908                                 "       Optional regular expression pattern is used to filter the list.\n"),
1909         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoint",
1910                 .command = "pjsip show endpoint",
1911                 .usage = "Usage: pjsip show endpoint <id>\n"
1912                                  "       Show the configured PJSIP endpoint\n"),
1913 };
1914
1915 struct ast_sip_cli_formatter_entry *channel_formatter;
1916 struct ast_sip_cli_formatter_entry *endpoint_formatter;
1917
1918 static void load_all_endpoints(void)
1919 {
1920         struct ao2_container *endpoints;
1921
1922         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1923         ao2_cleanup(endpoints);
1924 }
1925
1926 int ast_res_pjsip_initialize_configuration(void)
1927 {
1928         if (ast_manager_register_xml(AMI_SHOW_ENDPOINTS, EVENT_FLAG_SYSTEM, ami_show_endpoints) ||
1929             ast_manager_register_xml(AMI_SHOW_ENDPOINT, EVENT_FLAG_SYSTEM, ami_show_endpoint)) {
1930                 return -1;
1931         }
1932
1933         persistent_endpoints = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
1934                 PERSISTENT_BUCKETS, persistent_endpoint_hash, NULL, persistent_endpoint_cmp);
1935         if (!persistent_endpoints) {
1936                 return -1;
1937         }
1938
1939         if (!(sip_sorcery = ast_sorcery_open())) {
1940                 ast_log(LOG_ERROR, "Failed to open SIP sorcery failed to open\n");
1941                 return -1;
1942         }
1943
1944         ast_sip_initialize_cli();
1945
1946         if (ast_sip_initialize_sorcery_auth()) {
1947                 ast_log(LOG_ERROR, "Failed to register SIP authentication support\n");
1948                 ast_sorcery_unref(sip_sorcery);
1949                 sip_sorcery = NULL;
1950                 return -1;
1951         }
1952
1953         ast_sorcery_apply_default(sip_sorcery, "endpoint", "config", "pjsip.conf,criteria=type=endpoint");
1954         ast_sorcery_apply_default(sip_sorcery, "nat_hook", "memory", NULL);
1955
1956         if (ast_sorcery_object_register(sip_sorcery, "endpoint", ast_sip_endpoint_alloc, NULL, sip_endpoint_apply_handler)) {
1957                 ast_log(LOG_ERROR, "Failed to register SIP endpoint object with sorcery\n");
1958                 ast_sorcery_unref(sip_sorcery);
1959                 sip_sorcery = NULL;
1960                 return -1;
1961         }
1962
1963         if (ast_sorcery_internal_object_register(sip_sorcery, "nat_hook", sip_nat_hook_alloc, NULL, NULL)) {
1964                 ast_log(LOG_ERROR, "Failed to register nat_hook\n");
1965         }
1966
1967         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "type", "", OPT_NOOP_T, 0, 0);
1968         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "context", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, context));
1969         ast_sorcery_object_field_register_alias(sip_sorcery, "endpoint", "disallow", "", OPT_CODEC_T, 0, FLDSET(struct ast_sip_endpoint, media.codecs));
1970         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow", "", OPT_CODEC_T, 1, FLDSET(struct ast_sip_endpoint, media.codecs));
1971         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtmf_mode", "rfc4733", dtmf_handler, dtmf_to_str, NULL, 0, 0);
1972         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ipv6));
1973         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_symmetric", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.symmetric));
1974         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "ice_support", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ice_support));
1975         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_ptime", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_ptime));
1976         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_rport", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.force_rport));
1977         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rewrite_contact", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.rewrite_contact));
1978         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, transport));
1979         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, outbound_proxy));
1980         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_suggest", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, mohsuggest));
1981         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "100rel", "yes", prack_handler, prack_to_str, NULL, 0, 0);
1982         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "timers", "yes", timers_handler, timers_to_str, NULL, 0, 0);
1983         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "timers_min_se", "90", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, extensions.timer.min_se));
1984         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "timers_sess_expires", "1800", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, extensions.timer.sess_expires));
1985         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "auth", "", inbound_auth_handler, inbound_auths_to_str, NULL, 0, 0);
1986         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, NULL, 0, 0);
1987         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aors", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, aors));
1988         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_address", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.address));
1989         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "bind_rtp_to_media_address", "no", OPT_BOOL_T, 1, STRFLDSET(struct ast_sip_endpoint, media.bind_rtp_to_media_address));
1990         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "identify_by", "username,ip", ident_handler, ident_to_str, NULL, 0, 0);
1991         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "direct_media", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.direct_media.enabled));
1992         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "direct_media_method", "invite", direct_media_method_handler, direct_media_method_to_str, NULL, 0, 0);
1993         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "connected_line_method", "invite", connected_line_method_handler, connected_line_method_to_str, NULL, 0, 0);
1994         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "direct_media_glare_mitigation", "none", direct_media_glare_mitigation_handler, direct_media_glare_mitigation_to_str, NULL, 0, 0);
1995         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "disable_direct_media_on_nat", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.direct_media.disable_on_nat));
1996         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid", "", caller_id_handler, caller_id_to_str, NULL, 0, 0);
1997         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_privacy", "allowed_not_screened", caller_id_privacy_handler, caller_id_privacy_to_str, NULL, 0, 0);
1998         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_tag", "", caller_id_tag_handler, caller_id_tag_to_str, NULL, 0, 0);
1999         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_inbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_inbound));
2000         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_outbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_outbound));
2001         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_pai", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_pai));
2002         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_rpid", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_rpid));
2003         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rpid_immediate", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.rpid_immediate));
2004         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_diversion", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_diversion));
2005         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mailboxes", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.mailboxes));
2006         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "voicemail_extension", "", voicemail_extension_handler, voicemail_extension_to_str, NULL, 0, 0);
2007         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aggregate_mwi", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.aggregate));
2008         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_subscribe_replaces_unsolicited", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.subscribe_replaces_unsolicited));
2009         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "media_encryption", "no", media_encryption_handler, media_encryption_to_str, NULL, 0, 0);
2010         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_avpf", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_avpf));
2011         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_avp", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.force_avp));
2012         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_use_received_transport", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_received_transport));
2013         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_keepalive", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.keepalive));
2014         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_timeout", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.timeout));
2015         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_timeout_hold", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.timeout_hold));
2016         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "one_touch_recording", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, info.recording.enabled));
2017         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "inband_progress", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, inband_progress));
2018         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "call_group", "", group_handler, callgroup_to_str, NULL, 0, 0);
2019         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "pickup_group", "", group_handler, pickupgroup_to_str, NULL, 0, 0);
2020         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_call_group", "", named_groups_handler, named_callgroups_to_str, NULL, 0, 0);
2021         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_pickup_group", "", named_groups_handler, named_pickupgroups_to_str, NULL, 0, 0);
2022         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "device_state_busy_at", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, devicestate_busy_at));
2023         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.enabled));
2024         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "t38_udptl_ec", "none", t38udptl_ec_handler, t38udptl_ec_to_str, NULL, 0, 0);
2025         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_maxdatagram", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.t38.maxdatagram));
2026         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, faxdetect));
2027         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect_timeout", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, faxdetect_timeout));
2028         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_nat", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.nat));
2029         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.ipv6));
2030         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tone_zone", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, zone));
2031         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "language", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, language));
2032         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_on_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.onfeature));
2033         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_off_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.offfeature));
2034         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_transfer", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allowtransfer));
2035         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "user_eq_phone", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, usereqphone));
2036         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_passthrough", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, moh_passthrough));
2037         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_owner", "-", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpowner));
2038         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_session", "Asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpsession));
2039         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_audio", "0", tos_handler, tos_audio_to_str, NULL, 0, 0);
2040         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_video", "0", tos_handler, tos_video_to_str, NULL, 0, 0);
2041         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_audio", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_audio));
2042         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_video", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_video));
2043         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_subscribe", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.allow));
2044         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sub_min_expiry", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, subscription.minexpiry));
2045         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "from_user", "", from_user_handler, from_user_to_str, NULL, 0, 0);
2046         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_domain", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromdomain));
2047         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.fromuser));
2048         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_engine", "asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.rtp.engine));
2049         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_verify", "no", dtls_handler, dtlsverify_to_str, NULL, 0, 0);
2050         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_rekey", "0", dtls_handler, dtlsrekey_to_str, NULL, 0, 0);
2051         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_auto_generate_cert", "no", dtls_handler, dtlsautogeneratecert_to_str, NULL, 0, 0);
2052         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cert_file", "", dtls_handler, dtlscertfile_to_str, NULL, 0, 0);
2053         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_private_key", "", dtls_handler, dtlsprivatekey_to_str, NULL, 0, 0);
2054         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cipher", "", dtls_handler, dtlscipher_to_str, NULL, 0, 0);
2055         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_file", "", dtls_handler, dtlscafile_to_str, NULL, 0, 0);
2056         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_path", "", dtls_handler, dtlscapath_to_str, NULL, 0, 0);
2057         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_setup", "", dtls_handler, dtlssetup_to_str, NULL, 0, 0);
2058         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_fingerprint", "", dtls_handler, dtlsfingerprint_to_str, NULL, 0, 0);
2059         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "srtp_tag_32", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.srtp_tag_32));
2060         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_encryption_optimistic", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.encryption_optimistic));
2061         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "g726_non_standard", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.g726_non_standard));
2062         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "redirect_method", "user", redirect_handler, NULL, NULL, 0, 0);
2063         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "set_var", "", set_var_handler, set_var_to_str, set_var_to_vl, 0, 0);
2064         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "message_context", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, message_context));
2065         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "accountcode", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, accountcode));
2066         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "deny", "", endpoint_acl_handler, NULL, NULL, 0, 0);
2067         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "permit", "", endpoint_acl_handler, NULL, NULL, 0, 0);
2068         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "acl", "", endpoint_acl_handler, acl_to_str, NULL, 0, 0);
2069         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_deny", "", endpoint_acl_handler, NULL, NULL, 0, 0);
2070         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_permit", "", endpoint_acl_handler, NULL, NULL, 0, 0);
2071         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_acl", "", endpoint_acl_handler, contact_acl_to_str, NULL, 0, 0);
2072         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "subscribe_context", "", OPT_CHAR_ARRAY_T, 0, CHARFLDSET(struct ast_sip_endpoint, subscription.context));
2073         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_user", "", contact_user_handler, contact_user_to_str, NULL, 0, 0);
2074         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "preferred_codec_only", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, preferred_codec_only));
2075         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "asymmetric_rtp_codec", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, asymmetric_rtp_codec));
2076         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtcp_mux", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtcp_mux));
2077         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_overlap", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allow_overlap));
2078         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "refer_blind_progress", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, refer_blind_progress));
2079         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "notify_early_inuse_ringing", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, notify_early_inuse_ringing));
2080         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "max_audio_streams", "1", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.max_audio_streams));
2081         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "max_video_streams", "1", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.max_video_streams));
2082         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "bundle", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.bundle));
2083         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "webrtc", "no", OPT_YESNO_T, 1, FLDSET(struct ast_sip_endpoint, media.webrtc));
2084         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "incoming_mwi_mailbox", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, incoming_mwi_mailbox));
2085
2086         if (ast_sip_initialize_sorcery_transport()) {
2087                 ast_log(LOG_ERROR, "Failed to register SIP transport support with sorcery\n");
2088                 ast_sorcery_unref(sip_sorcery);
2089                 sip_sorcery = NULL;
2090                 return -1;
2091         }
2092
2093         if (ast_sip_initialize_sorcery_location()) {
2094                 ast_log(LOG_ERROR, "Failed to register SIP location support with sorcery\n");
2095                 ast_sorcery_unref(sip_sorcery);
2096                 sip_sorcery = NULL;
2097                 return -1;
2098         }
2099
2100         if (ast_sip_initialize_sorcery_qualify()) {
2101                 ast_log(LOG_ERROR, "Failed to register SIP qualify support with sorcery\n");
2102                 ast_sorcery_unref(sip_sorcery);
2103                 sip_sorcery = NULL;
2104                 return -1;
2105         }
2106
2107         ast_sorcery_observer_add(sip_sorcery, "endpoint", &endpoint_observers);
2108         ast_sorcery_observer_add(sip_sorcery, "contact", &state_contact_observer);
2109         ast_sorcery_observer_add(sip_sorcery, CONTACT_STATUS, &state_contact_status_observer);
2110
2111         if (ast_sip_initialize_sorcery_domain_alias()) {
2112                 ast_log(LOG_ERROR, "Failed to register SIP domain aliases support with sorcery\n");
2113                 ast_sorcery_unref(sip_sorcery);
2114                 sip_sorcery = NULL;
2115                 return -1;
2116         }
2117
2118         if (ast_sip_initialize_sorcery_global()) {
2119                 ast_log(LOG_ERROR, "Failed to register SIP Global support\n");
2120                 ast_sorcery_unref(sip_sorcery);
2121                 sip_sorcery = NULL;
2122                 return -1;
2123         }
2124
2125         endpoint_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
2126         if (!endpoint_formatter) {
2127                 ast_log(LOG_ERROR, "Unable to allocate memory for endpoint_formatter\n");
2128                 ast_sorcery_unref(sip_sorcery);
2129                 sip_sorcery = NULL;
2130                 return -1;
2131         }
2132         endpoint_formatter->name = "endpoint";
2133         endpoint_formatter->print_header = cli_endpoint_print_header;
2134         endpoint_formatter->print_body = cli_endpoint_print_body;
2135         endpoint_formatter->get_container = cli_endpoint_get_container;
2136         endpoint_formatter->iterate = cli_endpoint_iterate;
2137         endpoint_formatter->retrieve_by_id = cli_endpoint_retrieve_by_id;
2138         endpoint_formatter->get_id = ast_sorcery_object_get_id;
2139
2140         ast_sip_register_cli_formatter(endpoint_formatter);
2141         ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
2142
2143         ast_sorcery_load(sip_sorcery);
2144
2145         load_all_endpoints();
2146
2147         ast_sip_location_prune_boot_contacts();
2148
2149         return 0;
2150 }
2151
2152 void ast_res_pjsip_destroy_configuration(void)
2153 {
2154         if (!sip_sorcery) {
2155                 return;
2156         }
2157
2158         ast_sorcery_observer_remove(sip_sorcery, CONTACT_STATUS, &state_contact_status_observer);
2159         ast_sorcery_observer_remove(sip_sorcery, "contact", &state_contact_observer);
2160         ast_sip_destroy_sorcery_global();
2161         ast_sip_destroy_sorcery_location();
2162         ast_sip_destroy_sorcery_auth();
2163         ast_sip_destroy_sorcery_transport();
2164         ast_sorcery_unref(sip_sorcery);
2165         sip_sorcery = NULL;
2166         ast_manager_unregister(AMI_SHOW_ENDPOINT);
2167         ast_manager_unregister(AMI_SHOW_ENDPOINTS);
2168         ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
2169         ast_sip_unregister_cli_formatter(endpoint_formatter);
2170         ast_sip_destroy_cli();
2171         ao2_cleanup(persistent_endpoints);
2172         persistent_endpoints = NULL;
2173 }
2174
2175 int ast_res_pjsip_reload_configuration(void)
2176 {
2177         if (sip_sorcery) {
2178                 ast_sorcery_reload(sip_sorcery);
2179         }
2180         return 0;
2181 }
2182
2183 static void subscription_configuration_destroy(struct ast_sip_endpoint_subscription_configuration *subscription)
2184 {
2185         ast_string_field_free_memory(&subscription->mwi);
2186         ast_free(subscription->mwi.voicemail_extension);
2187 }
2188
2189 static void info_configuration_destroy(struct ast_sip_endpoint_info_configuration *info)
2190 {
2191         ast_string_field_free_memory(&info->recording);
2192 }
2193
2194 static void media_configuration_destroy(struct ast_sip_endpoint_media_configuration *media)
2195 {
2196         ast_rtp_dtls_cfg_free(&media->rtp.dtls_cfg);
2197         ast_string_field_free_memory(&media->rtp);
2198         ast_string_field_free_memory(media);
2199 }
2200
2201 static void endpoint_destructor(void* obj)
2202 {
2203         struct ast_sip_endpoint *endpoint = obj;
2204
2205         ast_string_field_free_memory(endpoint);
2206
2207         ao2_cleanup(endpoint->media.codecs);
2208         ast_stream_topology_free(endpoint->media.topology);
2209         subscription_configuration_destroy(&endpoint->subscription);
2210         info_configuration_destroy(&endpoint->info);
2211         media_configuration_destroy(&endpoint->media);
2212         ast_sip_auth_vector_destroy(&endpoint->inbound_auths);
2213         ast_sip_auth_vector_destroy(&endpoint->outbound_auths);
2214         ast_party_id_free(&endpoint->id.self);
2215         endpoint->pickup.named_callgroups = ast_unref_namedgroups(endpoint->pickup.named_callgroups);
2216         endpoint->pickup.named_pickupgroups = ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
2217         ao2_cleanup(endpoint->persistent);
2218         ast_variables_destroy(endpoint->channel_vars);
2219         AST_VECTOR_FREE(&endpoint->ident_method_order);
2220         ast_free(endpoint->contact_user);
2221         ast_free_acl_list(endpoint->contact_acl);
2222         ast_free_acl_list(endpoint->acl);
2223 }
2224
2225 static int init_subscription_configuration(struct ast_sip_endpoint_subscription_configuration *subscription)
2226 {
2227         return ast_string_field_init(&subscription->mwi, 64);
2228 }
2229
2230 static int init_info_configuration(struct ast_sip_endpoint_info_configuration *info)
2231 {
2232         return ast_string_field_init(&info->recording, 32);
2233 }
2234
2235 static int init_media_configuration(struct ast_sip_endpoint_media_configuration *media)
2236 {
2237         return ast_string_field_init(media, 64) || ast_string_field_init(&media->rtp, 32);
2238 }
2239
2240 void *ast_sip_endpoint_alloc(const char *name)
2241 {
2242         struct ast_sip_endpoint *endpoint = ast_sorcery_generic_alloc(sizeof(*endpoint), endpoint_destructor);
2243         if (!endpoint) {
2244                 return NULL;
2245         }
2246         if (ast_string_field_init(endpoint, 64)) {
2247                 ao2_cleanup(endpoint);
2248                 return NULL;
2249         }
2250
2251         ast_string_field_init_extended(endpoint, incoming_mwi_mailbox);
2252
2253         if (!(endpoint->media.codecs = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2254                 ao2_cleanup(endpoint);
2255                 return NULL;
2256         }
2257         if (init_subscription_configuration(&endpoint->subscription)) {
2258                 ao2_cleanup(endpoint);
2259                 return NULL;
2260         }
2261         if (init_info_configuration(&endpoint->info)) {
2262                 ao2_cleanup(endpoint);
2263                 return NULL;
2264         }
2265         if (init_media_configuration(&endpoint->media)) {
2266                 ao2_cleanup(endpoint);
2267                 return NULL;
2268         }
2269         ast_party_id_init(&endpoint->id.self);
2270
2271         if (AST_VECTOR_INIT(&endpoint->ident_method_order, 1)) {
2272                 return NULL;
2273         }
2274
2275         return endpoint;
2276 }
2277
2278 struct ao2_container *ast_sip_get_endpoints(void)
2279 {
2280         struct ao2_container *endpoints;
2281
2282         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
2283
2284         return endpoints;
2285 }
2286
2287 struct ast_sip_endpoint *ast_sip_default_outbound_endpoint(void)
2288 {
2289         RAII_VAR(char *, name, ast_sip_global_default_outbound_endpoint(), ast_free);
2290         return ast_strlen_zero(name) ? NULL : ast_sorcery_retrieve_by_id(
2291                 sip_sorcery, "endpoint", name);
2292 }
2293
2294 int ast_sip_retrieve_auths(const struct ast_sip_auth_vector *auths, struct ast_sip_auth **out)
2295 {
2296         int i;
2297
2298         for (i = 0; i < AST_VECTOR_SIZE(auths); ++i) {
2299                 /* Using AST_VECTOR_GET is safe since the vector is immutable */
2300                 const char *name = AST_VECTOR_GET(auths, i);
2301                 out[i] = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), SIP_SORCERY_AUTH_TYPE, name);
2302                 if (!out[i]) {
2303                         ast_log(LOG_NOTICE, "Couldn't find auth '%s'. Cannot authenticate\n", name);
2304                         return -1;
2305                 }
2306         }
2307
2308         return 0;
2309 }
2310
2311 void ast_sip_cleanup_auths(struct ast_sip_auth *auths[], size_t num_auths)
2312 {
2313         int i;
2314         for (i = 0; i < num_auths; ++i) {
2315                 ao2_cleanup(auths[i]);
2316         }
2317 }
2318
2319 struct ast_sorcery *ast_sip_get_sorcery(void)
2320 {
2321         return sip_sorcery;
2322 }