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