7dad58c1531a6f61c0b01bc244db5082d3d567fa
[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                 endpoint->pickup.callgroup = ast_get_group(var->value);
563         } else if (!strncmp(var->name, "pickup_group", 12)) {
564                 endpoint->pickup.pickupgroup = ast_get_group(var->value);
565         } else {
566                 return -1;
567         }
568
569         return 0;
570 }
571
572 static int callgroup_to_str(const void *obj, const intptr_t *args, char **buf)
573 {
574         const struct ast_sip_endpoint *endpoint = obj;
575
576         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
577                 return -1;
578         }
579
580         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.callgroup);
581         return 0;
582 }
583
584 static int pickupgroup_to_str(const void *obj, const intptr_t *args, char **buf)
585 {
586         const struct ast_sip_endpoint *endpoint = obj;
587
588         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
589                 return -1;
590         }
591
592         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.pickupgroup);
593         return 0;
594 }
595
596 static int named_groups_handler(const struct aco_option *opt,
597                                 struct ast_variable *var, void *obj)
598 {
599         struct ast_sip_endpoint *endpoint = obj;
600
601         if (!strncmp(var->name, "named_call_group", 16)) {
602                 if (ast_strlen_zero(var->value)) {
603                         endpoint->pickup.named_callgroups =
604                                 ast_unref_namedgroups(endpoint->pickup.named_callgroups);
605                 } else if (!(endpoint->pickup.named_callgroups =
606                       ast_get_namedgroups(var->value))) {
607                         return -1;
608                 }
609         } else if (!strncmp(var->name, "named_pickup_group", 18)) {
610                 if (ast_strlen_zero(var->value)) {
611                         endpoint->pickup.named_pickupgroups =
612                                 ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
613                 } else if (!(endpoint->pickup.named_pickupgroups =
614                       ast_get_namedgroups(var->value))) {
615                         return -1;
616                 }
617         } else {
618                 return -1;
619         }
620
621         return 0;
622 }
623
624 static int named_callgroups_to_str(const void *obj, const intptr_t *args, char **buf)
625 {
626         const struct ast_sip_endpoint *endpoint = obj;
627         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
628
629         ast_print_namedgroups(&str, endpoint->pickup.named_callgroups);
630         *buf = ast_strdup(ast_str_buffer(str));
631         return 0;
632 }
633
634 static int named_pickupgroups_to_str(const void *obj, const intptr_t *args, char **buf)
635 {
636         const struct ast_sip_endpoint *endpoint = obj;
637         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
638
639         ast_print_namedgroups(&str, endpoint->pickup.named_pickupgroups);
640         *buf = ast_strdup(ast_str_buffer(str));
641         return 0;
642 }
643
644 static int dtls_handler(const struct aco_option *opt,
645                          struct ast_variable *var, void *obj)
646 {
647         struct ast_sip_endpoint *endpoint = obj;
648         char *name = ast_strdupa(var->name);
649         char *front, *buf = name;
650
651         /* strip out underscores in the name */
652         front = strtok(buf, "_");
653         while (front) {
654                 int size = strlen(front);
655                 ast_copy_string(buf, front, size + 1);
656                 buf += size;
657                 front = strtok(NULL, "_");
658         }
659
660         return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, name, var->value);
661 }
662
663 static int dtlsverify_to_str(const void *obj, const intptr_t *args, char **buf)
664 {
665         const struct ast_sip_endpoint *endpoint = obj;
666         *buf = ast_strdup(AST_YESNO(endpoint->media.rtp.dtls_cfg.verify));
667         return 0;
668 }
669
670 static int dtlsrekey_to_str(const void *obj, const intptr_t *args, char **buf)
671 {
672         const struct ast_sip_endpoint *endpoint = obj;
673
674         return ast_asprintf(
675                 buf, "%u", endpoint->media.rtp.dtls_cfg.rekey) >=0 ? 0 : -1;
676 }
677
678 static int dtlscertfile_to_str(const void *obj, const intptr_t *args, char **buf)
679 {
680         const struct ast_sip_endpoint *endpoint = obj;
681         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.certfile);
682         return 0;
683 }
684
685 static int dtlsprivatekey_to_str(const void *obj, const intptr_t *args, char **buf)
686 {
687         const struct ast_sip_endpoint *endpoint = obj;
688         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.pvtfile);
689         return 0;
690 }
691
692 static int dtlscipher_to_str(const void *obj, const intptr_t *args, char **buf)
693 {
694         const struct ast_sip_endpoint *endpoint = obj;
695         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cipher);
696         return 0;
697 }
698
699 static int dtlscafile_to_str(const void *obj, const intptr_t *args, char **buf)
700 {
701         const struct ast_sip_endpoint *endpoint = obj;
702         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cafile);
703         return 0;
704 }
705
706 static int dtlscapath_to_str(const void *obj, const intptr_t *args, char **buf)
707 {
708         const struct ast_sip_endpoint *endpoint = obj;
709         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.capath);
710         return 0;
711 }
712
713 static const char *ast_rtp_dtls_setup_map[] = {
714         [AST_RTP_DTLS_SETUP_ACTIVE] = "active",
715         [AST_RTP_DTLS_SETUP_PASSIVE] = "passive",
716         [AST_RTP_DTLS_SETUP_ACTPASS] = "actpass",
717         [AST_RTP_DTLS_SETUP_HOLDCONN] = "holdconn",
718 };
719
720 static int dtlssetup_to_str(const void *obj, const intptr_t *args, char **buf)
721 {
722         const struct ast_sip_endpoint *endpoint = obj;
723         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.default_setup, ast_rtp_dtls_setup_map)) {
724                 *buf = ast_strdup(ast_rtp_dtls_setup_map[endpoint->media.rtp.dtls_cfg.default_setup]);
725         }
726         return 0;
727 }
728
729 static const char *ast_rtp_dtls_fingerprint_map[] = {
730         [AST_RTP_DTLS_HASH_SHA256] = "SHA-256",
731         [AST_RTP_DTLS_HASH_SHA1] = "SHA-1",
732 };
733
734 static int dtlsfingerprint_to_str(const void *obj, const intptr_t *args, char **buf)
735 {
736         const struct ast_sip_endpoint *endpoint = obj;
737         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.hash, ast_rtp_dtls_fingerprint_map)) {
738                 *buf = ast_strdup(ast_rtp_dtls_fingerprint_map[endpoint->media.rtp.dtls_cfg.hash]);
739         }
740         return 0;
741 }
742
743 static int t38udptl_ec_handler(const struct aco_option *opt,
744         struct ast_variable *var, void *obj)
745 {
746         struct ast_sip_endpoint *endpoint = obj;
747
748         if (!strcmp(var->value, "none")) {
749                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_NONE;
750         } else if (!strcmp(var->value, "fec")) {
751                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_FEC;
752         } else if (!strcmp(var->value, "redundancy")) {
753                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_REDUNDANCY;
754         } else {
755                 return -1;
756         }
757
758         return 0;
759 }
760
761 static const char *ast_t38_ec_modes_map[] = {
762         [UDPTL_ERROR_CORRECTION_NONE] = "none",
763         [UDPTL_ERROR_CORRECTION_FEC] = "fec",
764         [UDPTL_ERROR_CORRECTION_REDUNDANCY] = "redundancy"
765 };
766
767 static int t38udptl_ec_to_str(const void *obj, const intptr_t *args, char **buf)
768 {
769         const struct ast_sip_endpoint *endpoint = obj;
770         if (ARRAY_IN_BOUNDS(endpoint->media.t38.error_correction, ast_t38_ec_modes_map)) {
771                 *buf = ast_strdup(ast_t38_ec_modes_map[
772                                           endpoint->media.t38.error_correction]);
773         }
774         return 0;
775 }
776
777 static int tos_handler(const struct aco_option *opt,
778         struct ast_variable *var, void *obj)
779 {
780         struct ast_sip_endpoint *endpoint = obj;
781         unsigned int value;
782
783         if (ast_str2tos(var->value, &value)) {
784                 ast_log(LOG_ERROR, "Error configuring endpoint '%s' - Could not "
785                         "interpret '%s' value '%s'\n",
786                         ast_sorcery_object_get_id(endpoint), var->name, var->value);
787                 return -1;
788         }
789
790         if (!strcmp(var->name, "tos_audio")) {
791                 endpoint->media.tos_audio = value;
792         } else if (!strcmp(var->name, "tos_video")) {
793                 endpoint->media.tos_video = value;
794         } else {
795                 /* If we reach this point, someone called the tos_handler when they shouldn't have. */
796                 ast_assert(0);
797                 return -1;
798         }
799         return 0;
800 }
801
802 static int tos_audio_to_str(const void *obj, const intptr_t *args, char **buf)
803 {
804         const struct ast_sip_endpoint *endpoint = obj;
805
806         if (ast_asprintf(buf, "%u", endpoint->media.tos_audio) == -1) {
807                 return -1;
808         }
809         return 0;
810 }
811
812 static int tos_video_to_str(const void *obj, const intptr_t *args, char **buf)
813 {
814         const struct ast_sip_endpoint *endpoint = obj;
815
816         if (ast_asprintf(buf, "%u", endpoint->media.tos_video) == -1) {
817                 return -1;
818         }
819         return 0;
820 }
821
822 static int set_var_handler(const struct aco_option *opt,
823         struct ast_variable *var, void *obj)
824 {
825         struct ast_sip_endpoint *endpoint = obj;
826         struct ast_variable *new_var;
827         char *name;
828         char *val;
829
830         if (ast_strlen_zero(var->value)) {
831                 return 0;
832         }
833
834         name = ast_strdupa(var->value);
835         val = strchr(name, '=');
836
837         if (!val) {
838                 return -1;
839         }
840
841         *val++ = '\0';
842
843         if (!(new_var = ast_variable_new(name, val, ""))) {
844                 return -1;
845         }
846
847         ast_variable_list_append(&endpoint->channel_vars, new_var);
848
849         return 0;
850 }
851
852 static int set_var_to_str(const void *obj, const intptr_t *args, char **buf)
853 {
854         struct ast_str *str = ast_str_create(MAX_OBJECT_FIELD);
855         const struct ast_sip_endpoint *endpoint = obj;
856         struct ast_variable *var;
857
858         for (var = endpoint->channel_vars; var; var = var->next) {
859                 ast_str_append(&str, 0, "%s=%s,", var->name, var->value);
860         }
861
862         *buf = ast_strdup(ast_str_truncate(str, -1));
863         ast_free(str);
864         return 0;
865 }
866
867 static int set_var_to_vl(const void *obj, struct ast_variable **fields)
868 {
869         const struct ast_sip_endpoint *endpoint = obj;
870         if (endpoint->channel_vars) {
871                 *fields = ast_variables_dup(endpoint->channel_vars);
872         }
873         return 0;
874 }
875
876
877 static void *sip_nat_hook_alloc(const char *name)
878 {
879         return ast_sorcery_generic_alloc(sizeof(struct ast_sip_nat_hook), NULL);
880 }
881
882 /*! \brief Destructor function for persistent endpoint information */
883 static void persistent_endpoint_destroy(void *obj)
884 {
885         struct sip_persistent_endpoint *persistent = obj;
886
887         ast_endpoint_shutdown(persistent->endpoint);
888         ast_free(persistent->aors);
889 }
890
891 /*! \brief Internal function which finds (or creates) persistent endpoint information */
892 static struct ast_endpoint *persistent_endpoint_find_or_create(const struct ast_sip_endpoint *endpoint)
893 {
894         RAII_VAR(struct sip_persistent_endpoint *, persistent, NULL, ao2_cleanup);
895         SCOPED_AO2LOCK(lock, persistent_endpoints);
896
897         if (!(persistent = ao2_find(persistent_endpoints, ast_sorcery_object_get_id(endpoint), OBJ_KEY | OBJ_NOLOCK))) {
898                 if (!(persistent = ao2_alloc(sizeof(*persistent), persistent_endpoint_destroy))) {
899                         return NULL;
900                 }
901
902                 if (!(persistent->endpoint = ast_endpoint_create("PJSIP", ast_sorcery_object_get_id(endpoint)))) {
903                         return NULL;
904                 }
905
906                 persistent->aors = ast_strdup(endpoint->aors);
907
908                 if (ast_strlen_zero(persistent->aors)) {
909                         ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_UNKNOWN);
910                 } else {
911                         persistent_endpoint_update_state(persistent, NULL, 0);
912                 }
913
914                 ao2_link_flags(persistent_endpoints, persistent, OBJ_NOLOCK);
915         }
916
917         ao2_ref(persistent->endpoint, +1);
918         return persistent->endpoint;
919 }
920
921 /*! \brief Helper function which validates an outbound proxy */
922 static int outbound_proxy_validate(void *data)
923 {
924         const char *proxy = data;
925         pj_pool_t *pool;
926         pj_str_t tmp;
927         static const pj_str_t ROUTE_HNAME = { "Route", 5 };
928
929         pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Outbound Proxy Validation", 256, 256);
930         if (!pool) {
931                 return -1;
932         }
933
934         pj_strdup2_with_null(pool, &tmp, proxy);
935         if (!pjsip_parse_hdr(pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL)) {
936                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
937                 return -1;
938         }
939
940         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
941         return 0;
942 }
943
944 /*! \brief Callback function for when an object is finalized */
945 static int sip_endpoint_apply_handler(const struct ast_sorcery *sorcery, void *obj)
946 {
947         struct ast_sip_endpoint *endpoint = obj;
948
949         if (!(endpoint->persistent = persistent_endpoint_find_or_create(endpoint))) {
950                 return -1;
951         }
952
953         if (!ast_strlen_zero(endpoint->outbound_proxy) &&
954                 ast_sip_push_task_synchronous(NULL, outbound_proxy_validate, (char*)endpoint->outbound_proxy)) {
955                 ast_log(LOG_ERROR, "Invalid outbound proxy '%s' specified on endpoint '%s'\n",
956                         endpoint->outbound_proxy, ast_sorcery_object_get_id(endpoint));
957                 return -1;
958         } else if (endpoint->extensions.timer.min_se < 90) {
959                 ast_log(LOG_ERROR, "Session timer minimum expires time must be 90 or greater on endpoint '%s'\n",
960                         ast_sorcery_object_get_id(endpoint));
961                 return -1;
962         } else if (endpoint->extensions.timer.sess_expires < endpoint->extensions.timer.min_se) {
963                 ast_log(LOG_ERROR, "Session timer expires must be greater than minimum session expires time on endpoint '%s'\n",
964                         ast_sorcery_object_get_id(endpoint));
965                 return -1;
966         }
967
968         return 0;
969 }
970
971 const char *ast_sip_get_device_state(const struct ast_sip_endpoint *endpoint)
972 {
973         char device[MAX_OBJECT_FIELD];
974
975         snprintf(device, MAX_OBJECT_FIELD, "PJSIP/%s", ast_sorcery_object_get_id(endpoint));
976         return ast_devstate2str(ast_device_state(device));
977 }
978
979 struct ast_endpoint_snapshot *ast_sip_get_endpoint_snapshot(
980         const struct ast_sip_endpoint *endpoint)
981 {
982         return ast_endpoint_latest_snapshot(
983                 ast_endpoint_get_tech(endpoint->persistent),
984                 ast_endpoint_get_resource(endpoint->persistent));
985 }
986
987 int ast_sip_for_each_channel_snapshot(
988         const struct ast_endpoint_snapshot *endpoint_snapshot,
989         ao2_callback_fn on_channel_snapshot, void *arg)
990 {
991         int num, num_channels = endpoint_snapshot->num_channels;
992
993         if (!on_channel_snapshot || !num_channels) {
994                 return 0;
995         }
996
997         for (num = 0; num < num_channels; ++num) {
998                 RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
999                 int res;
1000
1001                 snapshot = ast_channel_snapshot_get_latest(endpoint_snapshot->channel_ids[num]);
1002                 if (!snapshot) {
1003                         continue;
1004                 }
1005
1006                 res = on_channel_snapshot(snapshot, arg, 0);
1007                 if (res) {
1008                         return -1;
1009                 }
1010         }
1011         return 0;
1012 }
1013
1014 int ast_sip_for_each_channel(
1015         const struct ast_sip_endpoint *endpoint,
1016         ao2_callback_fn on_channel_snapshot, void *arg)
1017 {
1018         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1019         return ast_sip_for_each_channel_snapshot(endpoint_snapshot, on_channel_snapshot, arg);
1020 }
1021
1022 static int active_channels_to_str_cb(void *object, void *arg, int flags)
1023 {
1024         const struct ast_channel_snapshot *snapshot = object;
1025         struct ast_str **buf = arg;
1026         ast_str_append(buf, 0, "%s,", snapshot->name);
1027         return 0;
1028 }
1029
1030 static void active_channels_to_str(const struct ast_sip_endpoint *endpoint,
1031                                    struct ast_str **str)
1032 {
1033
1034         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot,
1035                  ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1036
1037         if (endpoint_snapshot) {
1038                 return;
1039         }
1040
1041         ast_sip_for_each_channel_snapshot(endpoint_snapshot,
1042                                           active_channels_to_str_cb, str);
1043         ast_str_truncate(*str, -1);
1044 }
1045
1046 #define AMI_DEFAULT_STR_SIZE 512
1047
1048 struct ast_str *ast_sip_create_ami_event(const char *event, struct ast_sip_ami *ami)
1049 {
1050         struct ast_str *buf = ast_str_create(AMI_DEFAULT_STR_SIZE);
1051
1052         if (!(buf)) {
1053                 astman_send_error_va(ami->s, ami->m, "Unable create event "
1054                                      "for %s\n", event);
1055                 return NULL;
1056         }
1057
1058         ast_str_set(&buf, 0, "Event: %s\r\n", event);
1059         if (!ast_strlen_zero(ami->action_id)) {
1060                 ast_str_append(&buf, 0, "ActionID: %s\r\n", ami->action_id);
1061         }
1062         return buf;
1063 }
1064
1065 static void sip_sorcery_object_ami_set_type_name(const void *obj, struct ast_str **buf)
1066 {
1067         ast_str_append(buf, 0, "ObjectType: %s\r\n",
1068                        ast_sorcery_object_get_type(obj));
1069         ast_str_append(buf, 0, "ObjectName: %s\r\n",
1070                        ast_sorcery_object_get_id(obj));
1071 }
1072
1073 int ast_sip_sorcery_object_to_ami(const void *obj, struct ast_str **buf)
1074 {
1075         RAII_VAR(struct ast_variable *, objset, ast_sorcery_objectset_create2(
1076                          ast_sip_get_sorcery(), obj, AST_HANDLER_ONLY_STRING), ast_variables_destroy);
1077         struct ast_variable *i;
1078
1079         if (!objset) {
1080                 return -1;
1081         }
1082
1083         sip_sorcery_object_ami_set_type_name(obj, buf);
1084
1085         for (i = objset; i; i = i->next) {
1086                 RAII_VAR(char *, camel, ast_to_camel_case(i->name), ast_free);
1087                 ast_str_append(buf, 0, "%s: %s\r\n", camel, i->value);
1088         }
1089
1090         return 0;
1091 }
1092
1093 static int sip_endpoints_aors_ami(void *obj, void *arg, int flags)
1094 {
1095         struct ast_sip_aor *aor = obj;
1096         struct ast_str **buf = arg;
1097
1098         ast_str_append(buf, 0, "Contacts: ");
1099         ast_sip_for_each_contact(aor, ast_sip_contact_to_str, arg);
1100         ast_str_append(buf, 0, "\r\n");
1101
1102         return 0;
1103 }
1104
1105 static int sip_endpoint_to_ami(const struct ast_sip_endpoint *endpoint,
1106                                struct ast_str **buf)
1107 {
1108         if (ast_sip_sorcery_object_to_ami(endpoint, buf)) {
1109                 return -1;
1110         }
1111
1112         ast_str_append(buf, 0, "DeviceState: %s\r\n",
1113                        ast_sip_get_device_state(endpoint));
1114
1115         ast_str_append(buf, 0, "ActiveChannels: ");
1116         active_channels_to_str(endpoint, buf);
1117         ast_str_append(buf, 0, "\r\n");
1118
1119         return 0;
1120 }
1121
1122 static int format_ami_endpoint(const struct ast_sip_endpoint *endpoint,
1123                                struct ast_sip_ami *ami)
1124 {
1125         RAII_VAR(struct ast_str *, buf,
1126                  ast_sip_create_ami_event("EndpointDetail", ami), ast_free);
1127
1128         if (!buf) {
1129                 return -1;
1130         }
1131
1132         sip_endpoint_to_ami(endpoint, &buf);
1133         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1134         return 0;
1135 }
1136
1137 #define AMI_SHOW_ENDPOINTS "PJSIPShowEndpoints"
1138 #define AMI_SHOW_ENDPOINT "PJSIPShowEndpoint"
1139
1140 static int ami_show_endpoint(struct mansession *s, const struct message *m)
1141 {
1142         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"),
1143                 .count = 0, };
1144         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1145         const char *endpoint_name = astman_get_header(m, "Endpoint");
1146         int count = 0;
1147
1148         if (ast_strlen_zero(endpoint_name)) {
1149                 astman_send_error_va(s, m, "%s requires an endpoint name\n",
1150                         AMI_SHOW_ENDPOINT);
1151                 return 0;
1152         }
1153
1154         if (!strncasecmp(endpoint_name, "pjsip/", 6)) {
1155                 endpoint_name += 6;
1156         }
1157
1158         if (!(endpoint = ast_sorcery_retrieve_by_id(
1159                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1160                 astman_send_error_va(s, m, "Unable to retrieve endpoint %s\n",
1161                         endpoint_name);
1162                 return -1;
1163         }
1164
1165         astman_send_listack(s, m, "Following are Events for each object associated with the the Endpoint",
1166                 "start");
1167
1168         /* the endpoint detail needs to always come first so apply as such */
1169         if (format_ami_endpoint(endpoint, &ami) ||
1170             ast_sip_format_endpoint_ami(endpoint, &ami, &count)) {
1171                 astman_send_error_va(s, m, "Unable to format endpoint %s\n",
1172                         endpoint_name);
1173         }
1174
1175         astman_send_list_complete_start(s, m, "EndpointDetailComplete", ami.count + 1);
1176         astman_send_list_complete_end(s);
1177
1178         return 0;
1179 }
1180
1181 static int format_str_append_auth(const struct ast_sip_auth_vector *auths,
1182                                   struct ast_str **buf)
1183 {
1184         char *str = NULL;
1185         if (ast_sip_auths_to_str(auths, &str)) {
1186                 return -1;
1187         }
1188         ast_str_append(buf, 0, "%s", str ? str : "");
1189         ast_free(str);
1190         return 0;
1191 }
1192
1193 static int format_ami_endpoints(void *obj, void *arg, int flags)
1194 {
1195
1196         struct ast_sip_endpoint *endpoint = obj;
1197         struct ast_sip_ami *ami = arg;
1198         RAII_VAR(struct ast_str *, buf,
1199                  ast_sip_create_ami_event("EndpointList", ami), ast_free);
1200
1201         if (!buf) {
1202                 return -1;
1203         }
1204
1205         sip_sorcery_object_ami_set_type_name(endpoint, &buf);
1206         ast_str_append(&buf, 0, "Transport: %s\r\n",
1207                        endpoint->transport);
1208         ast_str_append(&buf, 0, "Aor: %s\r\n",
1209                        endpoint->aors);
1210
1211         ast_str_append(&buf, 0, "Auths: ");
1212         format_str_append_auth(&endpoint->inbound_auths, &buf);
1213         ast_str_append(&buf, 0, "\r\n");
1214
1215         ast_str_append(&buf, 0, "OutboundAuths: ");
1216         format_str_append_auth(&endpoint->outbound_auths, &buf);
1217         ast_str_append(&buf, 0, "\r\n");
1218
1219         ast_sip_for_each_aor(endpoint->aors,
1220                              sip_endpoints_aors_ami, &buf);
1221
1222         ast_str_append(&buf, 0, "DeviceState: %s\r\n",
1223                        ast_sip_get_device_state(endpoint));
1224
1225         ast_str_append(&buf, 0, "ActiveChannels: ");
1226         active_channels_to_str(endpoint, &buf);
1227         ast_str_append(&buf, 0, "\r\n");
1228
1229         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1230         return 0;
1231 }
1232
1233 static int ami_show_endpoints(struct mansession *s, const struct message *m)
1234 {
1235         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
1236         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
1237         int num;
1238
1239         endpoints = ast_sip_get_endpoints();
1240         if (!endpoints) {
1241                 return -1;
1242         }
1243
1244         if (!(num = ao2_container_count(endpoints))) {
1245                 astman_send_error(s, m, "No endpoints found\n");
1246                 return 0;
1247         }
1248
1249         astman_send_listack(s, m, "A listing of Endpoints follows, presented as EndpointList events",
1250                 "start");
1251
1252         ao2_callback(endpoints, OBJ_NODATA, format_ami_endpoints, &ami);
1253
1254         astman_send_list_complete_start(s, m, "EndpointListComplete", num);
1255         astman_send_list_complete_end(s);
1256         return 0;
1257 }
1258
1259 static struct ao2_container *cli_endpoint_get_container(void)
1260 {
1261         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
1262         struct ao2_container *s_container;
1263
1264         container = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint",
1265                 AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1266         if (!container) {
1267                 return NULL;
1268         }
1269
1270         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
1271                 (void *)ast_sorcery_object_id_sort, (void *)ast_sorcery_object_id_compare);
1272         if (!s_container) {
1273                 return NULL;
1274         }
1275
1276         if (ao2_container_dup(s_container, container, 0)) {
1277                 ao2_ref(s_container, -1);
1278                 return NULL;
1279         }
1280
1281         return s_container;
1282 }
1283
1284 static int cli_channel_populate_container(void *obj, void *arg, int flags)
1285 {
1286         struct ast_channel_snapshot *snapshot = obj;
1287
1288         ao2_link(arg, snapshot);
1289
1290         return 0;
1291 }
1292
1293 static int cli_channel_iterate(void *container, ao2_callback_fn callback, void *args)
1294 {
1295         const struct ast_sip_endpoint *endpoint = container;
1296
1297         ast_sip_for_each_channel(endpoint, callback, args);
1298
1299         return 0;
1300 }
1301
1302 static int cli_channel_sort(const void *obj, const void *arg, int flags)
1303 {
1304         const struct ast_channel_snapshot *left_obj = obj;
1305         const struct ast_channel_snapshot *right_obj = arg;
1306         const char *right_key = arg;
1307         int cmp;
1308
1309         switch (flags & OBJ_SEARCH_MASK) {
1310         case OBJ_SEARCH_OBJECT:
1311                 right_key = right_obj->name;
1312                 /* Fall through */
1313         case OBJ_SEARCH_KEY:
1314                 cmp = strcmp(left_obj->name, right_key);
1315                 break;
1316         case OBJ_SEARCH_PARTIAL_KEY:
1317                 cmp = strncmp(left_obj->name, right_key, strlen(right_key));
1318                 break;
1319         default:
1320                 cmp = 0;
1321                 break;
1322         }
1323
1324         return cmp;
1325 }
1326
1327 static int cli_channel_compare(void *obj, void *arg, int flags)
1328 {
1329         const struct ast_channel_snapshot *left_obj = obj;
1330         const struct ast_channel_snapshot *right_obj = arg;
1331         const char *right_key = arg;
1332         int cmp = 0;
1333
1334         switch (flags & OBJ_SEARCH_MASK) {
1335         case OBJ_SEARCH_OBJECT:
1336                 right_key = right_obj->name;
1337                 /* Fall through */
1338         case OBJ_SEARCH_KEY:
1339                 if (strcmp(left_obj->name, right_key) == 0) {
1340                         cmp = CMP_MATCH | CMP_STOP;
1341                 }
1342                 break;
1343         case OBJ_SEARCH_PARTIAL_KEY:
1344                 if (strncmp(left_obj->name, right_key, strlen(right_key)) == 0) {
1345                         cmp = CMP_MATCH;
1346                 }
1347                 break;
1348         default:
1349                 cmp = 0;
1350                 break;
1351         }
1352
1353         return cmp;
1354 }
1355
1356 static int cli_channel_hash(const void *obj, int flags)
1357 {
1358         const struct ast_channel_snapshot *snapshot = obj;
1359
1360         if (flags & OBJ_SEARCH_OBJECT) {
1361                 return ast_str_hash(snapshot->name);
1362         } else if (flags & OBJ_SEARCH_KEY) {
1363                 return ast_str_hash(obj);
1364         }
1365
1366         return -1;
1367 }
1368
1369 static int cli_endpoint_gather_channels(void *obj, void *arg, int flags)
1370 {
1371         struct ast_sip_endpoint *endpoint = obj;
1372         struct ao2_container *channels = arg;
1373
1374         ast_sip_for_each_channel(endpoint, cli_channel_populate_container, channels);
1375
1376         return 0;
1377 }
1378
1379 static struct ao2_container *cli_channel_get_container(void)
1380 {
1381         RAII_VAR(struct ao2_container *, parent_container, NULL, ao2_cleanup);
1382         struct ao2_container *child_container;
1383
1384         parent_container = cli_endpoint_get_container();
1385         if (!parent_container) {
1386                 return NULL;
1387         }
1388         child_container = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_NOLOCK, 0, 17,
1389                 cli_channel_hash, cli_channel_sort, cli_channel_compare);
1390         if (!child_container) {
1391                 return NULL;
1392         }
1393
1394         ao2_callback(parent_container, OBJ_NODATA, cli_endpoint_gather_channels, child_container);
1395
1396         return child_container;
1397 }
1398
1399 static const char *cli_channel_get_id(const void *obj)
1400 {
1401         const struct ast_channel_snapshot *snapshot = obj;
1402
1403         return snapshot->name;
1404 }
1405
1406 static void *cli_channel_retrieve_by_id(const char *id)
1407 {
1408         RAII_VAR(struct ao2_container *, container, cli_channel_get_container(), ao2_cleanup);
1409
1410         return ao2_find(container, id, OBJ_KEY | OBJ_NOLOCK);
1411 }
1412
1413 static int cli_channel_print_header(void *obj, void *arg, int flags)
1414 {
1415         struct ast_sip_cli_context *context = arg;
1416         int indent = CLI_INDENT_TO_SPACES(context->indent_level);
1417         int filler = CLI_LAST_TABSTOP - indent - 13;
1418
1419         ast_assert(context->output_buffer != NULL);
1420
1421         ast_str_append(&context->output_buffer, 0,
1422                 "%*s:  <ChannelId%*.*s>  <State.....>  <Time(sec)>\n",
1423                 indent, "Channel", filler, filler, CLI_HEADER_FILLER);
1424         if (context->recurse) {
1425                 context->indent_level++;
1426                 indent = CLI_INDENT_TO_SPACES(context->indent_level);
1427                 filler = CLI_LAST_TABSTOP - indent - 38;
1428                 ast_str_append(&context->output_buffer, 0,
1429                         "%*s: <DialedExten%*.*s>  CLCID: <ConnectedLineCID.......>\n",
1430                         indent, "Exten", filler, filler, CLI_HEADER_FILLER);
1431                 context->indent_level--;
1432         }
1433
1434         return 0;
1435 }
1436
1437 static int cli_channel_print_body(void *obj, void *arg, int flags)
1438 {
1439         const struct ast_channel_snapshot *snapshot = obj;
1440         struct ast_sip_cli_context *context = arg;
1441         struct timeval current_time;
1442         char *print_name = NULL;
1443         int print_name_len;
1444         int indent;
1445         int flexwidth;
1446
1447         ast_assert(context->output_buffer != NULL);
1448
1449         gettimeofday(&current_time, NULL);
1450
1451         print_name_len = strlen(snapshot->name) + strlen(snapshot->appl) + 2;
1452         if (!(print_name = alloca(print_name_len))) {
1453                 return -1;
1454         }
1455
1456         snprintf(print_name, print_name_len, "%s/%s", snapshot->name, snapshot->appl);
1457
1458         indent = CLI_INDENT_TO_SPACES(context->indent_level);
1459         flexwidth = CLI_LAST_TABSTOP - indent;
1460
1461         ast_str_append(&context->output_buffer, 0, "%*s: %-*.*s %-12.12s  %11ld\n",
1462                 CLI_INDENT_TO_SPACES(context->indent_level), "Channel",
1463                 flexwidth, flexwidth,
1464                 print_name,
1465                 ast_state2str(snapshot->state),
1466                 current_time.tv_sec - snapshot->creationtime.tv_sec);
1467
1468         if (context->recurse) {
1469                 context->indent_level++;
1470                 indent = CLI_INDENT_TO_SPACES(context->indent_level);
1471                 flexwidth = CLI_LAST_TABSTOP - indent - 25;
1472
1473                 ast_str_append(&context->output_buffer, 0,
1474                         "%*s: %-*.*s  CLCID: \"%s\" <%s>\n",
1475                         indent, "Exten",
1476                         flexwidth, flexwidth,
1477                         snapshot->exten,
1478                         snapshot->connected_name,
1479                         snapshot->connected_number
1480                         );
1481                 context->indent_level--;
1482                 if (context->indent_level == 0) {
1483                         ast_str_append(&context->output_buffer, 0, "\n");
1484                 }
1485         }
1486
1487         return 0;
1488 }
1489
1490 static int cli_endpoint_iterate(void *obj, ao2_callback_fn callback, void *args)
1491 {
1492         ao2_callback(obj, OBJ_NODATA, callback, args);
1493
1494         return 0;
1495 }
1496
1497 static void *cli_endpoint_retrieve_by_id(const char *id)
1498 {
1499         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", id);
1500 }
1501
1502 static void cli_endpoint_print_child_header(char *type, struct ast_sip_cli_context *context)
1503 {
1504         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1505
1506         formatter_entry = ast_sip_lookup_cli_formatter(type);
1507         if (formatter_entry) {
1508                 formatter_entry->print_header(NULL, context, 0);
1509         }
1510 }
1511
1512 static int cli_endpoint_print_header(void *obj, void *arg, int flags)
1513 {
1514         struct ast_sip_cli_context *context = arg;
1515
1516         ast_assert(context->output_buffer != NULL);
1517
1518         ast_str_append(&context->output_buffer, 0,
1519                         " Endpoint:  <Endpoint/CID.....................................>  <State.....>  <Channels.>\n");
1520
1521         if (context->recurse) {
1522                 context->indent_level++;
1523                 cli_endpoint_print_child_header("auth", context);
1524                 cli_endpoint_print_child_header("aor", context);
1525                 cli_endpoint_print_child_header("transport", context);
1526                 cli_endpoint_print_child_header("identify", context);
1527                 cli_endpoint_print_child_header("channel", context);
1528                 context->indent_level--;
1529         }
1530
1531         return 0;
1532 }
1533
1534 static void cli_endpoint_print_child_body(char *type, const void *obj, struct ast_sip_cli_context *context)
1535 {
1536         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1537
1538         formatter_entry = ast_sip_lookup_cli_formatter(type);
1539         if (formatter_entry) {
1540                 formatter_entry->iterate((void *)obj, formatter_entry->print_body, context);
1541         }
1542 }
1543
1544 static int cli_endpoint_print_body(void *obj, void *arg, int flags)
1545 {
1546         struct ast_sip_endpoint *endpoint = obj;
1547         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1548         struct ast_sip_cli_context *context = arg;
1549         const char *id = ast_sorcery_object_get_id(endpoint);
1550         char *print_name = NULL;
1551         int print_name_len;
1552         char *number = S_COR(endpoint->id.self.number.valid,
1553                 endpoint->id.self.number.str, NULL);
1554         int indent;
1555         int flexwidth;
1556
1557         ast_assert(context->output_buffer != NULL);
1558
1559         if (number) {
1560                 print_name_len = strlen(id) + strlen(number) + 2;
1561                 if (!(print_name = alloca(print_name_len))) {
1562                         return -1;
1563                 }
1564                 snprintf(print_name, print_name_len, "%s/%s", id, number);
1565         }
1566
1567         indent = CLI_INDENT_TO_SPACES(context->indent_level);
1568         flexwidth = CLI_LAST_TABSTOP - indent - 2;
1569
1570         ast_str_append(&context->output_buffer, 0, "%*s:  %-*.*s  %-12.12s  %d of %.0f\n",
1571                 indent, "Endpoint",
1572                 flexwidth, flexwidth, print_name ? print_name : id,
1573                 ast_sip_get_device_state(endpoint),
1574                 endpoint_snapshot->num_channels,
1575                 (double) endpoint->devicestate_busy_at ? endpoint->devicestate_busy_at :
1576                                                                                                                 INFINITY
1577                                                                                                                 );
1578
1579         if (context->recurse) {
1580                 context->indent_level++;
1581
1582                 context->auth_direction = "Out";
1583                 cli_endpoint_print_child_body("auth", &endpoint->outbound_auths, context);
1584                 context->auth_direction = "In";
1585                 cli_endpoint_print_child_body("auth", &endpoint->inbound_auths, context);
1586
1587                 cli_endpoint_print_child_body("aor", endpoint->aors, context);
1588                 cli_endpoint_print_child_body("transport", endpoint, context);
1589                 cli_endpoint_print_child_body("identify", endpoint, context);
1590                 cli_endpoint_print_child_body("channel", endpoint, context);
1591
1592                 context->indent_level--;
1593
1594                 if (context->indent_level == 0) {
1595                         ast_str_append(&context->output_buffer, 0, "\n");
1596                 }
1597         }
1598
1599         if (context->show_details || (context->show_details_only_level_0 && context->indent_level == 0)) {
1600                 ast_str_append(&context->output_buffer, 0, "\n");
1601                 ast_sip_cli_print_sorcery_objectset(endpoint, context, 0);
1602         }
1603
1604         return 0;
1605 }
1606
1607 static struct ast_cli_entry cli_commands[] = {
1608         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "List PJSIP Channels",
1609                 .command = "pjsip list channels",
1610                 .usage = "Usage: pjsip list channels\n"
1611                                  "       List the active PJSIP channels\n"),
1612         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Channels",
1613                 .command = "pjsip show channels",
1614                 .usage = "Usage: pjsip show channels\n"
1615                                  "       List(detailed) the active PJSIP channels\n"),
1616         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Channel",
1617                 .command = "pjsip show channel",
1618                 .usage = "Usage: pjsip show channel\n"
1619                                  "       List(detailed) the active PJSIP channel\n"),
1620
1621         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "List PJSIP Endpoints",
1622                 .command = "pjsip list endpoints",
1623                 .usage = "Usage: pjsip list endpoints\n"
1624                                  "       List the configured PJSIP endpoints\n"),
1625         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoints",
1626                 .command = "pjsip show endpoints",
1627                 .usage = "Usage: pjsip show endpoints\n"
1628                                  "       List(detailed) the configured PJSIP endpoints\n"),
1629         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoint",
1630                 .command = "pjsip show endpoint",
1631                 .usage = "Usage: pjsip show endpoint <id>\n"
1632                                  "       Show the configured PJSIP endpoint\n"),
1633 };
1634
1635 struct ast_sip_cli_formatter_entry *channel_formatter;
1636 struct ast_sip_cli_formatter_entry *endpoint_formatter;
1637
1638 int ast_res_pjsip_initialize_configuration(const struct ast_module_info *ast_module_info)
1639 {
1640         if (ast_manager_register_xml(AMI_SHOW_ENDPOINTS, EVENT_FLAG_SYSTEM, ami_show_endpoints) ||
1641             ast_manager_register_xml(AMI_SHOW_ENDPOINT, EVENT_FLAG_SYSTEM, ami_show_endpoint)) {
1642                 return -1;
1643         }
1644
1645         if (!(persistent_endpoints = ao2_container_alloc(PERSISTENT_BUCKETS, persistent_endpoint_hash, persistent_endpoint_cmp))) {
1646                 return -1;
1647         }
1648
1649         if (!(sip_sorcery = ast_sorcery_open())) {
1650                 ast_log(LOG_ERROR, "Failed to open SIP sorcery failed to open\n");
1651                 return -1;
1652         }
1653
1654         ast_sip_initialize_cli();
1655
1656         if (ast_sip_initialize_sorcery_auth()) {
1657                 ast_log(LOG_ERROR, "Failed to register SIP authentication support\n");
1658                 ast_sorcery_unref(sip_sorcery);
1659                 sip_sorcery = NULL;
1660                 return -1;
1661         }
1662
1663         ast_sorcery_apply_default(sip_sorcery, "endpoint", "config", "pjsip.conf,criteria=type=endpoint");
1664         ast_sorcery_apply_default(sip_sorcery, "nat_hook", "memory", NULL);
1665
1666         if (ast_sorcery_object_register(sip_sorcery, "endpoint", ast_sip_endpoint_alloc, NULL, sip_endpoint_apply_handler)) {
1667                 ast_log(LOG_ERROR, "Failed to register SIP endpoint object with sorcery\n");
1668                 ast_sorcery_unref(sip_sorcery);
1669                 sip_sorcery = NULL;
1670                 return -1;
1671         }
1672
1673         ast_sorcery_internal_object_register(sip_sorcery, "nat_hook", sip_nat_hook_alloc, NULL, NULL);
1674
1675         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "type", "", OPT_NOOP_T, 0, 0);
1676         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "context", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, context));
1677         ast_sorcery_object_field_register_alias(sip_sorcery, "endpoint", "disallow", "", OPT_CODEC_T, 0, FLDSET(struct ast_sip_endpoint, media.codecs));
1678         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow", "", OPT_CODEC_T, 1, FLDSET(struct ast_sip_endpoint, media.codecs));
1679         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtmf_mode", "rfc4733", dtmf_handler, dtmf_to_str, NULL, 0, 0);
1680         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ipv6));
1681         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_symmetric", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.symmetric));
1682         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "ice_support", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ice_support));
1683         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_ptime", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_ptime));
1684         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_rport", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.force_rport));
1685         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rewrite_contact", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.rewrite_contact));
1686         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, transport));
1687         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, outbound_proxy));
1688         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_suggest", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, mohsuggest));
1689         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "100rel", "yes", prack_handler, prack_to_str, NULL, 0, 0);
1690         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "timers", "yes", timers_handler, timers_to_str, NULL, 0, 0);
1691         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));
1692         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));
1693         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "auth", "", inbound_auth_handler, inbound_auths_to_str, NULL, 0, 0);
1694         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, NULL, 0, 0);
1695         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aors", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, aors));
1696         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_address", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.address));
1697         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "identify_by", "username", ident_handler, ident_to_str, NULL, 0, 0);
1698         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "direct_media", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.direct_media.enabled));
1699         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);
1700         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);
1701         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);
1702         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));
1703         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid", "", caller_id_handler, caller_id_to_str, NULL, 0, 0);
1704         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);
1705         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_tag", "", caller_id_tag_handler, caller_id_tag_to_str, NULL, 0, 0);
1706         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_inbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_inbound));
1707         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_outbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_outbound));
1708         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_pai", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_pai));
1709         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_rpid", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_rpid));
1710         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_diversion", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_diversion));
1711         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mailboxes", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.mailboxes));
1712         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aggregate_mwi", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.aggregate));
1713         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "media_encryption", "no", media_encryption_handler, media_encryption_to_str, NULL, 0, 0);
1714         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_avpf", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_avpf));
1715         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_avp", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.force_avp));
1716         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));
1717         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "one_touch_recording", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, info.recording.enabled));
1718         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "inband_progress", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, inband_progress));
1719         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "call_group", "", group_handler, callgroup_to_str, NULL, 0, 0);
1720         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "pickup_group", "", group_handler, pickupgroup_to_str, NULL, 0, 0);
1721         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_call_group", "", named_groups_handler, named_callgroups_to_str, NULL, 0, 0);
1722         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_pickup_group", "", named_groups_handler, named_pickupgroups_to_str, NULL, 0, 0);
1723         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));
1724         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.enabled));
1725         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "t38_udptl_ec", "none", t38udptl_ec_handler, t38udptl_ec_to_str, NULL, 0, 0);
1726         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_maxdatagram", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.t38.maxdatagram));
1727         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, faxdetect));
1728         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_nat", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.nat));
1729         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.ipv6));
1730         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tone_zone", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, zone));
1731         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "language", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, language));
1732         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_on_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.onfeature));
1733         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_off_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.offfeature));
1734         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_transfer", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allowtransfer));
1735         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "user_eq_phone", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, usereqphone));
1736         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_passthrough", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, moh_passthrough));
1737         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_owner", "-", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpowner));
1738         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_session", "Asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpsession));
1739         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_audio", "0", tos_handler, tos_audio_to_str, NULL, 0, 0);
1740         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_video", "0", tos_handler, tos_video_to_str, NULL, 0, 0);
1741         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_audio", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_audio));
1742         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_video", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_video));
1743         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_subscribe", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.allow));
1744         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sub_min_expiry", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, subscription.minexpiry));
1745         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromuser));
1746         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_domain", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromdomain));
1747         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.fromuser));
1748         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_engine", "asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.rtp.engine));
1749         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_verify", "no", dtls_handler, dtlsverify_to_str, NULL, 0, 0);
1750         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_rekey", "0", dtls_handler, dtlsrekey_to_str, NULL, 0, 0);
1751         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cert_file", "", dtls_handler, dtlscertfile_to_str, NULL, 0, 0);
1752         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_private_key", "", dtls_handler, dtlsprivatekey_to_str, NULL, 0, 0);
1753         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cipher", "", dtls_handler, dtlscipher_to_str, NULL, 0, 0);
1754         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_file", "", dtls_handler, dtlscafile_to_str, NULL, 0, 0);
1755         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_path", "", dtls_handler, dtlscapath_to_str, NULL, 0, 0);
1756         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_setup", "", dtls_handler, dtlssetup_to_str, NULL, 0, 0);
1757         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_fingerprint", "", dtls_handler, dtlsfingerprint_to_str, NULL, 0, 0);
1758         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));
1759         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));
1760         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "redirect_method", "user", redirect_handler, NULL, NULL, 0, 0);
1761         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "set_var", "", set_var_handler, set_var_to_str, set_var_to_vl, 0, 0);
1762         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "message_context", "", OPT_STRINGFIELD_T, 1, STRFLDSET(struct ast_sip_endpoint, message_context));
1763         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "accountcode", "", OPT_STRINGFIELD_T, 1, STRFLDSET(struct ast_sip_endpoint, accountcode));
1764
1765         if (ast_sip_initialize_sorcery_transport()) {
1766                 ast_log(LOG_ERROR, "Failed to register SIP transport support with sorcery\n");
1767                 ast_sorcery_unref(sip_sorcery);
1768                 sip_sorcery = NULL;
1769                 return -1;
1770         }
1771
1772         if (ast_sip_initialize_sorcery_location()) {
1773                 ast_log(LOG_ERROR, "Failed to register SIP location support with sorcery\n");
1774                 ast_sorcery_unref(sip_sorcery);
1775                 sip_sorcery = NULL;
1776                 return -1;
1777         }
1778
1779         if (ast_sip_initialize_sorcery_qualify()) {
1780                 ast_log(LOG_ERROR, "Failed to register SIP qualify support with sorcery\n");
1781                 ast_sorcery_unref(sip_sorcery);
1782                 sip_sorcery = NULL;
1783                 return -1;
1784         }
1785
1786         ast_sorcery_observer_add(sip_sorcery, "contact", &state_contact_observer);
1787
1788         if (ast_sip_initialize_sorcery_domain_alias()) {
1789                 ast_log(LOG_ERROR, "Failed to register SIP domain aliases support with sorcery\n");
1790                 ast_sorcery_unref(sip_sorcery);
1791                 sip_sorcery = NULL;
1792                 return -1;
1793         }
1794
1795         if (ast_sip_initialize_sorcery_global()) {
1796                 ast_log(LOG_ERROR, "Failed to register SIP Global support\n");
1797                 ast_sorcery_unref(sip_sorcery);
1798                 sip_sorcery = NULL;
1799                 return -1;
1800         }
1801
1802         channel_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
1803         if (!channel_formatter) {
1804                 ast_log(LOG_ERROR, "Unable to allocate memory for channel_formatter\n");
1805                 ast_sorcery_unref(sip_sorcery);
1806                 sip_sorcery = NULL;
1807                 return -1;
1808         }
1809         channel_formatter->name = "channel";
1810         channel_formatter->print_header = cli_channel_print_header;
1811         channel_formatter->print_body = cli_channel_print_body;
1812         channel_formatter->get_container = cli_channel_get_container;
1813         channel_formatter->iterate = cli_channel_iterate;
1814         channel_formatter->retrieve_by_id = cli_channel_retrieve_by_id;
1815         channel_formatter->get_id = cli_channel_get_id;
1816
1817         endpoint_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
1818         if (!endpoint_formatter) {
1819                 ast_log(LOG_ERROR, "Unable to allocate memory for endpoint_formatter\n");
1820                 ast_sorcery_unref(sip_sorcery);
1821                 sip_sorcery = NULL;
1822                 return -1;
1823         }
1824         endpoint_formatter->name = "endpoint";
1825         endpoint_formatter->print_header = cli_endpoint_print_header;
1826         endpoint_formatter->print_body = cli_endpoint_print_body;
1827         endpoint_formatter->get_container = cli_endpoint_get_container;
1828         endpoint_formatter->iterate = cli_endpoint_iterate;
1829         endpoint_formatter->retrieve_by_id = cli_endpoint_retrieve_by_id;
1830         endpoint_formatter->get_id = ast_sorcery_object_get_id;
1831
1832         ast_sip_register_cli_formatter(channel_formatter);
1833         ast_sip_register_cli_formatter(endpoint_formatter);
1834         ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
1835
1836         ast_sorcery_load(sip_sorcery);
1837
1838         return 0;
1839 }
1840
1841 void ast_res_pjsip_destroy_configuration(void)
1842 {
1843         ast_sip_destroy_sorcery_location();
1844         ast_sip_destroy_sorcery_auth();
1845         ast_sip_destroy_sorcery_transport();
1846         ast_manager_unregister(AMI_SHOW_ENDPOINT);
1847         ast_manager_unregister(AMI_SHOW_ENDPOINTS);
1848         ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
1849         ast_sip_unregister_cli_formatter(endpoint_formatter);
1850         ast_sip_unregister_cli_formatter(channel_formatter);
1851         ast_sorcery_unref(sip_sorcery);
1852 }
1853
1854 int ast_res_pjsip_reload_configuration(void)
1855 {
1856         if (sip_sorcery) {
1857                 ast_sorcery_reload(sip_sorcery);
1858         }
1859         return 0;
1860 }
1861
1862 static void subscription_configuration_destroy(struct ast_sip_endpoint_subscription_configuration *subscription)
1863 {
1864         ast_string_field_free_memory(&subscription->mwi);
1865 }
1866
1867 static void info_configuration_destroy(struct ast_sip_endpoint_info_configuration *info)
1868 {
1869         ast_string_field_free_memory(&info->recording);
1870 }
1871
1872 static void media_configuration_destroy(struct ast_sip_endpoint_media_configuration *media)
1873 {
1874         ast_string_field_free_memory(&media->rtp);
1875         ast_string_field_free_memory(media);
1876 }
1877
1878 static void endpoint_destructor(void* obj)
1879 {
1880         struct ast_sip_endpoint *endpoint = obj;
1881
1882         ast_string_field_free_memory(endpoint);
1883
1884         ao2_ref(endpoint->media.codecs, -1);
1885         subscription_configuration_destroy(&endpoint->subscription);
1886         info_configuration_destroy(&endpoint->info);
1887         media_configuration_destroy(&endpoint->media);
1888         ast_sip_auth_vector_destroy(&endpoint->inbound_auths);
1889         ast_sip_auth_vector_destroy(&endpoint->outbound_auths);
1890         ast_party_id_free(&endpoint->id.self);
1891         endpoint->pickup.named_callgroups = ast_unref_namedgroups(endpoint->pickup.named_callgroups);
1892         endpoint->pickup.named_pickupgroups = ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
1893         ao2_cleanup(endpoint->persistent);
1894         ast_variables_destroy(endpoint->channel_vars);
1895 }
1896
1897 static int init_subscription_configuration(struct ast_sip_endpoint_subscription_configuration *subscription)
1898 {
1899         return ast_string_field_init(&subscription->mwi, 64);
1900 }
1901
1902 static int init_info_configuration(struct ast_sip_endpoint_info_configuration *info)
1903 {
1904         return ast_string_field_init(&info->recording, 32);
1905 }
1906
1907 static int init_media_configuration(struct ast_sip_endpoint_media_configuration *media)
1908 {
1909         return ast_string_field_init(media, 64) || ast_string_field_init(&media->rtp, 32);
1910 }
1911
1912 void *ast_sip_endpoint_alloc(const char *name)
1913 {
1914         struct ast_sip_endpoint *endpoint = ast_sorcery_generic_alloc(sizeof(*endpoint), endpoint_destructor);
1915         if (!endpoint) {
1916                 return NULL;
1917         }
1918         if (ast_string_field_init(endpoint, 64)) {
1919                 ao2_cleanup(endpoint);
1920                 return NULL;
1921         }
1922         if (!(endpoint->media.codecs = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1923                 ao2_cleanup(endpoint);
1924                 return NULL;
1925         }
1926         if (init_subscription_configuration(&endpoint->subscription)) {
1927                 ao2_cleanup(endpoint);
1928                 return NULL;
1929         }
1930         if (init_info_configuration(&endpoint->info)) {
1931                 ao2_cleanup(endpoint);
1932                 return NULL;
1933         }
1934         if (init_media_configuration(&endpoint->media)) {
1935                 ao2_cleanup(endpoint);
1936                 return NULL;
1937         }
1938         ast_party_id_init(&endpoint->id.self);
1939         return endpoint;
1940 }
1941
1942 struct ao2_container *ast_sip_get_endpoints(void)
1943 {
1944         struct ao2_container *endpoints;
1945
1946         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1947
1948         return endpoints;
1949 }
1950
1951 struct ast_sip_endpoint *ast_sip_default_outbound_endpoint(void)
1952 {
1953         RAII_VAR(char *, name, ast_sip_global_default_outbound_endpoint(), ast_free);
1954         return ast_strlen_zero(name) ? NULL : ast_sorcery_retrieve_by_id(
1955                 sip_sorcery, "endpoint", name);
1956 }
1957
1958 int ast_sip_retrieve_auths(const struct ast_sip_auth_vector *auths, struct ast_sip_auth **out)
1959 {
1960         int i;
1961
1962         for (i = 0; i < AST_VECTOR_SIZE(auths); ++i) {
1963                 /* Using AST_VECTOR_GET is safe since the vector is immutable */
1964                 const char *name = AST_VECTOR_GET(auths, i);
1965                 out[i] = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), SIP_SORCERY_AUTH_TYPE, name);
1966                 if (!out[i]) {
1967                         ast_log(LOG_NOTICE, "Couldn't find auth '%s'. Cannot authenticate\n", name);
1968                         return -1;
1969                 }
1970         }
1971
1972         return 0;
1973 }
1974
1975 void ast_sip_cleanup_auths(struct ast_sip_auth *auths[], size_t num_auths)
1976 {
1977         int i;
1978         for (i = 0; i < num_auths; ++i) {
1979                 ao2_cleanup(auths[i]);
1980         }
1981 }
1982
1983 struct ast_sorcery *ast_sip_get_sorcery(void)
1984 {
1985         return sip_sorcery;
1986 }