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