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