alembic/res_pjsip: Add "webrtc" configuration option
[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 {
588                         ast_log(LOG_ERROR, "Unrecognized identification method %s specified for endpoint %s\n",
589                                         val, ast_sorcery_object_get_id(endpoint));
590                         AST_VECTOR_RESET(&endpoint->ident_method_order, AST_VECTOR_ELEM_CLEANUP_NOOP);
591                         endpoint->ident_method = 0;
592                         return -1;
593                 }
594                 if (endpoint->ident_method & method) {
595                         /* We are already indentifying by this method.  No need to do it again. */
596                         continue;
597                 }
598
599                 endpoint->ident_method |= method;
600                 AST_VECTOR_APPEND(&endpoint->ident_method_order, method);
601         }
602
603         return 0;
604 }
605
606 static int ident_to_str(const void *obj, const intptr_t *args, char **buf)
607 {
608         const struct ast_sip_endpoint *endpoint = obj;
609         int methods;
610         char *method;
611         int i;
612         int j = 0;
613
614         methods = AST_VECTOR_SIZE(&endpoint->ident_method_order);
615         if (!methods) {
616                 return 0;
617         }
618
619         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
620                 return -1;
621         }
622
623         for (i = 0; i < methods; i++) {
624                 switch (AST_VECTOR_GET(&endpoint->ident_method_order, i)) {
625                 case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME :
626                         method = "username";
627                         break;
628                 case AST_SIP_ENDPOINT_IDENTIFY_BY_AUTH_USERNAME :
629                         method = "auth_username";
630                         break;
631                 default:
632                         continue;
633                 }
634                 j = sprintf(*buf + j, "%s%s", method, i < methods - 1 ? "," : "");
635         }
636
637         return 0;
638 }
639
640 static int redirect_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
641 {
642         struct ast_sip_endpoint *endpoint = obj;
643
644         if (!strcasecmp(var->value, "user")) {
645                 endpoint->redirect_method = AST_SIP_REDIRECT_USER;
646         } else if (!strcasecmp(var->value, "uri_core")) {
647                 endpoint->redirect_method = AST_SIP_REDIRECT_URI_CORE;
648         } else if (!strcasecmp(var->value, "uri_pjsip")) {
649                 endpoint->redirect_method = AST_SIP_REDIRECT_URI_PJSIP;
650         } else {
651                 ast_log(LOG_ERROR, "Unrecognized redirect method %s specified for endpoint %s\n",
652                         var->value, ast_sorcery_object_get_id(endpoint));
653                 return -1;
654         }
655
656         return 0;
657 }
658
659 static int direct_media_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
660 {
661         struct ast_sip_endpoint *endpoint = obj;
662
663         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
664                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
665         } else if (!strcasecmp(var->value, "update")) {
666                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
667         } else {
668                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
669                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
670                 return -1;
671         }
672         return 0;
673 }
674
675 static const char *id_configuration_refresh_methods[] = {
676         [AST_SIP_SESSION_REFRESH_METHOD_INVITE] = "invite",
677         [AST_SIP_SESSION_REFRESH_METHOD_UPDATE] = "update"
678 };
679
680 static int direct_media_method_to_str(const void *obj, const intptr_t *args, char **buf)
681 {
682         const struct ast_sip_endpoint *endpoint = obj;
683         if (ARRAY_IN_BOUNDS(endpoint->id.refresh_method, id_configuration_refresh_methods)) {
684                 *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
685         }
686         return 0;
687 }
688
689 static int connected_line_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
690 {
691         struct ast_sip_endpoint *endpoint = obj;
692
693         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
694                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
695         } else if (!strcasecmp(var->value, "update")) {
696                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
697         } else {
698                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
699                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
700                 return -1;
701         }
702         return 0;
703 }
704
705 static int connected_line_method_to_str(const void *obj, const intptr_t *args, char **buf)
706 {
707         const struct ast_sip_endpoint *endpoint = obj;
708         *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
709         return 0;
710 }
711
712 static int direct_media_glare_mitigation_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
713 {
714         struct ast_sip_endpoint *endpoint = obj;
715
716         if (!strcasecmp(var->value, "none")) {
717                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE;
718         } else if (!strcasecmp(var->value, "outgoing")) {
719                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING;
720         } else if (!strcasecmp(var->value, "incoming")) {
721                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING;
722         } else {
723                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
724                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
725                 return -1;
726         }
727
728         return 0;
729 }
730
731 static const char *direct_media_glare_mitigation_map[] = {
732         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE] = "none",
733         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING] = "outgoing",
734         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING] = "incoming"
735 };
736
737 static int direct_media_glare_mitigation_to_str(const void *obj, const intptr_t *args, char **buf)
738 {
739         const struct ast_sip_endpoint *endpoint = obj;
740         if (ARRAY_IN_BOUNDS(endpoint->media.direct_media.glare_mitigation, direct_media_glare_mitigation_map)) {
741                 *buf = ast_strdup(direct_media_glare_mitigation_map[endpoint->media.direct_media.glare_mitigation]);
742         }
743
744         return 0;
745 }
746
747 static int caller_id_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
748 {
749         struct ast_sip_endpoint *endpoint = obj;
750         char cid_name[80] = { '\0' };
751         char cid_num[80] = { '\0' };
752
753         ast_callerid_split(var->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
754         if (!ast_strlen_zero(cid_name)) {
755                 endpoint->id.self.name.str = ast_strdup(cid_name);
756                 if (!endpoint->id.self.name.str) {
757                         return -1;
758                 }
759                 endpoint->id.self.name.valid = 1;
760         }
761         if (!ast_strlen_zero(cid_num)) {
762                 endpoint->id.self.number.str = ast_strdup(cid_num);
763                 if (!endpoint->id.self.number.str) {
764                         return -1;
765                 }
766                 endpoint->id.self.number.valid = 1;
767         }
768         return 0;
769 }
770
771 static int caller_id_to_str(const void *obj, const intptr_t *args, char **buf)
772 {
773         const struct ast_sip_endpoint *endpoint = obj;
774         const char *name = S_COR(endpoint->id.self.name.valid,
775                                  endpoint->id.self.name.str, NULL);
776         const char *number = S_COR(endpoint->id.self.number.valid,
777                                    endpoint->id.self.number.str, NULL);
778
779         /* make sure size is at least 10 - that should cover the "<unknown>"
780            case as well as any additional formatting characters added in
781            the name and/or number case. */
782         int size = 10;
783         size += name ? strlen(name) : 0;
784         size += number ? strlen(number) : 0;
785
786         if (!(*buf = ast_calloc(size + 1, sizeof(char)))) {
787                 return -1;
788         }
789
790         ast_callerid_merge(*buf, size + 1, name, number, NULL);
791         return 0;
792 }
793
794 static int caller_id_privacy_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
795 {
796         struct ast_sip_endpoint *endpoint = obj;
797         int callingpres = ast_parse_caller_presentation(var->value);
798         if (callingpres == -1 && sscanf(var->value, "%d", &callingpres) != 1) {
799                 return -1;
800         }
801         endpoint->id.self.number.presentation = callingpres;
802         endpoint->id.self.name.presentation = callingpres;
803         return 0;
804 }
805
806 static int caller_id_privacy_to_str(const void *obj, const intptr_t *args, char **buf)
807 {
808         const struct ast_sip_endpoint *endpoint = obj;
809         const char *presentation = ast_named_caller_presentation(
810                 endpoint->id.self.name.presentation);
811
812         *buf = ast_strdup(presentation);
813         return 0;
814 }
815
816 static int caller_id_tag_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
817 {
818         struct ast_sip_endpoint *endpoint = obj;
819         endpoint->id.self.tag = ast_strdup(var->value);
820         return endpoint->id.self.tag ? 0 : -1;
821 }
822
823 static int caller_id_tag_to_str(const void *obj, const intptr_t *args, char **buf)
824 {
825         const struct ast_sip_endpoint *endpoint = obj;
826         *buf = ast_strdup(endpoint->id.self.tag);
827         return 0;
828 }
829
830 static int media_encryption_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
831 {
832         struct ast_sip_endpoint *endpoint = obj;
833
834         if (!strcasecmp("no", var->value)) {
835                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
836         } else if (!strcasecmp("sdes", var->value)) {
837                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_SDES;
838         } else if (!strcasecmp("dtls", var->value)) {
839                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_DTLS;
840                 return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, "dtlsenable", "yes");
841         } else {
842                 return -1;
843         }
844
845         return 0;
846 }
847
848 static const char *media_encryption_map[] = {
849         [AST_SIP_MEDIA_TRANSPORT_INVALID] = "invalid",
850         [AST_SIP_MEDIA_ENCRYPT_NONE] = "no",
851         [AST_SIP_MEDIA_ENCRYPT_SDES] = "sdes",
852         [AST_SIP_MEDIA_ENCRYPT_DTLS] = "dtls",
853 };
854
855 static int media_encryption_to_str(const void *obj, const intptr_t *args, char **buf)
856 {
857         const struct ast_sip_endpoint *endpoint = obj;
858         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.encryption, media_encryption_map)) {
859                 *buf = ast_strdup(media_encryption_map[
860                                           endpoint->media.rtp.encryption]);
861         }
862         return 0;
863 }
864
865 static int group_handler(const struct aco_option *opt,
866                          struct ast_variable *var, void *obj)
867 {
868         struct ast_sip_endpoint *endpoint = obj;
869
870         if (!strncmp(var->name, "call_group", 10)) {
871                 endpoint->pickup.callgroup = ast_get_group(var->value);
872         } else if (!strncmp(var->name, "pickup_group", 12)) {
873                 endpoint->pickup.pickupgroup = ast_get_group(var->value);
874         } else {
875                 return -1;
876         }
877
878         return 0;
879 }
880
881 static int callgroup_to_str(const void *obj, const intptr_t *args, char **buf)
882 {
883         const struct ast_sip_endpoint *endpoint = obj;
884
885         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
886                 return -1;
887         }
888
889         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.callgroup);
890         return 0;
891 }
892
893 static int pickupgroup_to_str(const void *obj, const intptr_t *args, char **buf)
894 {
895         const struct ast_sip_endpoint *endpoint = obj;
896
897         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
898                 return -1;
899         }
900
901         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.pickupgroup);
902         return 0;
903 }
904
905 static int named_groups_handler(const struct aco_option *opt,
906                                 struct ast_variable *var, void *obj)
907 {
908         struct ast_sip_endpoint *endpoint = obj;
909
910         if (!strncmp(var->name, "named_call_group", 16)) {
911                 if (ast_strlen_zero(var->value)) {
912                         endpoint->pickup.named_callgroups =
913                                 ast_unref_namedgroups(endpoint->pickup.named_callgroups);
914                 } else if (!(endpoint->pickup.named_callgroups =
915                       ast_get_namedgroups(var->value))) {
916                         return -1;
917                 }
918         } else if (!strncmp(var->name, "named_pickup_group", 18)) {
919                 if (ast_strlen_zero(var->value)) {
920                         endpoint->pickup.named_pickupgroups =
921                                 ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
922                 } else if (!(endpoint->pickup.named_pickupgroups =
923                       ast_get_namedgroups(var->value))) {
924                         return -1;
925                 }
926         } else {
927                 return -1;
928         }
929
930         return 0;
931 }
932
933 static int named_callgroups_to_str(const void *obj, const intptr_t *args, char **buf)
934 {
935         const struct ast_sip_endpoint *endpoint = obj;
936         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
937
938         ast_print_namedgroups(&str, endpoint->pickup.named_callgroups);
939         *buf = ast_strdup(ast_str_buffer(str));
940         return 0;
941 }
942
943 static int named_pickupgroups_to_str(const void *obj, const intptr_t *args, char **buf)
944 {
945         const struct ast_sip_endpoint *endpoint = obj;
946         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
947
948         ast_print_namedgroups(&str, endpoint->pickup.named_pickupgroups);
949         *buf = ast_strdup(ast_str_buffer(str));
950         return 0;
951 }
952
953 static int dtls_handler(const struct aco_option *opt,
954                          struct ast_variable *var, void *obj)
955 {
956         struct ast_sip_endpoint *endpoint = obj;
957         char *name = ast_strdupa(var->name);
958         char *front = NULL;
959         char *back = NULL;
960         char *buf = name;
961
962         /* strip out underscores in the name */
963         front = strtok_r(buf, "_", &back);
964         while (front) {
965                 int size = strlen(front);
966                 ast_copy_string(buf, front, size + 1);
967                 buf += size;
968                 front = strtok_r(NULL, "_", &back);
969         }
970
971         return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, name, var->value);
972 }
973
974 static int dtlsverify_to_str(const void *obj, const intptr_t *args, char **buf)
975 {
976         const struct ast_sip_endpoint *endpoint = obj;
977         *buf = ast_strdup(AST_YESNO(endpoint->media.rtp.dtls_cfg.verify));
978         return 0;
979 }
980
981 static int dtlsrekey_to_str(const void *obj, const intptr_t *args, char **buf)
982 {
983         const struct ast_sip_endpoint *endpoint = obj;
984
985         return ast_asprintf(
986                 buf, "%u", endpoint->media.rtp.dtls_cfg.rekey) >=0 ? 0 : -1;
987 }
988
989 static int dtlscertfile_to_str(const void *obj, const intptr_t *args, char **buf)
990 {
991         const struct ast_sip_endpoint *endpoint = obj;
992         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.certfile);
993         return 0;
994 }
995
996 static int dtlsprivatekey_to_str(const void *obj, const intptr_t *args, char **buf)
997 {
998         const struct ast_sip_endpoint *endpoint = obj;
999         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.pvtfile);
1000         return 0;
1001 }
1002
1003 static int dtlscipher_to_str(const void *obj, const intptr_t *args, char **buf)
1004 {
1005         const struct ast_sip_endpoint *endpoint = obj;
1006         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cipher);
1007         return 0;
1008 }
1009
1010 static int dtlscafile_to_str(const void *obj, const intptr_t *args, char **buf)
1011 {
1012         const struct ast_sip_endpoint *endpoint = obj;
1013         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cafile);
1014         return 0;
1015 }
1016
1017 static int dtlscapath_to_str(const void *obj, const intptr_t *args, char **buf)
1018 {
1019         const struct ast_sip_endpoint *endpoint = obj;
1020         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.capath);
1021         return 0;
1022 }
1023
1024 static const char *ast_rtp_dtls_setup_map[] = {
1025         [AST_RTP_DTLS_SETUP_ACTIVE] = "active",
1026         [AST_RTP_DTLS_SETUP_PASSIVE] = "passive",
1027         [AST_RTP_DTLS_SETUP_ACTPASS] = "actpass",
1028         [AST_RTP_DTLS_SETUP_HOLDCONN] = "holdconn",
1029 };
1030
1031 static int dtlssetup_to_str(const void *obj, const intptr_t *args, char **buf)
1032 {
1033         const struct ast_sip_endpoint *endpoint = obj;
1034         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.default_setup, ast_rtp_dtls_setup_map)) {
1035                 *buf = ast_strdup(ast_rtp_dtls_setup_map[endpoint->media.rtp.dtls_cfg.default_setup]);
1036         }
1037         return 0;
1038 }
1039
1040 static const char *ast_rtp_dtls_fingerprint_map[] = {
1041         [AST_RTP_DTLS_HASH_SHA256] = "SHA-256",
1042         [AST_RTP_DTLS_HASH_SHA1] = "SHA-1",
1043 };
1044
1045 static int dtlsfingerprint_to_str(const void *obj, const intptr_t *args, char **buf)
1046 {
1047         const struct ast_sip_endpoint *endpoint = obj;
1048         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.hash, ast_rtp_dtls_fingerprint_map)) {
1049                 *buf = ast_strdup(ast_rtp_dtls_fingerprint_map[endpoint->media.rtp.dtls_cfg.hash]);
1050         }
1051         return 0;
1052 }
1053
1054 static int t38udptl_ec_handler(const struct aco_option *opt,
1055         struct ast_variable *var, void *obj)
1056 {
1057         struct ast_sip_endpoint *endpoint = obj;
1058
1059         if (!strcmp(var->value, "none")) {
1060                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_NONE;
1061         } else if (!strcmp(var->value, "fec")) {
1062                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_FEC;
1063         } else if (!strcmp(var->value, "redundancy")) {
1064                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_REDUNDANCY;
1065         } else {
1066                 return -1;
1067         }
1068
1069         return 0;
1070 }
1071
1072 static const char *ast_t38_ec_modes_map[] = {
1073         [UDPTL_ERROR_CORRECTION_NONE] = "none",
1074         [UDPTL_ERROR_CORRECTION_FEC] = "fec",
1075         [UDPTL_ERROR_CORRECTION_REDUNDANCY] = "redundancy"
1076 };
1077
1078 static int t38udptl_ec_to_str(const void *obj, const intptr_t *args, char **buf)
1079 {
1080         const struct ast_sip_endpoint *endpoint = obj;
1081         if (ARRAY_IN_BOUNDS(endpoint->media.t38.error_correction, ast_t38_ec_modes_map)) {
1082                 *buf = ast_strdup(ast_t38_ec_modes_map[
1083                                           endpoint->media.t38.error_correction]);
1084         }
1085         return 0;
1086 }
1087
1088 static int tos_handler(const struct aco_option *opt,
1089         struct ast_variable *var, void *obj)
1090 {
1091         struct ast_sip_endpoint *endpoint = obj;
1092         unsigned int value;
1093
1094         if (ast_str2tos(var->value, &value)) {
1095                 ast_log(LOG_ERROR, "Error configuring endpoint '%s' - Could not "
1096                         "interpret '%s' value '%s'\n",
1097                         ast_sorcery_object_get_id(endpoint), var->name, var->value);
1098                 return -1;
1099         }
1100
1101         if (!strcmp(var->name, "tos_audio")) {
1102                 endpoint->media.tos_audio = value;
1103         } else if (!strcmp(var->name, "tos_video")) {
1104                 endpoint->media.tos_video = value;
1105         } else {
1106                 /* If we reach this point, someone called the tos_handler when they shouldn't have. */
1107                 ast_assert(0);
1108                 return -1;
1109         }
1110         return 0;
1111 }
1112
1113 static int tos_audio_to_str(const void *obj, const intptr_t *args, char **buf)
1114 {
1115         const struct ast_sip_endpoint *endpoint = obj;
1116
1117         if (ast_asprintf(buf, "%u", endpoint->media.tos_audio) == -1) {
1118                 return -1;
1119         }
1120         return 0;
1121 }
1122
1123 static int tos_video_to_str(const void *obj, const intptr_t *args, char **buf)
1124 {
1125         const struct ast_sip_endpoint *endpoint = obj;
1126
1127         if (ast_asprintf(buf, "%u", endpoint->media.tos_video) == -1) {
1128                 return -1;
1129         }
1130         return 0;
1131 }
1132
1133 static int from_user_handler(const struct aco_option *opt,
1134         struct ast_variable *var, void *obj)
1135 {
1136         struct ast_sip_endpoint *endpoint = obj;
1137         /* Valid non-alphanumeric characters for URI */
1138         char *valid_uri_marks = "-_.!~*`()";
1139         const char *val;
1140
1141         for (val = var->value; *val; val++) {
1142                 if (!strchr(valid_uri_marks, *val) && !isdigit(*val) && !isalpha(*val)) {
1143                         ast_log(LOG_ERROR, "Error configuring endpoint '%s' - '%s' field "
1144                         "contains invalid character '%c'\n",
1145                         ast_sorcery_object_get_id(endpoint), var->name, *val);
1146                         return -1;
1147                 }
1148         }
1149
1150         ast_string_field_set(endpoint, fromuser, var->value);
1151
1152         return 0;
1153 }
1154
1155 static int from_user_to_str(const void *obj, const intptr_t *args, char **buf)
1156 {
1157         const struct ast_sip_endpoint *endpoint = obj;
1158
1159         *buf = ast_strdup(endpoint->fromuser);
1160
1161         return 0;
1162 }
1163
1164 static int set_var_handler(const struct aco_option *opt,
1165         struct ast_variable *var, void *obj)
1166 {
1167         struct ast_sip_endpoint *endpoint = obj;
1168         struct ast_variable *new_var;
1169         char *name;
1170         char *val;
1171
1172         if (ast_strlen_zero(var->value)) {
1173                 return 0;
1174         }
1175
1176         name = ast_strdupa(var->value);
1177         val = strchr(name, '=');
1178
1179         if (!val) {
1180                 return -1;
1181         }
1182
1183         *val++ = '\0';
1184
1185         if (!(new_var = ast_variable_new(name, val, ""))) {
1186                 return -1;
1187         }
1188
1189         ast_variable_list_append(&endpoint->channel_vars, new_var);
1190
1191         return 0;
1192 }
1193
1194 static int set_var_to_str(const void *obj, const intptr_t *args, char **buf)
1195 {
1196         struct ast_str *str = ast_str_create(MAX_OBJECT_FIELD);
1197         const struct ast_sip_endpoint *endpoint = obj;
1198         struct ast_variable *var;
1199
1200         for (var = endpoint->channel_vars; var; var = var->next) {
1201                 ast_str_append(&str, 0, "%s=%s,", var->name, var->value);
1202         }
1203
1204         *buf = ast_strdup(ast_str_truncate(str, -1));
1205         ast_free(str);
1206         return 0;
1207 }
1208
1209 static int set_var_to_vl(const void *obj, struct ast_variable **fields)
1210 {
1211         const struct ast_sip_endpoint *endpoint = obj;
1212         if (endpoint->channel_vars) {
1213                 *fields = ast_variables_dup(endpoint->channel_vars);
1214         }
1215         return 0;
1216 }
1217
1218 static int voicemail_extension_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1219 {
1220         struct ast_sip_endpoint *endpoint = obj;
1221
1222         endpoint->subscription.mwi.voicemail_extension = ast_strdup(var->value);
1223
1224         return endpoint->subscription.mwi.voicemail_extension ? 0 : -1;
1225 }
1226
1227 static int voicemail_extension_to_str(const void *obj, const intptr_t *args, char **buf)
1228 {
1229         const struct ast_sip_endpoint *endpoint = obj;
1230
1231         *buf = ast_strdup(endpoint->subscription.mwi.voicemail_extension);
1232
1233         return 0;
1234 }
1235
1236 static int contact_user_handler(const struct aco_option *opt,
1237         struct ast_variable *var, void *obj)
1238 {
1239         struct ast_sip_endpoint *endpoint = obj;
1240
1241         endpoint->contact_user = ast_strdup(var->value);
1242         if (!endpoint->contact_user) {
1243                 return -1;
1244         }
1245
1246         return 0;
1247 }
1248
1249 static int contact_user_to_str(const void *obj, const intptr_t *args, char **buf)
1250 {
1251         const struct ast_sip_endpoint *endpoint = obj;
1252
1253         *buf = ast_strdup(endpoint->contact_user);
1254         if (!(*buf)) {
1255                 return -1;
1256         }
1257
1258         return 0;
1259 }
1260
1261 static void *sip_nat_hook_alloc(const char *name)
1262 {
1263         return ast_sorcery_generic_alloc(sizeof(struct ast_sip_nat_hook), NULL);
1264 }
1265
1266 /*! \brief Destructor function for persistent endpoint information */
1267 static void persistent_endpoint_destroy(void *obj)
1268 {
1269         struct sip_persistent_endpoint *persistent = obj;
1270
1271         ast_endpoint_shutdown(persistent->endpoint);
1272         ast_free(persistent->aors);
1273 }
1274
1275 int ast_sip_persistent_endpoint_update_state(const char *endpoint_name, enum ast_endpoint_state state)
1276 {
1277         struct sip_persistent_endpoint *persistent;
1278
1279         ao2_lock(persistent_endpoints);
1280         persistent = ao2_find(persistent_endpoints, endpoint_name, OBJ_SEARCH_KEY | OBJ_NOLOCK);
1281         if (persistent) {
1282                 endpoint_update_state(persistent->endpoint, state);
1283                 ao2_ref(persistent, -1);
1284         }
1285         ao2_unlock(persistent_endpoints);
1286         return persistent ? 0 : -1;
1287 }
1288
1289 /*! \brief Internal function which finds (or creates) persistent endpoint information */
1290 static struct ast_endpoint *persistent_endpoint_find_or_create(const struct ast_sip_endpoint *endpoint)
1291 {
1292         RAII_VAR(struct sip_persistent_endpoint *, persistent, NULL, ao2_cleanup);
1293         SCOPED_AO2LOCK(lock, persistent_endpoints);
1294
1295         persistent = ao2_find(persistent_endpoints, ast_sorcery_object_get_id(endpoint),
1296                 OBJ_SEARCH_KEY | OBJ_NOLOCK);
1297         if (!persistent) {
1298                 persistent = ao2_alloc_options(sizeof(*persistent), persistent_endpoint_destroy,
1299                         AO2_ALLOC_OPT_LOCK_NOLOCK);
1300                 if (!persistent) {
1301                         return NULL;
1302                 }
1303
1304                 persistent->endpoint = ast_endpoint_create("PJSIP",
1305                         ast_sorcery_object_get_id(endpoint));
1306                 if (!persistent->endpoint) {
1307                         return NULL;
1308                 }
1309
1310                 persistent->aors = ast_strdup(endpoint->aors);
1311                 if (!persistent->aors) {
1312                         return NULL;
1313                 }
1314
1315                 ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_OFFLINE);
1316
1317                 ao2_link_flags(persistent_endpoints, persistent, OBJ_NOLOCK);
1318         }
1319
1320         ao2_ref(persistent->endpoint, +1);
1321         return persistent->endpoint;
1322 }
1323
1324 /*! \brief Callback function for when an object is finalized */
1325 static int sip_endpoint_apply_handler(const struct ast_sorcery *sorcery, void *obj)
1326 {
1327         struct ast_sip_endpoint *endpoint = obj;
1328
1329         if (!(endpoint->persistent = persistent_endpoint_find_or_create(endpoint))) {
1330                 return -1;
1331         }
1332
1333         if (endpoint->extensions.timer.min_se < 90) {
1334                 ast_log(LOG_ERROR, "Session timer minimum expires time must be 90 or greater on endpoint '%s'\n",
1335                         ast_sorcery_object_get_id(endpoint));
1336                 return -1;
1337         } else if (endpoint->extensions.timer.sess_expires < endpoint->extensions.timer.min_se) {
1338                 ast_log(LOG_ERROR, "Session timer expires must be greater than minimum session expires time on endpoint '%s'\n",
1339                         ast_sorcery_object_get_id(endpoint));
1340                 return -1;
1341         }
1342
1343         endpoint->media.topology = ast_stream_topology_create_from_format_cap(endpoint->media.codecs);
1344         if (!endpoint->media.topology) {
1345                 return -1;
1346         }
1347
1348         endpoint->media.rtcp_mux |= endpoint->media.bundle;
1349
1350         /*
1351          * If webrtc has been enabled then enable those attributes, and default
1352          * some, that are needed in order for webrtc to work.
1353          */
1354         endpoint->media.bundle |= endpoint->media.webrtc;
1355         endpoint->media.rtcp_mux |= endpoint->media.webrtc;
1356         endpoint->media.rtp.use_avpf |= endpoint->media.webrtc;
1357         endpoint->media.rtp.ice_support |= endpoint->media.webrtc;
1358         endpoint->media.rtp.use_received_transport |= endpoint->media.webrtc;
1359
1360         if (endpoint->media.webrtc) {
1361                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_DTLS;
1362                 endpoint->media.rtp.dtls_cfg.enabled = 1;
1363                 endpoint->media.rtp.dtls_cfg.default_setup = AST_RTP_DTLS_SETUP_ACTPASS;
1364                 endpoint->media.rtp.dtls_cfg.verify = AST_RTP_DTLS_VERIFY_FINGERPRINT;
1365
1366                 if (ast_strlen_zero(endpoint->media.rtp.dtls_cfg.certfile) ||
1367                         (ast_strlen_zero(endpoint->media.rtp.dtls_cfg.cafile))) {
1368                         ast_log(LOG_ERROR, "WebRTC can't be enabled on endpoint '%s' - a DTLS cert "
1369                                 "or ca file has not been specified", ast_sorcery_object_get_id(endpoint));
1370                         return -1;
1371                 }
1372         }
1373
1374         return 0;
1375 }
1376
1377 const char *ast_sip_get_device_state(const struct ast_sip_endpoint *endpoint)
1378 {
1379         char device[MAX_OBJECT_FIELD];
1380
1381         snprintf(device, MAX_OBJECT_FIELD, "PJSIP/%s", ast_sorcery_object_get_id(endpoint));
1382         return ast_devstate2str(ast_device_state(device));
1383 }
1384
1385 struct ast_endpoint_snapshot *ast_sip_get_endpoint_snapshot(
1386         const struct ast_sip_endpoint *endpoint)
1387 {
1388         return ast_endpoint_latest_snapshot(
1389                 ast_endpoint_get_tech(endpoint->persistent),
1390                 ast_endpoint_get_resource(endpoint->persistent));
1391 }
1392
1393 int ast_sip_for_each_channel_snapshot(
1394         const struct ast_endpoint_snapshot *endpoint_snapshot,
1395         ao2_callback_fn on_channel_snapshot, void *arg)
1396 {
1397         int num, num_channels = endpoint_snapshot->num_channels;
1398
1399         if (!on_channel_snapshot || !num_channels) {
1400                 return 0;
1401         }
1402
1403         for (num = 0; num < num_channels; ++num) {
1404                 RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1405                 int res;
1406
1407                 snapshot = ast_channel_snapshot_get_latest(endpoint_snapshot->channel_ids[num]);
1408                 if (!snapshot) {
1409                         continue;
1410                 }
1411
1412                 res = on_channel_snapshot(snapshot, arg, 0);
1413                 if (res) {
1414                         return -1;
1415                 }
1416         }
1417         return 0;
1418 }
1419
1420 int ast_sip_for_each_channel(
1421         const struct ast_sip_endpoint *endpoint,
1422         ao2_callback_fn on_channel_snapshot, void *arg)
1423 {
1424         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1425         return ast_sip_for_each_channel_snapshot(endpoint_snapshot, on_channel_snapshot, arg);
1426 }
1427
1428 static int active_channels_to_str_cb(void *object, void *arg, int flags)
1429 {
1430         const struct ast_channel_snapshot *snapshot = object;
1431         struct ast_str **buf = arg;
1432         ast_str_append(buf, 0, "%s,", snapshot->name);
1433         return 0;
1434 }
1435
1436 static void active_channels_to_str(const struct ast_sip_endpoint *endpoint,
1437                                    struct ast_str **str)
1438 {
1439
1440         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot,
1441                  ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1442
1443         if (endpoint_snapshot) {
1444                 return;
1445         }
1446
1447         ast_sip_for_each_channel_snapshot(endpoint_snapshot,
1448                                           active_channels_to_str_cb, str);
1449         ast_str_truncate(*str, -1);
1450 }
1451
1452 #define AMI_DEFAULT_STR_SIZE 512
1453
1454 struct ast_str *ast_sip_create_ami_event(const char *event, struct ast_sip_ami *ami)
1455 {
1456         struct ast_str *buf = ast_str_create(AMI_DEFAULT_STR_SIZE);
1457
1458         if (!(buf)) {
1459                 astman_send_error_va(ami->s, ami->m, "Unable create event "
1460                                      "for %s\n", event);
1461                 return NULL;
1462         }
1463
1464         ast_str_set(&buf, 0, "Event: %s\r\n", event);
1465         if (!ast_strlen_zero(ami->action_id)) {
1466                 ast_str_append(&buf, 0, "ActionID: %s\r\n", ami->action_id);
1467         }
1468         return buf;
1469 }
1470
1471 static void sip_sorcery_object_ami_set_type_name(const void *obj, struct ast_str **buf)
1472 {
1473         ast_str_append(buf, 0, "ObjectType: %s\r\n",
1474                        ast_sorcery_object_get_type(obj));
1475         ast_str_append(buf, 0, "ObjectName: %s\r\n",
1476                        ast_sorcery_object_get_id(obj));
1477 }
1478
1479 int ast_sip_sorcery_object_to_ami(const void *obj, struct ast_str **buf)
1480 {
1481         RAII_VAR(struct ast_variable *, objset, ast_sorcery_objectset_create2(
1482                          ast_sip_get_sorcery(), obj, AST_HANDLER_ONLY_STRING), ast_variables_destroy);
1483         struct ast_variable *i;
1484
1485         if (!objset) {
1486                 return -1;
1487         }
1488
1489         sip_sorcery_object_ami_set_type_name(obj, buf);
1490
1491         for (i = objset; i; i = i->next) {
1492                 RAII_VAR(char *, camel, ast_to_camel_case(i->name), ast_free);
1493                 ast_str_append(buf, 0, "%s: %s\r\n", camel, i->value);
1494         }
1495
1496         return 0;
1497 }
1498
1499 static int sip_endpoints_aors_ami(void *obj, void *arg, int flags)
1500 {
1501         struct ast_sip_aor *aor = obj;
1502         struct ast_str **buf = arg;
1503
1504         ast_str_append(buf, 0, "Contacts: ");
1505         ast_sip_for_each_contact(aor, ast_sip_contact_to_str, arg);
1506         ast_str_append(buf, 0, "\r\n");
1507
1508         return 0;
1509 }
1510
1511 static int sip_endpoint_to_ami(const struct ast_sip_endpoint *endpoint,
1512                                struct ast_str **buf)
1513 {
1514         if (ast_sip_sorcery_object_to_ami(endpoint, buf)) {
1515                 return -1;
1516         }
1517
1518         ast_str_append(buf, 0, "DeviceState: %s\r\n",
1519                        ast_sip_get_device_state(endpoint));
1520
1521         ast_str_append(buf, 0, "ActiveChannels: ");
1522         active_channels_to_str(endpoint, buf);
1523         ast_str_append(buf, 0, "\r\n");
1524
1525         return 0;
1526 }
1527
1528 static int format_ami_endpoint(const struct ast_sip_endpoint *endpoint,
1529                                struct ast_sip_ami *ami)
1530 {
1531         RAII_VAR(struct ast_str *, buf,
1532                  ast_sip_create_ami_event("EndpointDetail", ami), ast_free);
1533
1534         if (!buf) {
1535                 return -1;
1536         }
1537
1538         sip_endpoint_to_ami(endpoint, &buf);
1539         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1540         return 0;
1541 }
1542
1543 #define AMI_SHOW_ENDPOINTS "PJSIPShowEndpoints"
1544 #define AMI_SHOW_ENDPOINT "PJSIPShowEndpoint"
1545
1546 static int ami_show_endpoint(struct mansession *s, const struct message *m)
1547 {
1548         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"),
1549                 .count = 0, };
1550         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1551         const char *endpoint_name = astman_get_header(m, "Endpoint");
1552         int count = 0;
1553
1554         if (ast_strlen_zero(endpoint_name)) {
1555                 astman_send_error_va(s, m, "%s requires an endpoint name\n",
1556                         AMI_SHOW_ENDPOINT);
1557                 return 0;
1558         }
1559
1560         if (!strncasecmp(endpoint_name, "pjsip/", 6)) {
1561                 endpoint_name += 6;
1562         }
1563
1564         if (!(endpoint = ast_sorcery_retrieve_by_id(
1565                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1566                 astman_send_error_va(s, m, "Unable to retrieve endpoint %s\n",
1567                         endpoint_name);
1568                 return 0;
1569         }
1570
1571         astman_send_listack(s, m, "Following are Events for each object associated with the the Endpoint",
1572                 "start");
1573
1574         /* the endpoint detail needs to always come first so apply as such */
1575         if (format_ami_endpoint(endpoint, &ami) ||
1576             ast_sip_format_endpoint_ami(endpoint, &ami, &count)) {
1577                 astman_send_error_va(s, m, "Unable to format endpoint %s\n",
1578                         endpoint_name);
1579         }
1580
1581         astman_send_list_complete_start(s, m, "EndpointDetailComplete", ami.count + 1);
1582         astman_send_list_complete_end(s);
1583
1584         return 0;
1585 }
1586
1587 static int format_str_append_auth(const struct ast_sip_auth_vector *auths,
1588                                   struct ast_str **buf)
1589 {
1590         char *str = NULL;
1591         if (ast_sip_auths_to_str(auths, &str)) {
1592                 return -1;
1593         }
1594         ast_str_append(buf, 0, "%s", str ? str : "");
1595         ast_free(str);
1596         return 0;
1597 }
1598
1599 static int format_ami_endpoints(void *obj, void *arg, int flags)
1600 {
1601
1602         struct ast_sip_endpoint *endpoint = obj;
1603         struct ast_sip_ami *ami = arg;
1604         RAII_VAR(struct ast_str *, buf,
1605                  ast_sip_create_ami_event("EndpointList", ami), ast_free);
1606
1607         if (!buf) {
1608                 return CMP_STOP;
1609         }
1610
1611         sip_sorcery_object_ami_set_type_name(endpoint, &buf);
1612         ast_str_append(&buf, 0, "Transport: %s\r\n",
1613                        endpoint->transport);
1614         ast_str_append(&buf, 0, "Aor: %s\r\n",
1615                        endpoint->aors);
1616
1617         ast_str_append(&buf, 0, "Auths: ");
1618         format_str_append_auth(&endpoint->inbound_auths, &buf);
1619         ast_str_append(&buf, 0, "\r\n");
1620
1621         ast_str_append(&buf, 0, "OutboundAuths: ");
1622         format_str_append_auth(&endpoint->outbound_auths, &buf);
1623         ast_str_append(&buf, 0, "\r\n");
1624
1625         ast_sip_for_each_aor(endpoint->aors,
1626                              sip_endpoints_aors_ami, &buf);
1627
1628         ast_str_append(&buf, 0, "DeviceState: %s\r\n",
1629                        ast_sip_get_device_state(endpoint));
1630
1631         ast_str_append(&buf, 0, "ActiveChannels: ");
1632         active_channels_to_str(endpoint, &buf);
1633         ast_str_append(&buf, 0, "\r\n");
1634
1635         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1636         return 0;
1637 }
1638
1639 static int ami_show_endpoints(struct mansession *s, const struct message *m)
1640 {
1641         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
1642         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
1643         int num;
1644
1645         endpoints = ast_sip_get_endpoints();
1646         if (!endpoints) {
1647                 astman_send_error(s, m, "Could not get endpoints\n");
1648                 return 0;
1649         }
1650
1651         if (!(num = ao2_container_count(endpoints))) {
1652                 astman_send_error(s, m, "No endpoints found\n");
1653                 return 0;
1654         }
1655
1656         astman_send_listack(s, m, "A listing of Endpoints follows, presented as EndpointList events",
1657                 "start");
1658
1659         ao2_callback(endpoints, OBJ_NODATA, format_ami_endpoints, &ami);
1660
1661         astman_send_list_complete_start(s, m, "EndpointListComplete", num);
1662         astman_send_list_complete_end(s);
1663         return 0;
1664 }
1665
1666 static struct ao2_container *cli_endpoint_get_container(const char *regex)
1667 {
1668         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
1669         struct ao2_container *s_container;
1670
1671         container = ast_sorcery_retrieve_by_regex(sip_sorcery, "endpoint", regex);
1672         if (!container) {
1673                 return NULL;
1674         }
1675
1676         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
1677                 (void *)ast_sorcery_object_id_sort, (void *)ast_sorcery_object_id_compare);
1678         if (!s_container) {
1679                 return NULL;
1680         }
1681
1682         if (ao2_container_dup(s_container, container, 0)) {
1683                 ao2_ref(s_container, -1);
1684                 return NULL;
1685         }
1686
1687         return s_container;
1688 }
1689
1690 static int cli_endpoint_iterate(void *obj, ao2_callback_fn callback, void *args)
1691 {
1692         ao2_callback(obj, OBJ_NODATA, callback, args);
1693
1694         return 0;
1695 }
1696
1697 static void *cli_endpoint_retrieve_by_id(const char *id)
1698 {
1699         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", id);
1700 }
1701
1702 static void cli_endpoint_print_child_header(char *type, struct ast_sip_cli_context *context)
1703 {
1704         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1705
1706         formatter_entry = ast_sip_lookup_cli_formatter(type);
1707         if (formatter_entry) {
1708                 formatter_entry->print_header(NULL, context, 0);
1709         }
1710 }
1711
1712 static int cli_endpoint_print_header(void *obj, void *arg, int flags)
1713 {
1714         struct ast_sip_cli_context *context = arg;
1715
1716         ast_assert(context->output_buffer != NULL);
1717
1718         ast_str_append(&context->output_buffer, 0,
1719                         " Endpoint:  <Endpoint/CID.....................................>  <State.....>  <Channels.>\n");
1720
1721         if (context->recurse) {
1722                 context->indent_level++;
1723                 cli_endpoint_print_child_header("auth", context);
1724                 cli_endpoint_print_child_header("aor", context);
1725                 cli_endpoint_print_child_header("transport", context);
1726                 cli_endpoint_print_child_header("identify", context);
1727                 cli_endpoint_print_child_header("channel", context);
1728                 context->indent_level--;
1729         }
1730
1731         return 0;
1732 }
1733
1734 static void cli_endpoint_print_child_body(char *type, const void *obj, struct ast_sip_cli_context *context)
1735 {
1736         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1737
1738         formatter_entry = ast_sip_lookup_cli_formatter(type);
1739         if (formatter_entry) {
1740                 formatter_entry->iterate((void *)obj, formatter_entry->print_body, context);
1741         }
1742 }
1743
1744 static int cli_endpoint_print_body(void *obj, void *arg, int flags)
1745 {
1746         struct ast_sip_endpoint *endpoint = obj;
1747         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1748         struct ast_sip_cli_context *context = arg;
1749         const char *id = ast_sorcery_object_get_id(endpoint);
1750         char *print_name = NULL;
1751         int print_name_len;
1752         char *number = S_COR(endpoint->id.self.number.valid,
1753                 endpoint->id.self.number.str, NULL);
1754         int indent;
1755         int flexwidth;
1756
1757         ast_assert(context->output_buffer != NULL);
1758
1759         if (number) {
1760                 print_name_len = strlen(id) + strlen(number) + 2;
1761                 print_name = ast_alloca(print_name_len);
1762                 snprintf(print_name, print_name_len, "%s/%s", id, number);
1763         }
1764
1765         indent = CLI_INDENT_TO_SPACES(context->indent_level);
1766         flexwidth = CLI_LAST_TABSTOP - indent - 2;
1767
1768         ast_str_append(&context->output_buffer, 0, "%*s:  %-*.*s  %-12.12s  %d of %.0f\n",
1769                 indent, "Endpoint",
1770                 flexwidth, flexwidth, print_name ? print_name : id,
1771                 ast_sip_get_device_state(endpoint),
1772                 endpoint_snapshot->num_channels,
1773                 (double) endpoint->devicestate_busy_at ? endpoint->devicestate_busy_at :
1774                                                                                                                 INFINITY
1775                                                                                                                 );
1776
1777         if (context->recurse) {
1778                 context->indent_level++;
1779
1780                 context->auth_direction = "Out";
1781                 cli_endpoint_print_child_body("auth", &endpoint->outbound_auths, context);
1782                 context->auth_direction = "In";
1783                 cli_endpoint_print_child_body("auth", &endpoint->inbound_auths, context);
1784
1785                 cli_endpoint_print_child_body("aor", endpoint->aors, context);
1786                 cli_endpoint_print_child_body("transport", endpoint, context);
1787                 cli_endpoint_print_child_body("identify", endpoint, context);
1788                 cli_endpoint_print_child_body("channel", endpoint, context);
1789
1790                 context->indent_level--;
1791
1792                 if (context->indent_level == 0) {
1793                         ast_str_append(&context->output_buffer, 0, "\n");
1794                 }
1795         }
1796
1797         if (context->show_details || (context->show_details_only_level_0 && context->indent_level == 0)) {
1798                 ast_str_append(&context->output_buffer, 0, "\n");
1799                 ast_sip_cli_print_sorcery_objectset(endpoint, context, 0);
1800         }
1801
1802         return 0;
1803 }
1804
1805 static struct ast_cli_entry cli_commands[] = {
1806         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "List PJSIP Endpoints",
1807                 .command = "pjsip list endpoints",
1808                 .usage = "Usage: pjsip list endpoints [ like <pattern> ]\n"
1809                                 "       List the configured PJSIP endpoints\n"
1810                                 "       Optional regular expression pattern is used to filter the list.\n"),
1811         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoints",
1812                 .command = "pjsip show endpoints",
1813                 .usage = "Usage: pjsip show endpoints [ like <pattern> ]\n"
1814                                 "       List(detailed) the configured PJSIP endpoints\n"
1815                                 "       Optional regular expression pattern is used to filter the list.\n"),
1816         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoint",
1817                 .command = "pjsip show endpoint",
1818                 .usage = "Usage: pjsip show endpoint <id>\n"
1819                                  "       Show the configured PJSIP endpoint\n"),
1820 };
1821
1822 struct ast_sip_cli_formatter_entry *channel_formatter;
1823 struct ast_sip_cli_formatter_entry *endpoint_formatter;
1824
1825 static int on_load_endpoint(void *obj, void *arg, int flags)
1826 {
1827         return sip_endpoint_apply_handler(sip_sorcery, obj);
1828 }
1829
1830 static void load_all_endpoints(void)
1831 {
1832         struct ao2_container *endpoints;
1833
1834         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1835         if (endpoints) {
1836                 ao2_callback(endpoints, OBJ_NODATA, on_load_endpoint, NULL);
1837                 ao2_ref(endpoints, -1);
1838         }
1839 }
1840
1841 int ast_res_pjsip_initialize_configuration(void)
1842 {
1843         if (ast_manager_register_xml(AMI_SHOW_ENDPOINTS, EVENT_FLAG_SYSTEM, ami_show_endpoints) ||
1844             ast_manager_register_xml(AMI_SHOW_ENDPOINT, EVENT_FLAG_SYSTEM, ami_show_endpoint)) {
1845                 return -1;
1846         }
1847
1848         persistent_endpoints = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0,
1849                 PERSISTENT_BUCKETS, persistent_endpoint_hash, NULL, persistent_endpoint_cmp);
1850         if (!persistent_endpoints) {
1851                 return -1;
1852         }
1853
1854         if (!(sip_sorcery = ast_sorcery_open())) {
1855                 ast_log(LOG_ERROR, "Failed to open SIP sorcery failed to open\n");
1856                 return -1;
1857         }
1858
1859         ast_sip_initialize_cli();
1860
1861         if (ast_sip_initialize_sorcery_auth()) {
1862                 ast_log(LOG_ERROR, "Failed to register SIP authentication support\n");
1863                 ast_sorcery_unref(sip_sorcery);
1864                 sip_sorcery = NULL;
1865                 return -1;
1866         }
1867
1868         ast_sorcery_apply_default(sip_sorcery, "endpoint", "config", "pjsip.conf,criteria=type=endpoint");
1869         ast_sorcery_apply_default(sip_sorcery, "nat_hook", "memory", NULL);
1870
1871         if (ast_sorcery_object_register(sip_sorcery, "endpoint", ast_sip_endpoint_alloc, NULL, sip_endpoint_apply_handler)) {
1872                 ast_log(LOG_ERROR, "Failed to register SIP endpoint object with sorcery\n");
1873                 ast_sorcery_unref(sip_sorcery);
1874                 sip_sorcery = NULL;
1875                 return -1;
1876         }
1877
1878         if (ast_sorcery_internal_object_register(sip_sorcery, "nat_hook", sip_nat_hook_alloc, NULL, NULL)) {
1879                 ast_log(LOG_ERROR, "Failed to register nat_hook\n");
1880         }
1881
1882         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "type", "", OPT_NOOP_T, 0, 0);
1883         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "context", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, context));
1884         ast_sorcery_object_field_register_alias(sip_sorcery, "endpoint", "disallow", "", OPT_CODEC_T, 0, FLDSET(struct ast_sip_endpoint, media.codecs));
1885         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow", "", OPT_CODEC_T, 1, FLDSET(struct ast_sip_endpoint, media.codecs));
1886         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtmf_mode", "rfc4733", dtmf_handler, dtmf_to_str, NULL, 0, 0);
1887         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ipv6));
1888         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_symmetric", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.symmetric));
1889         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "ice_support", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ice_support));
1890         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_ptime", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_ptime));
1891         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_rport", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.force_rport));
1892         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rewrite_contact", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.rewrite_contact));
1893         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, transport));
1894         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, outbound_proxy));
1895         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_suggest", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, mohsuggest));
1896         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "100rel", "yes", prack_handler, prack_to_str, NULL, 0, 0);
1897         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "timers", "yes", timers_handler, timers_to_str, NULL, 0, 0);
1898         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));
1899         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));
1900         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "auth", "", inbound_auth_handler, inbound_auths_to_str, NULL, 0, 0);
1901         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, NULL, 0, 0);
1902         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aors", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, aors));
1903         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_address", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.address));
1904         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));
1905         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "identify_by", "username", ident_handler, ident_to_str, NULL, 0, 0);
1906         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "direct_media", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.direct_media.enabled));
1907         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);
1908         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);
1909         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);
1910         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));
1911         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid", "", caller_id_handler, caller_id_to_str, NULL, 0, 0);
1912         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);
1913         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_tag", "", caller_id_tag_handler, caller_id_tag_to_str, NULL, 0, 0);
1914         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_inbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_inbound));
1915         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_outbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_outbound));
1916         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_pai", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_pai));
1917         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_rpid", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_rpid));
1918         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rpid_immediate", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.rpid_immediate));
1919         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_diversion", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_diversion));
1920         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mailboxes", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.mailboxes));
1921         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "voicemail_extension", "", voicemail_extension_handler, voicemail_extension_to_str, NULL, 0, 0);
1922         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aggregate_mwi", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.aggregate));
1923         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));
1924         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "media_encryption", "no", media_encryption_handler, media_encryption_to_str, NULL, 0, 0);
1925         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_avpf", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_avpf));
1926         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_avp", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.force_avp));
1927         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));
1928         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_keepalive", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.keepalive));
1929         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_timeout", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.timeout));
1930         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));
1931         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "one_touch_recording", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, info.recording.enabled));
1932         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "inband_progress", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, inband_progress));
1933         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "call_group", "", group_handler, callgroup_to_str, NULL, 0, 0);
1934         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "pickup_group", "", group_handler, pickupgroup_to_str, NULL, 0, 0);
1935         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_call_group", "", named_groups_handler, named_callgroups_to_str, NULL, 0, 0);
1936         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_pickup_group", "", named_groups_handler, named_pickupgroups_to_str, NULL, 0, 0);
1937         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));
1938         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.enabled));
1939         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "t38_udptl_ec", "none", t38udptl_ec_handler, t38udptl_ec_to_str, NULL, 0, 0);
1940         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_maxdatagram", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.t38.maxdatagram));
1941         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, faxdetect));
1942         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect_timeout", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, faxdetect_timeout));
1943         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_nat", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.nat));
1944         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.ipv6));
1945         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tone_zone", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, zone));
1946         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "language", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, language));
1947         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_on_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.onfeature));
1948         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_off_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.offfeature));
1949         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_transfer", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allowtransfer));
1950         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "user_eq_phone", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, usereqphone));
1951         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_passthrough", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, moh_passthrough));
1952         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_owner", "-", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpowner));
1953         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_session", "Asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpsession));
1954         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_audio", "0", tos_handler, tos_audio_to_str, NULL, 0, 0);
1955         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_video", "0", tos_handler, tos_video_to_str, NULL, 0, 0);
1956         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_audio", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_audio));
1957         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_video", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_video));
1958         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_subscribe", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.allow));
1959         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sub_min_expiry", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, subscription.minexpiry));
1960         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "from_user", "", from_user_handler, from_user_to_str, NULL, 0, 0);
1961         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_domain", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromdomain));
1962         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.fromuser));
1963         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_engine", "asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.rtp.engine));
1964         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_verify", "no", dtls_handler, dtlsverify_to_str, NULL, 0, 0);
1965         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_rekey", "0", dtls_handler, dtlsrekey_to_str, NULL, 0, 0);
1966         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cert_file", "", dtls_handler, dtlscertfile_to_str, NULL, 0, 0);
1967         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_private_key", "", dtls_handler, dtlsprivatekey_to_str, NULL, 0, 0);
1968         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cipher", "", dtls_handler, dtlscipher_to_str, NULL, 0, 0);
1969         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_file", "", dtls_handler, dtlscafile_to_str, NULL, 0, 0);
1970         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_path", "", dtls_handler, dtlscapath_to_str, NULL, 0, 0);
1971         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_setup", "", dtls_handler, dtlssetup_to_str, NULL, 0, 0);
1972         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_fingerprint", "", dtls_handler, dtlsfingerprint_to_str, NULL, 0, 0);
1973         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));
1974         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));
1975         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));
1976         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "redirect_method", "user", redirect_handler, NULL, NULL, 0, 0);
1977         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "set_var", "", set_var_handler, set_var_to_str, set_var_to_vl, 0, 0);
1978         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "message_context", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, message_context));
1979         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "accountcode", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, accountcode));
1980         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "deny", "", endpoint_acl_handler, NULL, NULL, 0, 0);
1981         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "permit", "", endpoint_acl_handler, NULL, NULL, 0, 0);
1982         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "acl", "", endpoint_acl_handler, acl_to_str, NULL, 0, 0);
1983         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_deny", "", endpoint_acl_handler, NULL, NULL, 0, 0);
1984         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_permit", "", endpoint_acl_handler, NULL, NULL, 0, 0);
1985         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_acl", "", endpoint_acl_handler, contact_acl_to_str, NULL, 0, 0);
1986         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "subscribe_context", "", OPT_CHAR_ARRAY_T, 0, CHARFLDSET(struct ast_sip_endpoint, subscription.context));
1987         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "contact_user", "", contact_user_handler, contact_user_to_str, NULL, 0, 0);
1988         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "preferred_codec_only", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, preferred_codec_only));
1989         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "asymmetric_rtp_codec", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, asymmetric_rtp_codec));
1990         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtcp_mux", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtcp_mux));
1991         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_overlap", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allow_overlap));
1992         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "refer_blind_progress", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, refer_blind_progress));
1993         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));
1994         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));
1995         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));
1996         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "bundle", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.bundle));
1997         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "webrtc", "no", OPT_YESNO_T, 1, FLDSET(struct ast_sip_endpoint, media.webrtc));
1998
1999         if (ast_sip_initialize_sorcery_transport()) {
2000                 ast_log(LOG_ERROR, "Failed to register SIP transport support with sorcery\n");
2001                 ast_sorcery_unref(sip_sorcery);
2002                 sip_sorcery = NULL;
2003                 return -1;
2004         }
2005
2006         if (ast_sip_initialize_sorcery_location()) {
2007                 ast_log(LOG_ERROR, "Failed to register SIP location support with sorcery\n");
2008                 ast_sorcery_unref(sip_sorcery);
2009                 sip_sorcery = NULL;
2010                 return -1;
2011         }
2012
2013         if (ast_sip_initialize_sorcery_qualify()) {
2014                 ast_log(LOG_ERROR, "Failed to register SIP qualify support with sorcery\n");
2015                 ast_sorcery_unref(sip_sorcery);
2016                 sip_sorcery = NULL;
2017                 return -1;
2018         }
2019
2020         ast_sorcery_observer_add(sip_sorcery, "endpoint", &endpoint_observers);
2021         ast_sorcery_observer_add(sip_sorcery, "contact", &state_contact_observer);
2022         ast_sorcery_observer_add(sip_sorcery, CONTACT_STATUS, &state_contact_status_observer);
2023
2024         if (ast_sip_initialize_sorcery_domain_alias()) {
2025                 ast_log(LOG_ERROR, "Failed to register SIP domain aliases support with sorcery\n");
2026                 ast_sorcery_unref(sip_sorcery);
2027                 sip_sorcery = NULL;
2028                 return -1;
2029         }
2030
2031         if (ast_sip_initialize_sorcery_global()) {
2032                 ast_log(LOG_ERROR, "Failed to register SIP Global support\n");
2033                 ast_sorcery_unref(sip_sorcery);
2034                 sip_sorcery = NULL;
2035                 return -1;
2036         }
2037
2038         endpoint_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
2039         if (!endpoint_formatter) {
2040                 ast_log(LOG_ERROR, "Unable to allocate memory for endpoint_formatter\n");
2041                 ast_sorcery_unref(sip_sorcery);
2042                 sip_sorcery = NULL;
2043                 return -1;
2044         }
2045         endpoint_formatter->name = "endpoint";
2046         endpoint_formatter->print_header = cli_endpoint_print_header;
2047         endpoint_formatter->print_body = cli_endpoint_print_body;
2048         endpoint_formatter->get_container = cli_endpoint_get_container;
2049         endpoint_formatter->iterate = cli_endpoint_iterate;
2050         endpoint_formatter->retrieve_by_id = cli_endpoint_retrieve_by_id;
2051         endpoint_formatter->get_id = ast_sorcery_object_get_id;
2052
2053         ast_sip_register_cli_formatter(endpoint_formatter);
2054         ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
2055
2056         ast_sorcery_load(sip_sorcery);
2057
2058         load_all_endpoints();
2059
2060         return 0;
2061 }
2062
2063 void ast_res_pjsip_destroy_configuration(void)
2064 {
2065         if (!sip_sorcery) {
2066                 return;
2067         }
2068
2069         ast_sorcery_observer_remove(sip_sorcery, CONTACT_STATUS, &state_contact_status_observer);
2070         ast_sorcery_observer_remove(sip_sorcery, "contact", &state_contact_observer);
2071         ast_sip_destroy_sorcery_global();
2072         ast_sip_destroy_sorcery_location();
2073         ast_sip_destroy_sorcery_auth();
2074         ast_sip_destroy_sorcery_transport();
2075         ast_sorcery_unref(sip_sorcery);
2076         sip_sorcery = NULL;
2077         ast_manager_unregister(AMI_SHOW_ENDPOINT);
2078         ast_manager_unregister(AMI_SHOW_ENDPOINTS);
2079         ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
2080         ast_sip_unregister_cli_formatter(endpoint_formatter);
2081         ast_sip_destroy_cli();
2082         ao2_cleanup(persistent_endpoints);
2083         persistent_endpoints = NULL;
2084 }
2085
2086 int ast_res_pjsip_reload_configuration(void)
2087 {
2088         if (sip_sorcery) {
2089                 ast_sorcery_reload(sip_sorcery);
2090         }
2091         return 0;
2092 }
2093
2094 static void subscription_configuration_destroy(struct ast_sip_endpoint_subscription_configuration *subscription)
2095 {
2096         ast_string_field_free_memory(&subscription->mwi);
2097         ast_free(subscription->mwi.voicemail_extension);
2098 }
2099
2100 static void info_configuration_destroy(struct ast_sip_endpoint_info_configuration *info)
2101 {
2102         ast_string_field_free_memory(&info->recording);
2103 }
2104
2105 static void media_configuration_destroy(struct ast_sip_endpoint_media_configuration *media)
2106 {
2107         ast_string_field_free_memory(&media->rtp);
2108         ast_string_field_free_memory(media);
2109 }
2110
2111 static void endpoint_destructor(void* obj)
2112 {
2113         struct ast_sip_endpoint *endpoint = obj;
2114
2115         ast_string_field_free_memory(endpoint);
2116
2117         ao2_cleanup(endpoint->media.codecs);
2118         ast_stream_topology_free(endpoint->media.topology);
2119         subscription_configuration_destroy(&endpoint->subscription);
2120         info_configuration_destroy(&endpoint->info);
2121         media_configuration_destroy(&endpoint->media);
2122         ast_sip_auth_vector_destroy(&endpoint->inbound_auths);
2123         ast_sip_auth_vector_destroy(&endpoint->outbound_auths);
2124         ast_party_id_free(&endpoint->id.self);
2125         endpoint->pickup.named_callgroups = ast_unref_namedgroups(endpoint->pickup.named_callgroups);
2126         endpoint->pickup.named_pickupgroups = ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
2127         ao2_cleanup(endpoint->persistent);
2128         ast_variables_destroy(endpoint->channel_vars);
2129         AST_VECTOR_FREE(&endpoint->ident_method_order);
2130         ast_free(endpoint->contact_user);
2131         ast_free_acl_list(endpoint->contact_acl);
2132         ast_free_acl_list(endpoint->acl);
2133 }
2134
2135 static int init_subscription_configuration(struct ast_sip_endpoint_subscription_configuration *subscription)
2136 {
2137         return ast_string_field_init(&subscription->mwi, 64);
2138 }
2139
2140 static int init_info_configuration(struct ast_sip_endpoint_info_configuration *info)
2141 {
2142         return ast_string_field_init(&info->recording, 32);
2143 }
2144
2145 static int init_media_configuration(struct ast_sip_endpoint_media_configuration *media)
2146 {
2147         return ast_string_field_init(media, 64) || ast_string_field_init(&media->rtp, 32);
2148 }
2149
2150 void *ast_sip_endpoint_alloc(const char *name)
2151 {
2152         struct ast_sip_endpoint *endpoint = ast_sorcery_generic_alloc(sizeof(*endpoint), endpoint_destructor);
2153         if (!endpoint) {
2154                 return NULL;
2155         }
2156         if (ast_string_field_init(endpoint, 64)) {
2157                 ao2_cleanup(endpoint);
2158                 return NULL;
2159         }
2160         if (!(endpoint->media.codecs = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2161                 ao2_cleanup(endpoint);
2162                 return NULL;
2163         }
2164         if (init_subscription_configuration(&endpoint->subscription)) {
2165                 ao2_cleanup(endpoint);
2166                 return NULL;
2167         }
2168         if (init_info_configuration(&endpoint->info)) {
2169                 ao2_cleanup(endpoint);
2170                 return NULL;
2171         }
2172         if (init_media_configuration(&endpoint->media)) {
2173                 ao2_cleanup(endpoint);
2174                 return NULL;
2175         }
2176         ast_party_id_init(&endpoint->id.self);
2177
2178         if (AST_VECTOR_INIT(&endpoint->ident_method_order, 1)) {
2179                 return NULL;
2180         }
2181
2182         return endpoint;
2183 }
2184
2185 struct ao2_container *ast_sip_get_endpoints(void)
2186 {
2187         struct ao2_container *endpoints;
2188
2189         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
2190
2191         return endpoints;
2192 }
2193
2194 struct ast_sip_endpoint *ast_sip_default_outbound_endpoint(void)
2195 {
2196         RAII_VAR(char *, name, ast_sip_global_default_outbound_endpoint(), ast_free);
2197         return ast_strlen_zero(name) ? NULL : ast_sorcery_retrieve_by_id(
2198                 sip_sorcery, "endpoint", name);
2199 }
2200
2201 int ast_sip_retrieve_auths(const struct ast_sip_auth_vector *auths, struct ast_sip_auth **out)
2202 {
2203         int i;
2204
2205         for (i = 0; i < AST_VECTOR_SIZE(auths); ++i) {
2206                 /* Using AST_VECTOR_GET is safe since the vector is immutable */
2207                 const char *name = AST_VECTOR_GET(auths, i);
2208                 out[i] = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), SIP_SORCERY_AUTH_TYPE, name);
2209                 if (!out[i]) {
2210                         ast_log(LOG_NOTICE, "Couldn't find auth '%s'. Cannot authenticate\n", name);
2211                         return -1;
2212                 }
2213         }
2214
2215         return 0;
2216 }
2217
2218 void ast_sip_cleanup_auths(struct ast_sip_auth *auths[], size_t num_auths)
2219 {
2220         int i;
2221         for (i = 0; i < num_auths; ++i) {
2222                 ao2_cleanup(auths[i]);
2223         }
2224 }
2225
2226 struct ast_sorcery *ast_sip_get_sorcery(void)
2227 {
2228         return sip_sorcery;
2229 }