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