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