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