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