res_pjsip: AMI commands and events.
[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/cli.h"
16 #include "asterisk/manager.h"
17 #include "asterisk/astobj2.h"
18 #include "asterisk/utils.h"
19 #include "asterisk/sorcery.h"
20 #include "asterisk/callerid.h"
21
22 /*! \brief Number of buckets for persistent endpoint information */
23 #define PERSISTENT_BUCKETS 53
24
25 /*! \brief Persistent endpoint information */
26 struct sip_persistent_endpoint {
27         /*! \brief Asterisk endpoint itself */
28         struct ast_endpoint *endpoint;
29         /*! \brief AORs that we should react to */
30         char *aors;
31 };
32
33 /*! \brief Container for persistent endpoint information */
34 static struct ao2_container *persistent_endpoints;
35
36 static struct ast_sorcery *sip_sorcery;
37
38 /*! \brief Hashing function for persistent endpoint information */
39 static int persistent_endpoint_hash(const void *obj, const int flags)
40 {
41         const struct sip_persistent_endpoint *persistent = obj;
42         const char *id = (flags & OBJ_KEY ? obj : ast_endpoint_get_resource(persistent->endpoint));
43
44         return ast_str_hash(id);
45 }
46
47 /*! \brief Comparison function for persistent endpoint information */
48 static int persistent_endpoint_cmp(void *obj, void *arg, int flags)
49 {
50         const struct sip_persistent_endpoint *persistent1 = obj;
51         const struct sip_persistent_endpoint *persistent2 = arg;
52         const char *id = (flags & OBJ_KEY ? arg : ast_endpoint_get_resource(persistent2->endpoint));
53
54         return !strcmp(ast_endpoint_get_resource(persistent1->endpoint), id) ? CMP_MATCH | CMP_STOP : 0;
55 }
56
57 /*! \brief Callback function for changing the state of an endpoint */
58 static int persistent_endpoint_update_state(void *obj, void *arg, int flags)
59 {
60         struct sip_persistent_endpoint *persistent = obj;
61         char *aor = arg;
62         RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
63         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
64
65         if (!ast_strlen_zero(aor) && !strstr(persistent->aors, aor)) {
66                 return 0;
67         }
68
69         if ((contact = ast_sip_location_retrieve_contact_from_aor_list(persistent->aors))) {
70                 ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_ONLINE);
71                 blob = ast_json_pack("{s: s}", "peer_status", "Reachable");
72         } else {
73                 ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_OFFLINE);
74                 blob = ast_json_pack("{s: s}", "peer_status", "Unreachable");
75         }
76
77         ast_endpoint_blob_publish(persistent->endpoint, ast_endpoint_state_type(), blob);
78
79         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_endpoint_get_resource(persistent->endpoint));
80
81         return 0;
82 }
83
84 /*! \brief Function called when stuff relating to a contact happens (created/deleted) */
85 static void persistent_endpoint_contact_observer(const void *object)
86 {
87         char *id = ast_strdupa(ast_sorcery_object_get_id(object)), *aor = NULL;
88
89         aor = strsep(&id, ";@");
90
91         ao2_callback(persistent_endpoints, OBJ_NODATA, persistent_endpoint_update_state, aor);
92 }
93
94 /*! \brief Observer for contacts so state can be updated on respective endpoints */
95 static struct ast_sorcery_observer state_contact_observer = {
96         .created = persistent_endpoint_contact_observer,
97         .deleted = persistent_endpoint_contact_observer,
98 };
99
100 static char *handle_cli_show_endpoints(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
101 {
102         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
103         struct ao2_iterator it_endpoints;
104         struct ast_sip_endpoint *endpoint;
105
106         switch (cmd) {
107         case CLI_INIT:
108                 e->command = "pjsip show endpoints";
109                 e->usage =
110                         "Usage: pjsip show endpoints\n"
111                         "       Show the registered PJSIP endpoints\n";
112                 return NULL;
113         case CLI_GENERATE:
114                 return NULL;
115         }
116
117         endpoints = ast_sip_get_endpoints();
118         if (!endpoints) {
119                 return CLI_FAILURE;
120         }
121
122         if (!ao2_container_count(endpoints)) {
123                 ast_cli(a->fd, "No endpoints found\n");
124                 return CLI_SUCCESS;
125         }
126
127         ast_cli(a->fd, "Endpoints:\n");
128         it_endpoints = ao2_iterator_init(endpoints, 0);
129         while ((endpoint = ao2_iterator_next(&it_endpoints))) {
130                 ast_cli(a->fd, "%s\n", ast_sorcery_object_get_id(endpoint));
131                 ao2_ref(endpoint, -1);
132         }
133         ao2_iterator_destroy(&it_endpoints);
134         return CLI_SUCCESS;
135 }
136
137 static int show_contact(void *obj, void *arg, int flags)
138 {
139         struct ast_sip_contact *contact = obj;
140         struct ast_cli_args *a = arg;
141         RAII_VAR(struct ast_sip_contact_status *, status, ast_sorcery_retrieve_by_id(
142                          ast_sip_get_sorcery(), CONTACT_STATUS,
143                          ast_sorcery_object_get_id(contact)), ao2_cleanup);
144
145         ast_cli(a->fd, "\tContact %s:\n", contact->uri);
146
147         if (!status) {
148                 ast_cli(a->fd, "\tStatus not found!\n");
149                 return 0;
150         }
151
152         ast_cli(a->fd, "\t\tavailable = %s\n", status->status ? "yes" : "no");
153
154         if (status->status) {
155                 ast_cli(a->fd, "\t\tRTT = %lld microseconds\n", (long long)status->rtt);
156         }
157
158         return 0;
159 }
160
161 static void show_endpoint(struct ast_sip_endpoint *endpoint, struct ast_cli_args *a)
162 {
163         char *aor_name, *aors;
164
165         if (ast_strlen_zero(endpoint->aors)) {
166                 return;
167         }
168
169         aors = ast_strdupa(endpoint->aors);
170
171         while ((aor_name = strsep(&aors, ","))) {
172                 RAII_VAR(struct ast_sip_aor *, aor,
173                          ast_sip_location_retrieve_aor(aor_name), ao2_cleanup);
174                 RAII_VAR(struct ao2_container *, contacts, NULL, ao2_cleanup);
175
176                 if (!aor || !(contacts = ast_sip_location_retrieve_aor_contacts(aor))) {
177                         continue;
178                 }
179
180                 ast_cli(a->fd, "AOR %s:\n", ast_sorcery_object_get_id(aor));
181                 ao2_callback(contacts, OBJ_NODATA, show_contact, a);
182         }
183
184         return;
185 }
186
187 static char *cli_show_endpoint(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
188 {
189         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
190         const char *endpoint_name;
191
192         switch (cmd) {
193         case CLI_INIT:
194                 e->command = "pjsip show endpoint";
195                 e->usage =
196                         "Usage: pjsip show endpoint <endpoint>\n"
197                         "       Show the given PJSIP endpoint.\n";
198                 return NULL;
199         case CLI_GENERATE:
200                 return NULL;
201         }
202
203         if (a->argc != 4) {
204                 return CLI_SHOWUSAGE;
205         }
206
207         endpoint_name = a->argv[3];
208
209         if (!(endpoint = ast_sorcery_retrieve_by_id(
210                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
211                 ast_cli(a->fd, "Unable to retrieve endpoint %s\n", endpoint_name);
212                 return CLI_FAILURE;
213         }
214
215         ast_cli(a->fd, "Endpoint %s:\n", endpoint_name);
216         show_endpoint(endpoint, a);
217
218         return CLI_SUCCESS;
219 }
220
221 static struct ast_cli_entry cli_commands[] = {
222         AST_CLI_DEFINE(handle_cli_show_endpoints, "Show PJSIP Endpoints"),
223         AST_CLI_DEFINE(cli_show_endpoint, "Show PJSIP Endpoint")
224 };
225
226 static int dtmf_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
227 {
228         struct ast_sip_endpoint *endpoint = obj;
229
230         if (!strcasecmp(var->value, "rfc4733")) {
231                 endpoint->dtmf = AST_SIP_DTMF_RFC_4733;
232         } else if (!strcasecmp(var->value, "inband")) {
233                 endpoint->dtmf = AST_SIP_DTMF_INBAND;
234         } else if (!strcasecmp(var->value, "info")) {
235                 endpoint->dtmf = AST_SIP_DTMF_INFO;
236         } else if (!strcasecmp(var->value, "none")) {
237                 endpoint->dtmf = AST_SIP_DTMF_NONE;
238         } else {
239                 return -1;
240         }
241
242         return 0;
243 }
244
245 static int dtmf_to_str(const void *obj, const intptr_t *args, char **buf)
246 {
247         const struct ast_sip_endpoint *endpoint = obj;
248
249         switch (endpoint->dtmf) {
250         case AST_SIP_DTMF_RFC_4733 :
251                 *buf = "rfc4733"; break;
252         case AST_SIP_DTMF_INBAND :
253                 *buf = "inband"; break;
254         case AST_SIP_DTMF_INFO :
255                 *buf = "info"; break;
256         default:
257                 *buf = "none";
258         }
259
260         *buf = ast_strdup(*buf);
261         return 0;
262 }
263
264 static int prack_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
265 {
266         struct ast_sip_endpoint *endpoint = obj;
267
268         if (ast_true(var->value)) {
269                 endpoint->extensions.flags |= PJSIP_INV_SUPPORT_100REL;
270         } else if (ast_false(var->value)) {
271                 endpoint->extensions.flags &= PJSIP_INV_SUPPORT_100REL;
272         } else if (!strcasecmp(var->value, "required")) {
273                 endpoint->extensions.flags |= PJSIP_INV_REQUIRE_100REL;
274         } else {
275                 return -1;
276         }
277
278         return 0;
279 }
280
281 static int prack_to_str(const void *obj, const intptr_t *args, char **buf)
282 {
283         const struct ast_sip_endpoint *endpoint = obj;
284
285         if (endpoint->extensions.flags & PJSIP_INV_REQUIRE_100REL) {
286                 *buf = "required";
287         } else if (endpoint->extensions.flags & PJSIP_INV_SUPPORT_100REL) {
288                 *buf = "yes";
289         } else {
290                 *buf = "no";
291         }
292
293         *buf = ast_strdup(*buf);
294         return 0;
295 }
296
297 static int timers_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
298 {
299         struct ast_sip_endpoint *endpoint = obj;
300
301         if (ast_true(var->value)) {
302                 endpoint->extensions.flags |= PJSIP_INV_SUPPORT_TIMER;
303         } else if (ast_false(var->value)) {
304                 endpoint->extensions.flags &= PJSIP_INV_SUPPORT_TIMER;
305         } else if (!strcasecmp(var->value, "required")) {
306                 endpoint->extensions.flags |= PJSIP_INV_REQUIRE_TIMER;
307         } else if (!strcasecmp(var->value, "always")) {
308                 endpoint->extensions.flags |= PJSIP_INV_ALWAYS_USE_TIMER;
309         } else {
310                 return -1;
311         }
312
313         return 0;
314 }
315
316 static int timers_to_str(const void *obj, const intptr_t *args, char **buf)
317 {
318         const struct ast_sip_endpoint *endpoint = obj;
319
320         if (endpoint->extensions.flags & PJSIP_INV_ALWAYS_USE_TIMER) {
321                 *buf = "always";
322         } else if (endpoint->extensions.flags & PJSIP_INV_REQUIRE_TIMER) {
323                 *buf = "required";
324         } else if (endpoint->extensions.flags & PJSIP_INV_SUPPORT_TIMER) {
325                 *buf = "yes";
326         } else {
327                 *buf = "no";
328         }
329
330         *buf = ast_strdup(*buf);
331         return 0;
332 }
333
334 void ast_sip_auth_array_destroy(struct ast_sip_auth_array *auths)
335 {
336         int i;
337
338         if (!auths) {
339                 return;
340         }
341
342         for (i = 0; i < auths->num; ++i) {
343                 ast_free((char *) auths->names[i]);
344         }
345         ast_free(auths->names);
346         auths->names = NULL;
347         auths->num = 0;
348 }
349
350 #define AUTH_INCREMENT 4
351
352 int ast_sip_auth_array_init(struct ast_sip_auth_array *auths, const char *value)
353 {
354         char *auth_names = ast_strdupa(value);
355         char *val;
356         int num_alloced = 0;
357         const char **alloced_auths;
358
359         ast_assert(auths != NULL);
360         ast_assert(auths->names == NULL);
361         ast_assert(!auths->num);
362
363         while ((val = strsep(&auth_names, ","))) {
364                 if (auths->num >= num_alloced) {
365                         num_alloced += AUTH_INCREMENT;
366                         alloced_auths = ast_realloc(auths->names, num_alloced * sizeof(char *));
367                         if (!alloced_auths) {
368                                 goto failure;
369                         }
370                         auths->names = alloced_auths;
371                 }
372                 val = ast_strdup(val);
373                 if (!val) {
374                         goto failure;
375                 }
376                 auths->names[auths->num] = val;
377                 ++auths->num;
378         }
379         return 0;
380
381 failure:
382         ast_sip_auth_array_destroy(auths);
383         return -1;
384 }
385
386 static int inbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
387 {
388         struct ast_sip_endpoint *endpoint = obj;
389
390         return ast_sip_auth_array_init(&endpoint->inbound_auths, var->value);
391 }
392
393 static int outbound_auth_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
394 {
395         struct ast_sip_endpoint *endpoint = obj;
396
397         return ast_sip_auth_array_init(&endpoint->outbound_auths, var->value);
398 }
399
400 int ast_sip_auths_to_str(const struct ast_sip_auth_array *auths, char **buf)
401 {
402         if (!auths || !auths->num) {
403                 return 0;
404         }
405
406         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
407                 return -1;
408         }
409
410         ast_join_delim(*buf, MAX_OBJECT_FIELD, auths->names, auths->num, ',');
411         return 0;
412 }
413
414 static int inbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
415 {
416         const struct ast_sip_endpoint *endpoint = obj;
417         return ast_sip_auths_to_str(&endpoint->inbound_auths, buf);
418 }
419
420 static int outbound_auths_to_str(const void *obj, const intptr_t *args, char **buf)
421 {
422         const struct ast_sip_endpoint *endpoint = obj;
423         return ast_sip_auths_to_str(&endpoint->outbound_auths, buf);
424 }
425
426 static int ident_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
427 {
428         struct ast_sip_endpoint *endpoint = obj;
429         char *idents = ast_strdupa(var->value);
430         char *val;
431
432         while ((val = strsep(&idents, ","))) {
433                 if (!strcasecmp(val, "username")) {
434                         endpoint->ident_method |= AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME;
435                 } else {
436                         ast_log(LOG_ERROR, "Unrecognized identification method %s specified for endpoint %s\n",
437                                         val, ast_sorcery_object_get_id(endpoint));
438                         return -1;
439                 }
440         }
441         return 0;
442 }
443
444 static int ident_to_str(const void *obj, const intptr_t *args, char **buf)
445 {
446         const struct ast_sip_endpoint *endpoint = obj;
447         switch (endpoint->ident_method) {
448         case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME :
449                 *buf = "username"; break;
450         default:
451                 return 0;
452         }
453
454         *buf = ast_strdup(*buf);
455         return 0;
456 }
457
458 static int direct_media_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
459 {
460         struct ast_sip_endpoint *endpoint = obj;
461
462         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
463                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
464         } else if (!strcasecmp(var->value, "update")) {
465                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
466         } else {
467                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
468                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
469                 return -1;
470         }
471         return 0;
472 }
473
474 static const char *id_configuration_refresh_methods[] = {
475         [AST_SIP_SESSION_REFRESH_METHOD_INVITE] = "invite",
476         [AST_SIP_SESSION_REFRESH_METHOD_UPDATE] = "update"
477 };
478
479 static int direct_media_method_to_str(const void *obj, const intptr_t *args, char **buf)
480 {
481         const struct ast_sip_endpoint *endpoint = obj;
482         if (ARRAY_IN_BOUNDS(endpoint->id.refresh_method, id_configuration_refresh_methods)) {
483                 *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
484         }
485         return 0;
486 }
487
488 static int connected_line_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
489 {
490         struct ast_sip_endpoint *endpoint = obj;
491
492         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
493                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
494         } else if (!strcasecmp(var->value, "update")) {
495                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
496         } else {
497                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
498                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
499                 return -1;
500         }
501         return 0;
502 }
503
504 static int connected_line_method_to_str(const void *obj, const intptr_t *args, char **buf)
505 {
506         const struct ast_sip_endpoint *endpoint = obj;
507         *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
508         return 0;
509 }
510
511 static int direct_media_glare_mitigation_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
512 {
513         struct ast_sip_endpoint *endpoint = obj;
514
515         if (!strcasecmp(var->value, "none")) {
516                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE;
517         } else if (!strcasecmp(var->value, "outgoing")) {
518                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING;
519         } else if (!strcasecmp(var->value, "incoming")) {
520                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING;
521         } else {
522                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
523                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
524                 return -1;
525         }
526
527         return 0;
528 }
529
530 static const char *direct_media_glare_mitigation_map[] = {
531         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE] = "none",
532         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING] = "outgoing",
533         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING] = "incoming"
534 };
535
536 static int direct_media_glare_mitigation_to_str(const void *obj, const intptr_t *args, char **buf)
537 {
538         const struct ast_sip_endpoint *endpoint = obj;
539         if (ARRAY_IN_BOUNDS(endpoint->media.direct_media.glare_mitigation, direct_media_glare_mitigation_map)) {
540                 *buf = ast_strdup(direct_media_glare_mitigation_map[endpoint->media.direct_media.glare_mitigation]);
541         }
542
543         return 0;
544 }
545
546 static int caller_id_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
547 {
548         struct ast_sip_endpoint *endpoint = obj;
549         char cid_name[80] = { '\0' };
550         char cid_num[80] = { '\0' };
551
552         ast_callerid_split(var->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
553         if (!ast_strlen_zero(cid_name)) {
554                 endpoint->id.self.name.str = ast_strdup(cid_name);
555                 if (!endpoint->id.self.name.str) {
556                         return -1;
557                 }
558                 endpoint->id.self.name.valid = 1;
559         }
560         if (!ast_strlen_zero(cid_num)) {
561                 endpoint->id.self.number.str = ast_strdup(cid_num);
562                 if (!endpoint->id.self.number.str) {
563                         return -1;
564                 }
565                 endpoint->id.self.number.valid = 1;
566         }
567         return 0;
568 }
569
570 static int caller_id_to_str(const void *obj, const intptr_t *args, char **buf)
571 {
572         const struct ast_sip_endpoint *endpoint = obj;
573         const char *name = S_COR(endpoint->id.self.name.valid,
574                                  endpoint->id.self.name.str, NULL);
575         const char *number = S_COR(endpoint->id.self.number.valid,
576                                    endpoint->id.self.number.str, NULL);
577
578         /* make sure size is at least 10 - that should cover the "<unknown>"
579            case as well as any additional formatting characters added in
580            the name and/or number case. */
581         int size = 10;
582         size += name ? strlen(name) : 0;
583         size += number ? strlen(number) : 0;
584
585         if (!(*buf = ast_calloc(size + 1, sizeof(char)))) {
586                 return -1;
587         }
588
589         ast_callerid_merge(*buf, size + 1, name, number, NULL);
590         return 0;
591 }
592
593 static int caller_id_privacy_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
594 {
595         struct ast_sip_endpoint *endpoint = obj;
596         int callingpres = ast_parse_caller_presentation(var->value);
597         if (callingpres == -1 && sscanf(var->value, "%d", &callingpres) != 1) {
598                 return -1;
599         }
600         endpoint->id.self.number.presentation = callingpres;
601         endpoint->id.self.name.presentation = callingpres;
602         return 0;
603 }
604
605 static int caller_id_privacy_to_str(const void *obj, const intptr_t *args, char **buf)
606 {
607         const struct ast_sip_endpoint *endpoint = obj;
608         const char *presentation = ast_named_caller_presentation(
609                 endpoint->id.self.name.presentation);
610
611         *buf = ast_strdup(presentation);
612         return 0;
613 }
614
615 static int caller_id_tag_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
616 {
617         struct ast_sip_endpoint *endpoint = obj;
618         endpoint->id.self.tag = ast_strdup(var->value);
619         return endpoint->id.self.tag ? 0 : -1;
620 }
621
622 static int caller_id_tag_to_str(const void *obj, const intptr_t *args, char **buf)
623 {
624         const struct ast_sip_endpoint *endpoint = obj;
625         *buf = ast_strdup(endpoint->id.self.tag);
626         return 0;
627 }
628
629 static int media_encryption_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
630 {
631         struct ast_sip_endpoint *endpoint = obj;
632
633         if (!strcasecmp("no", var->value)) {
634                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
635         } else if (!strcasecmp("sdes", var->value)) {
636                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_SDES;
637         } else if (!strcasecmp("dtls", var->value)) {
638                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_DTLS;
639                 ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, "dtlsenable", "yes");
640         } else {
641                 return -1;
642         }
643
644         return 0;
645 }
646
647 static const char *media_encryption_map[] = {
648         [AST_SIP_MEDIA_TRANSPORT_INVALID] = "invalid",
649         [AST_SIP_MEDIA_ENCRYPT_NONE] = "none",
650         [AST_SIP_MEDIA_ENCRYPT_SDES] = "sdes",
651         [AST_SIP_MEDIA_ENCRYPT_DTLS] = "dtls",
652 };
653
654 static int media_encryption_to_str(const void *obj, const intptr_t *args, char **buf)
655 {
656         const struct ast_sip_endpoint *endpoint = obj;
657         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.encryption, media_encryption_map)) {
658                 *buf = ast_strdup(media_encryption_map[
659                                           endpoint->media.rtp.encryption]);
660         }
661         return 0;
662 }
663
664 static int group_handler(const struct aco_option *opt,
665                          struct ast_variable *var, void *obj)
666 {
667         struct ast_sip_endpoint *endpoint = obj;
668
669         if (!strncmp(var->name, "callgroup", 9)) {
670                 if (!(endpoint->pickup.callgroup = ast_get_group(var->value))) {
671                         return -1;
672                 }
673         } else if (!strncmp(var->name, "pickupgroup", 11)) {
674                 if (!(endpoint->pickup.pickupgroup = ast_get_group(var->value))) {
675                         return -1;
676                 }
677         } else {
678                 return -1;
679         }
680
681         return 0;
682 }
683
684 static int callgroup_to_str(const void *obj, const intptr_t *args, char **buf)
685 {
686         const struct ast_sip_endpoint *endpoint = obj;
687
688         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
689                 return -1;
690         }
691
692         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.callgroup);
693         return 0;
694 }
695
696 static int pickupgroup_to_str(const void *obj, const intptr_t *args, char **buf)
697 {
698         const struct ast_sip_endpoint *endpoint = obj;
699
700         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
701                 return -1;
702         }
703
704         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.pickupgroup);
705         return 0;
706 }
707
708 static int named_groups_handler(const struct aco_option *opt,
709                                 struct ast_variable *var, void *obj)
710 {
711         struct ast_sip_endpoint *endpoint = obj;
712
713         if (!strncmp(var->name, "namedcallgroup", 14)) {
714                 if (!(endpoint->pickup.named_callgroups =
715                       ast_get_namedgroups(var->value))) {
716                         return -1;
717                 }
718         } else if (!strncmp(var->name, "namedpickupgroup", 16)) {
719                 if (!(endpoint->pickup.named_pickupgroups =
720                       ast_get_namedgroups(var->value))) {
721                         return -1;
722                 }
723         } else {
724                 return -1;
725         }
726
727         return 0;
728 }
729
730 static int named_callgroups_to_str(const void *obj, const intptr_t *args, char **buf)
731 {
732         const struct ast_sip_endpoint *endpoint = obj;
733         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
734
735         ast_print_namedgroups(&str, endpoint->pickup.named_callgroups);
736         *buf = ast_strdup(ast_str_buffer(str));
737         return 0;
738 }
739
740 static int named_pickupgroups_to_str(const void *obj, const intptr_t *args, char **buf)
741 {
742         const struct ast_sip_endpoint *endpoint = obj;
743         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
744
745         ast_print_namedgroups(&str, endpoint->pickup.named_pickupgroups);
746         *buf = ast_strdup(ast_str_buffer(str));
747         return 0;
748 }
749
750 static int dtls_handler(const struct aco_option *opt,
751                          struct ast_variable *var, void *obj)
752 {
753         struct ast_sip_endpoint *endpoint = obj;
754         char *name = ast_strdupa(var->name);
755         char *front, *buf = name;
756
757         /* strip out underscores in the name */
758         front = strtok(buf, "_");
759         while (front) {
760                 int size = strlen(front);
761                 ast_copy_string(buf, front, size + 1);
762                 buf += size;
763                 front = strtok(NULL, "_");
764         }
765
766         return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, name, var->value);
767 }
768
769 static int dtlsverify_to_str(const void *obj, const intptr_t *args, char **buf)
770 {
771         const struct ast_sip_endpoint *endpoint = obj;
772         *buf = ast_strdup(AST_YESNO(endpoint->media.rtp.dtls_cfg.verify));
773         return 0;
774 }
775
776 static int dtlsrekey_to_str(const void *obj, const intptr_t *args, char **buf)
777 {
778         const struct ast_sip_endpoint *endpoint = obj;
779
780         return ast_asprintf(
781                 buf, "%d", endpoint->media.rtp.dtls_cfg.rekey) >=0 ? 0 : -1;
782 }
783
784 static int dtlscertfile_to_str(const void *obj, const intptr_t *args, char **buf)
785 {
786         const struct ast_sip_endpoint *endpoint = obj;
787         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.certfile);
788         return 0;
789 }
790
791 static int dtlsprivatekey_to_str(const void *obj, const intptr_t *args, char **buf)
792 {
793         const struct ast_sip_endpoint *endpoint = obj;
794         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.pvtfile);
795         return 0;
796 }
797
798 static int dtlscipher_to_str(const void *obj, const intptr_t *args, char **buf)
799 {
800         const struct ast_sip_endpoint *endpoint = obj;
801         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cipher);
802         return 0;
803 }
804
805 static int dtlscafile_to_str(const void *obj, const intptr_t *args, char **buf)
806 {
807         const struct ast_sip_endpoint *endpoint = obj;
808         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cafile);
809         return 0;
810 }
811
812 static int dtlscapath_to_str(const void *obj, const intptr_t *args, char **buf)
813 {
814         const struct ast_sip_endpoint *endpoint = obj;
815         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.capath);
816         return 0;
817 }
818
819 static const char *ast_rtp_dtls_setup_map[] = {
820         [AST_RTP_DTLS_SETUP_ACTIVE] = "active",
821         [AST_RTP_DTLS_SETUP_PASSIVE] = "passive",
822         [AST_RTP_DTLS_SETUP_ACTPASS] = "actpass",
823         [AST_RTP_DTLS_SETUP_HOLDCONN] = "holdconn",
824 };
825
826 static int dtlssetup_to_str(const void *obj, const intptr_t *args, char **buf)
827 {
828         const struct ast_sip_endpoint *endpoint = obj;
829         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.default_setup, ast_rtp_dtls_setup_map)) {
830                 *buf = ast_strdup(ast_rtp_dtls_setup_map[endpoint->media.rtp.dtls_cfg.default_setup]);
831         }
832         return 0;
833 }
834
835 static int t38udptl_ec_handler(const struct aco_option *opt,
836         struct ast_variable *var, void *obj)
837 {
838         struct ast_sip_endpoint *endpoint = obj;
839
840         if (!strcmp(var->value, "none")) {
841                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_NONE;
842         } else if (!strcmp(var->value, "fec")) {
843                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_FEC;
844         } else if (!strcmp(var->value, "redundancy")) {
845                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_REDUNDANCY;
846         } else {
847                 return -1;
848         }
849
850         return 0;
851 }
852
853 static const char *ast_t38_ec_modes_map[] = {
854         [UDPTL_ERROR_CORRECTION_NONE] = "none",
855         [UDPTL_ERROR_CORRECTION_FEC] = "fec",
856         [UDPTL_ERROR_CORRECTION_REDUNDANCY] = "redundancy"
857 };
858
859 static int t38udptl_ec_to_str(const void *obj, const intptr_t *args, char **buf)
860 {
861         const struct ast_sip_endpoint *endpoint = obj;
862         if (ARRAY_IN_BOUNDS(endpoint->media.t38.error_correction, ast_t38_ec_modes_map)) {
863                 *buf = ast_strdup(ast_t38_ec_modes_map[
864                                           endpoint->media.t38.error_correction]);
865         }
866         return 0;
867 }
868
869 static void *sip_nat_hook_alloc(const char *name)
870 {
871         return ast_sorcery_generic_alloc(sizeof(struct ast_sip_nat_hook), NULL);
872 }
873
874 /*! \brief Destructor function for persistent endpoint information */
875 static void persistent_endpoint_destroy(void *obj)
876 {
877         struct sip_persistent_endpoint *persistent = obj;
878
879         ast_endpoint_shutdown(persistent->endpoint);
880         ast_free(persistent->aors);
881 }
882
883 /*! \brief Internal function which finds (or creates) persistent endpoint information */
884 static struct ast_endpoint *persistent_endpoint_find_or_create(const struct ast_sip_endpoint *endpoint)
885 {
886         RAII_VAR(struct sip_persistent_endpoint *, persistent, NULL, ao2_cleanup);
887         SCOPED_AO2LOCK(lock, persistent_endpoints);
888
889         if (!(persistent = ao2_find(persistent_endpoints, ast_sorcery_object_get_id(endpoint), OBJ_KEY | OBJ_NOLOCK))) {
890                 if (!(persistent = ao2_alloc(sizeof(*persistent), persistent_endpoint_destroy))) {
891                         return NULL;
892                 }
893
894                 if (!(persistent->endpoint = ast_endpoint_create("PJSIP", ast_sorcery_object_get_id(endpoint)))) {
895                         return NULL;
896                 }
897
898                 persistent->aors = ast_strdup(endpoint->aors);
899
900                 if (ast_strlen_zero(persistent->aors)) {
901                         ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_UNKNOWN);
902                 } else {
903                         persistent_endpoint_update_state(persistent, NULL, 0);
904                 }
905
906                 ao2_link_flags(persistent_endpoints, persistent, OBJ_NOLOCK);
907         }
908
909         ao2_ref(persistent->endpoint, +1);
910         return persistent->endpoint;
911 }
912
913 /*! \brief Callback function for when an object is finalized */
914 static int sip_endpoint_apply_handler(const struct ast_sorcery *sorcery, void *obj)
915 {
916         struct ast_sip_endpoint *endpoint = obj;
917
918         if (!(endpoint->persistent = persistent_endpoint_find_or_create(endpoint))) {
919                 return -1;
920         }
921
922         if (!ast_strlen_zero(endpoint->outbound_proxy)) {
923                 pj_pool_t *pool = pjsip_endpt_create_pool(ast_sip_get_pjsip_endpoint(), "Outbound Proxy Validation", 256, 256);
924                 static const pj_str_t ROUTE_HNAME = { "Route", 5 };
925                 pj_str_t tmp;
926
927                 if (!pool) {
928                         ast_log(LOG_ERROR, "Could not allocate pool for outbound proxy validation on '%s'\n",
929                                 ast_sorcery_object_get_id(endpoint));
930                         return -1;
931                 }
932
933                 pj_strdup2_with_null(pool, &tmp, endpoint->outbound_proxy);
934                 if (!pjsip_parse_hdr(pool, &ROUTE_HNAME, tmp.ptr, tmp.slen, NULL)) {
935                         ast_log(LOG_ERROR, "Invalid outbound proxy '%s' specified on endpoint '%s'\n",
936                                 endpoint->outbound_proxy, ast_sorcery_object_get_id(endpoint));
937                         pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
938                         return -1;
939                 }
940
941                 pjsip_endpt_release_pool(ast_sip_get_pjsip_endpoint(), pool);
942         }
943
944         return 0;
945 }
946
947 static const char *get_device_state(const struct ast_sip_endpoint *endpoint)
948 {
949         char device[MAX_OBJECT_FIELD];
950
951         snprintf(device, MAX_OBJECT_FIELD, "PJSIP/%s", ast_sorcery_object_get_id(endpoint));
952         return ast_devstate2str(ast_device_state(device));
953 }
954
955 static struct ast_endpoint_snapshot *sip_get_endpoint_snapshot(
956         const struct ast_sip_endpoint *endpoint)
957 {
958         return ast_endpoint_latest_snapshot(
959                 ast_endpoint_get_tech(endpoint->persistent),
960                 ast_endpoint_get_resource(endpoint->persistent));
961 }
962
963 int ast_sip_for_each_channel_snapshot(
964         const struct ast_endpoint_snapshot *endpoint_snapshot,
965         on_channel_snapshot_t on_channel_snapshot, void *arg)
966 {
967         int num, num_channels = endpoint_snapshot->num_channels;
968         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
969
970         if (!on_channel_snapshot || !num_channels ||
971             !(cache = ast_channel_cache())) {
972                 return 0;
973         }
974
975         ao2_ref(cache, +1);
976
977         for (num = 0; num < num_channels; ++num) {
978                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
979                 struct ast_channel_snapshot *snapshot;
980
981                 msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
982                         endpoint_snapshot->channel_ids[num]);
983
984                 if (!(snapshot = stasis_message_data(msg))) {
985                         continue;
986                 }
987
988                 if (on_channel_snapshot(
989                             snapshot, num == (num_channels - 1), arg)) {
990                         return -1;
991                 }
992         }
993         return 0;
994 }
995
996 static int active_channels_to_str_cb(const struct ast_channel_snapshot *snapshot,
997                                      int last, void *arg)
998 {
999         struct ast_str **buf = arg;
1000         if (last) {
1001                 ast_str_append(buf, 0, "%s", snapshot->name);
1002         } else {
1003                 ast_str_append(buf, 0, "%s,", snapshot->name);
1004         }
1005         return 0;
1006 }
1007
1008 static void active_channels_to_str(const struct ast_sip_endpoint *endpoint,
1009                                    struct ast_str **str)
1010 {
1011
1012         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot,
1013                  sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1014
1015         if (endpoint_snapshot) {
1016                 return;
1017         }
1018
1019         ast_sip_for_each_channel_snapshot(endpoint_snapshot,
1020                                           active_channels_to_str_cb, str);
1021 }
1022
1023 #define AMI_DEFAULT_STR_SIZE 512
1024
1025 struct ast_str *ast_sip_create_ami_event(const char *event, struct ast_sip_ami *ami)
1026 {
1027         struct ast_str *buf = ast_str_create(AMI_DEFAULT_STR_SIZE);
1028
1029         if (!(buf)) {
1030                 astman_send_error_va(ami->s, ami->m, "Unable create event "
1031                                      "for %s\n", event);
1032                 return NULL;
1033         }
1034
1035         ast_str_set(&buf, 0, "Event: %s\r\n", event);
1036         return buf;
1037 }
1038
1039 static void sip_sorcery_object_ami_set_type_name(const void *obj, struct ast_str **buf)
1040 {
1041         ast_str_append(buf, 0, "ObjectType: %s\r\n",
1042                        ast_sorcery_object_get_type(obj));
1043         ast_str_append(buf, 0, "ObjectName: %s\r\n",
1044                        ast_sorcery_object_get_id(obj));
1045 }
1046
1047 int ast_sip_sorcery_object_to_ami(const void *obj, struct ast_str **buf)
1048 {
1049         RAII_VAR(struct ast_variable *, objset, ast_sorcery_objectset_create(
1050                          ast_sip_get_sorcery(), obj), ast_variables_destroy);
1051         struct ast_variable *i;
1052
1053         if (!objset) {
1054                 return -1;
1055         }
1056
1057         sip_sorcery_object_ami_set_type_name(obj, buf);
1058
1059         for (i = objset; i; i = i->next) {
1060                 RAII_VAR(char *, camel, ast_to_camel_case(i->name), ast_free);
1061                 ast_str_append(buf, 0, "%s: %s\r\n", camel, i->value);
1062         }
1063
1064         return 0;
1065 }
1066
1067 static int sip_endpoints_aors_ami(void *obj, void *arg, int flags)
1068 {
1069         const struct ast_sip_aor *aor = obj;
1070         struct ast_str **buf = arg;
1071
1072         ast_str_append(buf, 0, "Contacts: ");
1073         ast_sip_for_each_contact(aor, ast_sip_contact_to_str, arg);
1074         ast_str_append(buf, 0, "\r\n");
1075
1076         return 0;
1077 }
1078
1079 static int sip_endpoint_to_ami(const struct ast_sip_endpoint *endpoint,
1080                                struct ast_str **buf)
1081 {
1082         if (ast_sip_sorcery_object_to_ami(endpoint, buf)) {
1083                 return -1;
1084         }
1085
1086         ast_str_append(buf, 0, "DeviceState: %s\r\n",
1087                        get_device_state(endpoint));
1088
1089         ast_str_append(buf, 0, "ActiveChannels: ");
1090         active_channels_to_str(endpoint, buf);
1091         ast_str_append(buf, 0, "\r\n");
1092
1093         return 0;
1094 }
1095
1096 static int format_ami_endpoint(const struct ast_sip_endpoint *endpoint,
1097                                struct ast_sip_ami *ami)
1098 {
1099         RAII_VAR(struct ast_str *, buf,
1100                  ast_sip_create_ami_event("EndpointDetail", ami), ast_free);
1101
1102         if (!buf) {
1103                 return -1;
1104         }
1105
1106         sip_endpoint_to_ami(endpoint, &buf);
1107         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1108         return 0;
1109 }
1110
1111 #define AMI_SHOW_ENDPOINTS "PJSIPShowEndpoints"
1112 #define AMI_SHOW_ENDPOINT "PJSIPShowEndpoint"
1113
1114 static int ami_show_endpoint(struct mansession *s, const struct message *m)
1115 {
1116         struct ast_sip_ami ami = { .s = s, .m = m };
1117         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1118         const char *endpoint_name = astman_get_header(m, "Endpoint");
1119         int count = 0;
1120
1121         if (ast_strlen_zero(endpoint_name)) {
1122                 astman_send_error_va(s, m, "%s requires an endpoint name\n",
1123                         AMI_SHOW_ENDPOINT);
1124                 return 0;
1125         }
1126
1127         if (!strncasecmp(endpoint_name, "pjsip/", 6)) {
1128                 endpoint_name += 6;
1129         }
1130
1131         if (!(endpoint = ast_sorcery_retrieve_by_id(
1132                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1133                 astman_send_error_va(s, m, "Unable to retrieve endpoint %s\n",
1134                         endpoint_name);
1135                 return -1;
1136         }
1137
1138         astman_send_listack(s, m, "Following are Events for each object "
1139                             "associated with the the Endpoint", "start");
1140
1141         /* the endpoint detail needs to always come first so apply as such */
1142         if (format_ami_endpoint(endpoint, &ami) ||
1143             ast_sip_format_endpoint_ami(endpoint, &ami, &count)) {
1144                 astman_send_error_va(s, m, "Unable to format endpoint %s\n",
1145                         endpoint_name);
1146         }
1147
1148         astman_append(s,
1149                       "Event: EndpointDetailComplete\r\n"
1150                       "EventList: Complete\r\n"
1151                       "ListItems: %d\r\n\r\n", count + 1);
1152         return 0;
1153 }
1154
1155 static int format_str_append_auth(const struct ast_sip_auth_array *auths,
1156                                   struct ast_str **buf)
1157 {
1158         char *str = NULL;
1159         if (ast_sip_auths_to_str(auths, &str)) {
1160                 return -1;
1161         }
1162         ast_str_append(buf, 0, "%s", str ? str : "");
1163         ast_free(str);
1164         return 0;
1165 }
1166
1167 static int format_ami_endpoints(void *obj, void *arg, int flags)
1168 {
1169
1170         struct ast_sip_endpoint *endpoint = obj;
1171         struct ast_sip_ami *ami = arg;
1172         RAII_VAR(struct ast_str *, buf,
1173                  ast_sip_create_ami_event("EndpointList", ami), ast_free);
1174
1175         if (!buf) {
1176                 return -1;
1177         }
1178
1179         sip_sorcery_object_ami_set_type_name(endpoint, &buf);
1180         ast_str_append(&buf, 0, "Transport: %s\r\n",
1181                        endpoint->transport);
1182         ast_str_append(&buf, 0, "Aor: %s\r\n",
1183                        endpoint->aors);
1184
1185         ast_str_append(&buf, 0, "Auths: ");
1186         format_str_append_auth(&endpoint->inbound_auths, &buf);
1187         ast_str_append(&buf, 0, "\r\n");
1188
1189         ast_str_append(&buf, 0, "OutboundAuths: ");
1190         format_str_append_auth(&endpoint->outbound_auths, &buf);
1191         ast_str_append(&buf, 0, "\r\n");
1192
1193         ast_sip_for_each_aor(endpoint->aors,
1194                              sip_endpoints_aors_ami, &buf);
1195
1196         ast_str_append(&buf, 0, "DeviceState: %s\r\n",
1197                        get_device_state(endpoint));
1198
1199         ast_str_append(&buf, 0, "ActiveChannels: ");
1200         active_channels_to_str(endpoint, &buf);
1201         ast_str_append(&buf, 0, "\r\n");
1202
1203         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1204         return 0;
1205 }
1206
1207 static int ami_show_endpoints(struct mansession *s, const struct message *m)
1208 {
1209         struct ast_sip_ami ami = { .s = s, .m = m };
1210         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
1211         int num;
1212
1213         endpoints = ast_sip_get_endpoints();
1214         if (!endpoints) {
1215                 return -1;
1216         }
1217
1218         if (!(num = ao2_container_count(endpoints))) {
1219                 astman_send_error(s, m, "No endpoints found\n");
1220                 return 0;
1221         }
1222
1223         astman_send_listack(s, m, "A listing of Endpoints follows, "
1224                             "presented as EndpointList events", "start");
1225
1226         ao2_callback(endpoints, OBJ_NODATA, format_ami_endpoints, &ami);
1227
1228         astman_append(s,
1229                       "Event: EndpointListComplete\r\n"
1230                       "EventList: Complete\r\n"
1231                       "ListItems: %d\r\n\r\n", num);
1232         return 0;
1233 }
1234
1235 int ast_res_pjsip_initialize_configuration(const struct ast_module_info *ast_module_info)
1236 {
1237         if (ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands))) {
1238                 return -1;
1239         }
1240
1241         if (ast_manager_register_xml(AMI_SHOW_ENDPOINTS, EVENT_FLAG_SYSTEM, ami_show_endpoints) ||
1242             ast_manager_register_xml(AMI_SHOW_ENDPOINT, EVENT_FLAG_SYSTEM, ami_show_endpoint)) {
1243                 return -1;
1244         }
1245
1246         if (!(persistent_endpoints = ao2_container_alloc(PERSISTENT_BUCKETS, persistent_endpoint_hash, persistent_endpoint_cmp))) {
1247                 return -1;
1248         }
1249
1250         if (!(sip_sorcery = ast_sorcery_open())) {
1251                 ast_log(LOG_ERROR, "Failed to open SIP sorcery failed to open\n");
1252                 return -1;
1253         }
1254
1255         ast_sorcery_apply_config(sip_sorcery, "res_pjsip");
1256
1257         if (ast_sip_initialize_sorcery_auth(sip_sorcery)) {
1258                 ast_log(LOG_ERROR, "Failed to register SIP authentication support\n");
1259                 ast_sorcery_unref(sip_sorcery);
1260                 sip_sorcery = NULL;
1261                 return -1;
1262         }
1263
1264         ast_sorcery_apply_default(sip_sorcery, "endpoint", "config", "pjsip.conf,criteria=type=endpoint");
1265
1266         ast_sorcery_apply_default(sip_sorcery, "nat_hook", "memory", NULL);
1267
1268         if (ast_sorcery_object_register(sip_sorcery, "endpoint", ast_sip_endpoint_alloc, NULL, sip_endpoint_apply_handler)) {
1269                 ast_log(LOG_ERROR, "Failed to register SIP endpoint object with sorcery\n");
1270                 ast_sorcery_unref(sip_sorcery);
1271                 sip_sorcery = NULL;
1272                 return -1;
1273         }
1274
1275         ast_sorcery_internal_object_register(sip_sorcery, "nat_hook", sip_nat_hook_alloc, NULL, NULL);
1276
1277         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "type", "", OPT_NOOP_T, 0, 0);
1278         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "context", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, context));
1279         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "disallow", "", OPT_CODEC_T, 0, FLDSET(struct ast_sip_endpoint, media.prefs, media.codecs));
1280         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow", "", OPT_CODEC_T, 1, FLDSET(struct ast_sip_endpoint, media.prefs, media.codecs));
1281         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtmf_mode", "rfc4733", dtmf_handler, dtmf_to_str, 0, 0);
1282         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ipv6));
1283         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_symmetric", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.symmetric));
1284         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "ice_support", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ice_support));
1285         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_ptime", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_ptime));
1286         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_rport", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.force_rport));
1287         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rewrite_contact", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.rewrite_contact));
1288         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, transport));
1289         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, outbound_proxy));
1290         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_suggest", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, mohsuggest));
1291         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "100rel", "yes", prack_handler, prack_to_str, 0, 0);
1292         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "timers", "yes", timers_handler, timers_to_str, 0, 0);
1293         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));
1294         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));
1295         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "auth", "", inbound_auth_handler, inbound_auths_to_str, 0, 0);
1296         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, 0, 0);
1297         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aors", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, aors));
1298         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_address", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.address));
1299         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "identify_by", "username", ident_handler, ident_to_str, 0, 0);
1300         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "direct_media", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.direct_media.enabled));
1301         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "direct_media_method", "invite", direct_media_method_handler, direct_media_method_to_str, 0, 0);
1302         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "connected_line_method", "invite", connected_line_method_handler, connected_line_method_to_str, 0, 0);
1303         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, 0, 0);
1304         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));
1305         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid", "", caller_id_handler, caller_id_to_str, 0, 0);
1306         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_privacy", "", caller_id_privacy_handler, caller_id_privacy_to_str, 0, 0);
1307         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_tag", "", caller_id_tag_handler, caller_id_tag_to_str, 0, 0);
1308         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_inbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_inbound));
1309         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_outbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_outbound));
1310         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_pai", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_pai));
1311         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_rpid", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_rpid));
1312         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_diversion", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_diversion));
1313         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mailboxes", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.mailboxes));
1314         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aggregate_mwi", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.aggregate));
1315         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "media_encryption", "no", media_encryption_handler, media_encryption_to_str, 0, 0);
1316         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_avpf", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_avpf));
1317         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "one_touch_recording", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, info.recording.enabled));
1318         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "inband_progress", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, inband_progress));
1319         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "call_group", "", group_handler, callgroup_to_str, 0, 0);
1320         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "pickup_group", "", group_handler, pickupgroup_to_str, 0, 0);
1321         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_call_group", "", named_groups_handler, named_callgroups_to_str, 0, 0);
1322         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_pickup_group", "", named_groups_handler, named_pickupgroups_to_str, 0, 0);
1323         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));
1324         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.enabled));
1325         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "t38_udptl_ec", "none", t38udptl_ec_handler, t38udptl_ec_to_str, 0, 0);
1326         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_maxdatagram", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.t38.maxdatagram));
1327         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, faxdetect));
1328         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_nat", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.nat));
1329         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.ipv6));
1330         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tone_zone", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, zone));
1331         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "language", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, language));
1332         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_on_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.onfeature));
1333         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_off_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.offfeature));
1334         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_transfer", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allowtransfer));
1335         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_owner", "-", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpowner));
1336         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_session", "Asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpsession));
1337         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tos_audio", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.tos_audio));
1338         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tos_video", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.tos_video));
1339         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_audio", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_audio));
1340         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_video", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_video));
1341         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_subscribe", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.allow));
1342         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sub_min_expiry", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, subscription.minexpiry));
1343         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromuser));
1344         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_domain", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromdomain));
1345         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.fromuser));
1346         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_engine", "asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.rtp.engine));
1347         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_verify", "", dtls_handler, dtlsverify_to_str, 0, 0);
1348         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_rekey", "", dtls_handler, dtlsrekey_to_str, 0, 0);
1349         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cert_file", "", dtls_handler, dtlscertfile_to_str, 0, 0);
1350         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_private_key", "", dtls_handler, dtlsprivatekey_to_str, 0, 0);
1351         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cipher", "", dtls_handler, dtlscipher_to_str, 0, 0);
1352         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_file", "", dtls_handler, dtlscafile_to_str, 0, 0);
1353         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_path", "", dtls_handler, dtlscapath_to_str, 0, 0);
1354         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_setup", "", dtls_handler, dtlssetup_to_str, 0, 0);
1355         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));
1356
1357         if (ast_sip_initialize_sorcery_transport(sip_sorcery)) {
1358                 ast_log(LOG_ERROR, "Failed to register SIP transport support with sorcery\n");
1359                 ast_sorcery_unref(sip_sorcery);
1360                 sip_sorcery = NULL;
1361                 return -1;
1362         }
1363
1364         if (ast_sip_initialize_sorcery_location(sip_sorcery)) {
1365                 ast_log(LOG_ERROR, "Failed to register SIP location support with sorcery\n");
1366                 ast_sorcery_unref(sip_sorcery);
1367                 sip_sorcery = NULL;
1368                 return -1;
1369         }
1370
1371         if (ast_sip_initialize_sorcery_qualify(sip_sorcery)) {
1372                 ast_log(LOG_ERROR, "Failed to register SIP qualify support with sorcery\n");
1373                 ast_sorcery_unref(sip_sorcery);
1374                 sip_sorcery = NULL;
1375                 return -1;
1376         }
1377
1378         ast_sorcery_observer_add(sip_sorcery, "contact", &state_contact_observer);
1379
1380         if (ast_sip_initialize_sorcery_domain_alias(sip_sorcery)) {
1381                 ast_log(LOG_ERROR, "Failed to register SIP domain aliases support with sorcery\n");
1382                 ast_sorcery_unref(sip_sorcery);
1383                 sip_sorcery = NULL;
1384                 return -1;
1385         }
1386
1387         if (ast_sip_initialize_sorcery_global(sip_sorcery)) {
1388                 ast_log(LOG_ERROR, "Failed to register SIP Global support\n");
1389                 ast_sorcery_unref(sip_sorcery);
1390                 sip_sorcery = NULL;
1391                 return -1;
1392         }
1393
1394         ast_sorcery_load(sip_sorcery);
1395
1396         return 0;
1397 }
1398
1399 void ast_res_pjsip_destroy_configuration(void)
1400 {
1401         ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
1402         ast_manager_unregister(AMI_SHOW_ENDPOINT);
1403         ast_manager_unregister(AMI_SHOW_ENDPOINTS);
1404         ast_sorcery_unref(sip_sorcery);
1405 }
1406
1407 int ast_res_pjsip_reload_configuration(void)
1408 {
1409         if (sip_sorcery) {
1410                 ast_sorcery_reload(sip_sorcery);
1411         }
1412         return 0;
1413 }
1414
1415 static void subscription_configuration_destroy(struct ast_sip_endpoint_subscription_configuration *subscription)
1416 {
1417         ast_string_field_free_memory(&subscription->mwi);
1418 }
1419
1420 static void info_configuration_destroy(struct ast_sip_endpoint_info_configuration *info)
1421 {
1422         ast_string_field_free_memory(&info->recording);
1423 }
1424
1425 static void media_configuration_destroy(struct ast_sip_endpoint_media_configuration *media)
1426 {
1427         ast_string_field_free_memory(&media->rtp);
1428         ast_string_field_free_memory(media);
1429 }
1430
1431 static void endpoint_destructor(void* obj)
1432 {
1433         struct ast_sip_endpoint *endpoint = obj;
1434
1435         ast_string_field_free_memory(endpoint);
1436
1437         if (endpoint->media.codecs) {
1438                 ast_format_cap_destroy(endpoint->media.codecs);
1439         }
1440         subscription_configuration_destroy(&endpoint->subscription);
1441         info_configuration_destroy(&endpoint->info);
1442         media_configuration_destroy(&endpoint->media);
1443         ast_sip_auth_array_destroy(&endpoint->inbound_auths);
1444         ast_sip_auth_array_destroy(&endpoint->outbound_auths);
1445         ast_party_id_free(&endpoint->id.self);
1446         endpoint->pickup.named_callgroups = ast_unref_namedgroups(endpoint->pickup.named_callgroups);
1447         endpoint->pickup.named_pickupgroups = ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
1448         ao2_cleanup(endpoint->persistent);
1449 }
1450
1451 static int init_subscription_configuration(struct ast_sip_endpoint_subscription_configuration *subscription)
1452 {
1453         return ast_string_field_init(&subscription->mwi, 64);
1454 }
1455
1456 static int init_info_configuration(struct ast_sip_endpoint_info_configuration *info)
1457 {
1458         return ast_string_field_init(&info->recording, 32);
1459 }
1460
1461 static int init_media_configuration(struct ast_sip_endpoint_media_configuration *media)
1462 {
1463         return ast_string_field_init(media, 64) || ast_string_field_init(&media->rtp, 32);
1464 }
1465
1466 void *ast_sip_endpoint_alloc(const char *name)
1467 {
1468         struct ast_sip_endpoint *endpoint = ast_sorcery_generic_alloc(sizeof(*endpoint), endpoint_destructor);
1469         if (!endpoint) {
1470                 return NULL;
1471         }
1472         if (ast_string_field_init(endpoint, 64)) {
1473                 ao2_cleanup(endpoint);
1474                 return NULL;
1475         }
1476         if (!(endpoint->media.codecs = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_NOLOCK))) {
1477                 ao2_cleanup(endpoint);
1478                 return NULL;
1479         }
1480         if (init_subscription_configuration(&endpoint->subscription)) {
1481                 ao2_cleanup(endpoint);
1482                 return NULL;
1483         }
1484         if (init_info_configuration(&endpoint->info)) {
1485                 ao2_cleanup(endpoint);
1486                 return NULL;
1487         }
1488         if (init_media_configuration(&endpoint->media)) {
1489                 ao2_cleanup(endpoint);
1490                 return NULL;
1491         }
1492         ast_party_id_init(&endpoint->id.self);
1493         return endpoint;
1494 }
1495
1496 struct ao2_container *ast_sip_get_endpoints(void)
1497 {
1498         struct ao2_container *endpoints;
1499
1500         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1501
1502         return endpoints;
1503 }
1504
1505 int ast_sip_retrieve_auths(const struct ast_sip_auth_array *auths, struct ast_sip_auth **out)
1506 {
1507         int i;
1508
1509         for (i = 0; i < auths->num; ++i) {
1510                 out[i] = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), SIP_SORCERY_AUTH_TYPE, auths->names[i]);
1511                 if (!out[i]) {
1512                         ast_log(LOG_NOTICE, "Couldn't find auth '%s'. Cannot authenticate\n", auths->names[i]);
1513                         return -1;
1514                 }
1515         }
1516
1517         return 0;
1518 }
1519
1520 void ast_sip_cleanup_auths(struct ast_sip_auth *auths[], size_t num_auths)
1521 {
1522         int i;
1523         for (i = 0; i < num_auths; ++i) {
1524                 ao2_cleanup(auths[i]);
1525         }
1526 }
1527
1528 struct ast_sorcery *ast_sip_get_sorcery(void)
1529 {
1530         return sip_sorcery;
1531 }