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