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