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