res_pjsip_mwi: Add voicemail extension and mwi_subscribe_replaces_unsolicited
[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 = ast_strip(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 = ast_strip(strsep(&idents, ",")))) {
481                 if (ast_strlen_zero(val)) {
482                         continue;
483                 }
484
485                 if (!strcasecmp(val, "username")) {
486                         endpoint->ident_method |= AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME;
487                 } else {
488                         ast_log(LOG_ERROR, "Unrecognized identification method %s specified for endpoint %s\n",
489                                         val, ast_sorcery_object_get_id(endpoint));
490                         return -1;
491                 }
492         }
493         return 0;
494 }
495
496 static int ident_to_str(const void *obj, const intptr_t *args, char **buf)
497 {
498         const struct ast_sip_endpoint *endpoint = obj;
499         switch (endpoint->ident_method) {
500         case AST_SIP_ENDPOINT_IDENTIFY_BY_USERNAME :
501                 *buf = "username"; break;
502         default:
503                 return 0;
504         }
505
506         *buf = ast_strdup(*buf);
507         return 0;
508 }
509
510 static int redirect_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
511 {
512         struct ast_sip_endpoint *endpoint = obj;
513
514         if (!strcasecmp(var->value, "user")) {
515                 endpoint->redirect_method = AST_SIP_REDIRECT_USER;
516         } else if (!strcasecmp(var->value, "uri_core")) {
517                 endpoint->redirect_method = AST_SIP_REDIRECT_URI_CORE;
518         } else if (!strcasecmp(var->value, "uri_pjsip")) {
519                 endpoint->redirect_method = AST_SIP_REDIRECT_URI_PJSIP;
520         } else {
521                 ast_log(LOG_ERROR, "Unrecognized redirect method %s specified for endpoint %s\n",
522                         var->value, ast_sorcery_object_get_id(endpoint));
523                 return -1;
524         }
525
526         return 0;
527 }
528
529 static int direct_media_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
530 {
531         struct ast_sip_endpoint *endpoint = obj;
532
533         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
534                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
535         } else if (!strcasecmp(var->value, "update")) {
536                 endpoint->media.direct_media.method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
537         } else {
538                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
539                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
540                 return -1;
541         }
542         return 0;
543 }
544
545 static const char *id_configuration_refresh_methods[] = {
546         [AST_SIP_SESSION_REFRESH_METHOD_INVITE] = "invite",
547         [AST_SIP_SESSION_REFRESH_METHOD_UPDATE] = "update"
548 };
549
550 static int direct_media_method_to_str(const void *obj, const intptr_t *args, char **buf)
551 {
552         const struct ast_sip_endpoint *endpoint = obj;
553         if (ARRAY_IN_BOUNDS(endpoint->id.refresh_method, id_configuration_refresh_methods)) {
554                 *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
555         }
556         return 0;
557 }
558
559 static int connected_line_method_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
560 {
561         struct ast_sip_endpoint *endpoint = obj;
562
563         if (!strcasecmp(var->value, "invite") || !strcasecmp(var->value, "reinvite")) {
564                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_INVITE;
565         } else if (!strcasecmp(var->value, "update")) {
566                 endpoint->id.refresh_method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
567         } else {
568                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
569                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
570                 return -1;
571         }
572         return 0;
573 }
574
575 static int connected_line_method_to_str(const void *obj, const intptr_t *args, char **buf)
576 {
577         const struct ast_sip_endpoint *endpoint = obj;
578         *buf = ast_strdup(id_configuration_refresh_methods[endpoint->id.refresh_method]);
579         return 0;
580 }
581
582 static int direct_media_glare_mitigation_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
583 {
584         struct ast_sip_endpoint *endpoint = obj;
585
586         if (!strcasecmp(var->value, "none")) {
587                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE;
588         } else if (!strcasecmp(var->value, "outgoing")) {
589                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING;
590         } else if (!strcasecmp(var->value, "incoming")) {
591                 endpoint->media.direct_media.glare_mitigation = AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING;
592         } else {
593                 ast_log(LOG_NOTICE, "Unrecognized option value %s for %s on endpoint %s\n",
594                                 var->value, var->name, ast_sorcery_object_get_id(endpoint));
595                 return -1;
596         }
597
598         return 0;
599 }
600
601 static const char *direct_media_glare_mitigation_map[] = {
602         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE] = "none",
603         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING] = "outgoing",
604         [AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING] = "incoming"
605 };
606
607 static int direct_media_glare_mitigation_to_str(const void *obj, const intptr_t *args, char **buf)
608 {
609         const struct ast_sip_endpoint *endpoint = obj;
610         if (ARRAY_IN_BOUNDS(endpoint->media.direct_media.glare_mitigation, direct_media_glare_mitigation_map)) {
611                 *buf = ast_strdup(direct_media_glare_mitigation_map[endpoint->media.direct_media.glare_mitigation]);
612         }
613
614         return 0;
615 }
616
617 static int caller_id_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
618 {
619         struct ast_sip_endpoint *endpoint = obj;
620         char cid_name[80] = { '\0' };
621         char cid_num[80] = { '\0' };
622
623         ast_callerid_split(var->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
624         if (!ast_strlen_zero(cid_name)) {
625                 endpoint->id.self.name.str = ast_strdup(cid_name);
626                 if (!endpoint->id.self.name.str) {
627                         return -1;
628                 }
629                 endpoint->id.self.name.valid = 1;
630         }
631         if (!ast_strlen_zero(cid_num)) {
632                 endpoint->id.self.number.str = ast_strdup(cid_num);
633                 if (!endpoint->id.self.number.str) {
634                         return -1;
635                 }
636                 endpoint->id.self.number.valid = 1;
637         }
638         return 0;
639 }
640
641 static int caller_id_to_str(const void *obj, const intptr_t *args, char **buf)
642 {
643         const struct ast_sip_endpoint *endpoint = obj;
644         const char *name = S_COR(endpoint->id.self.name.valid,
645                                  endpoint->id.self.name.str, NULL);
646         const char *number = S_COR(endpoint->id.self.number.valid,
647                                    endpoint->id.self.number.str, NULL);
648
649         /* make sure size is at least 10 - that should cover the "<unknown>"
650            case as well as any additional formatting characters added in
651            the name and/or number case. */
652         int size = 10;
653         size += name ? strlen(name) : 0;
654         size += number ? strlen(number) : 0;
655
656         if (!(*buf = ast_calloc(size + 1, sizeof(char)))) {
657                 return -1;
658         }
659
660         ast_callerid_merge(*buf, size + 1, name, number, NULL);
661         return 0;
662 }
663
664 static int caller_id_privacy_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
665 {
666         struct ast_sip_endpoint *endpoint = obj;
667         int callingpres = ast_parse_caller_presentation(var->value);
668         if (callingpres == -1 && sscanf(var->value, "%d", &callingpres) != 1) {
669                 return -1;
670         }
671         endpoint->id.self.number.presentation = callingpres;
672         endpoint->id.self.name.presentation = callingpres;
673         return 0;
674 }
675
676 static int caller_id_privacy_to_str(const void *obj, const intptr_t *args, char **buf)
677 {
678         const struct ast_sip_endpoint *endpoint = obj;
679         const char *presentation = ast_named_caller_presentation(
680                 endpoint->id.self.name.presentation);
681
682         *buf = ast_strdup(presentation);
683         return 0;
684 }
685
686 static int caller_id_tag_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
687 {
688         struct ast_sip_endpoint *endpoint = obj;
689         endpoint->id.self.tag = ast_strdup(var->value);
690         return endpoint->id.self.tag ? 0 : -1;
691 }
692
693 static int caller_id_tag_to_str(const void *obj, const intptr_t *args, char **buf)
694 {
695         const struct ast_sip_endpoint *endpoint = obj;
696         *buf = ast_strdup(endpoint->id.self.tag);
697         return 0;
698 }
699
700 static int media_encryption_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
701 {
702         struct ast_sip_endpoint *endpoint = obj;
703
704         if (!strcasecmp("no", var->value)) {
705                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_NONE;
706         } else if (!strcasecmp("sdes", var->value)) {
707                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_SDES;
708         } else if (!strcasecmp("dtls", var->value)) {
709                 endpoint->media.rtp.encryption = AST_SIP_MEDIA_ENCRYPT_DTLS;
710                 return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, "dtlsenable", "yes");
711         } else {
712                 return -1;
713         }
714
715         return 0;
716 }
717
718 static const char *media_encryption_map[] = {
719         [AST_SIP_MEDIA_TRANSPORT_INVALID] = "invalid",
720         [AST_SIP_MEDIA_ENCRYPT_NONE] = "no",
721         [AST_SIP_MEDIA_ENCRYPT_SDES] = "sdes",
722         [AST_SIP_MEDIA_ENCRYPT_DTLS] = "dtls",
723 };
724
725 static int media_encryption_to_str(const void *obj, const intptr_t *args, char **buf)
726 {
727         const struct ast_sip_endpoint *endpoint = obj;
728         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.encryption, media_encryption_map)) {
729                 *buf = ast_strdup(media_encryption_map[
730                                           endpoint->media.rtp.encryption]);
731         }
732         return 0;
733 }
734
735 static int group_handler(const struct aco_option *opt,
736                          struct ast_variable *var, void *obj)
737 {
738         struct ast_sip_endpoint *endpoint = obj;
739
740         if (!strncmp(var->name, "call_group", 10)) {
741                 endpoint->pickup.callgroup = ast_get_group(var->value);
742         } else if (!strncmp(var->name, "pickup_group", 12)) {
743                 endpoint->pickup.pickupgroup = ast_get_group(var->value);
744         } else {
745                 return -1;
746         }
747
748         return 0;
749 }
750
751 static int callgroup_to_str(const void *obj, const intptr_t *args, char **buf)
752 {
753         const struct ast_sip_endpoint *endpoint = obj;
754
755         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
756                 return -1;
757         }
758
759         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.callgroup);
760         return 0;
761 }
762
763 static int pickupgroup_to_str(const void *obj, const intptr_t *args, char **buf)
764 {
765         const struct ast_sip_endpoint *endpoint = obj;
766
767         if (!(*buf = ast_calloc(MAX_OBJECT_FIELD, sizeof(char)))) {
768                 return -1;
769         }
770
771         ast_print_group(*buf, MAX_OBJECT_FIELD, endpoint->pickup.pickupgroup);
772         return 0;
773 }
774
775 static int named_groups_handler(const struct aco_option *opt,
776                                 struct ast_variable *var, void *obj)
777 {
778         struct ast_sip_endpoint *endpoint = obj;
779
780         if (!strncmp(var->name, "named_call_group", 16)) {
781                 if (ast_strlen_zero(var->value)) {
782                         endpoint->pickup.named_callgroups =
783                                 ast_unref_namedgroups(endpoint->pickup.named_callgroups);
784                 } else if (!(endpoint->pickup.named_callgroups =
785                       ast_get_namedgroups(var->value))) {
786                         return -1;
787                 }
788         } else if (!strncmp(var->name, "named_pickup_group", 18)) {
789                 if (ast_strlen_zero(var->value)) {
790                         endpoint->pickup.named_pickupgroups =
791                                 ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
792                 } else if (!(endpoint->pickup.named_pickupgroups =
793                       ast_get_namedgroups(var->value))) {
794                         return -1;
795                 }
796         } else {
797                 return -1;
798         }
799
800         return 0;
801 }
802
803 static int named_callgroups_to_str(const void *obj, const intptr_t *args, char **buf)
804 {
805         const struct ast_sip_endpoint *endpoint = obj;
806         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
807
808         ast_print_namedgroups(&str, endpoint->pickup.named_callgroups);
809         *buf = ast_strdup(ast_str_buffer(str));
810         return 0;
811 }
812
813 static int named_pickupgroups_to_str(const void *obj, const intptr_t *args, char **buf)
814 {
815         const struct ast_sip_endpoint *endpoint = obj;
816         RAII_VAR(struct ast_str *, str, ast_str_create(MAX_OBJECT_FIELD), ast_free);
817
818         ast_print_namedgroups(&str, endpoint->pickup.named_pickupgroups);
819         *buf = ast_strdup(ast_str_buffer(str));
820         return 0;
821 }
822
823 static int dtls_handler(const struct aco_option *opt,
824                          struct ast_variable *var, void *obj)
825 {
826         struct ast_sip_endpoint *endpoint = obj;
827         char *name = ast_strdupa(var->name);
828         char *front, *back, *buf = name;
829
830         /* strip out underscores in the name */
831         front = strtok_r(buf, "_", &back);
832         while (front) {
833                 int size = strlen(front);
834                 ast_copy_string(buf, front, size + 1);
835                 buf += size;
836                 front = strtok_r(NULL, "_", &back);
837         }
838
839         return ast_rtp_dtls_cfg_parse(&endpoint->media.rtp.dtls_cfg, name, var->value);
840 }
841
842 static int dtlsverify_to_str(const void *obj, const intptr_t *args, char **buf)
843 {
844         const struct ast_sip_endpoint *endpoint = obj;
845         *buf = ast_strdup(AST_YESNO(endpoint->media.rtp.dtls_cfg.verify));
846         return 0;
847 }
848
849 static int dtlsrekey_to_str(const void *obj, const intptr_t *args, char **buf)
850 {
851         const struct ast_sip_endpoint *endpoint = obj;
852
853         return ast_asprintf(
854                 buf, "%u", endpoint->media.rtp.dtls_cfg.rekey) >=0 ? 0 : -1;
855 }
856
857 static int dtlscertfile_to_str(const void *obj, const intptr_t *args, char **buf)
858 {
859         const struct ast_sip_endpoint *endpoint = obj;
860         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.certfile);
861         return 0;
862 }
863
864 static int dtlsprivatekey_to_str(const void *obj, const intptr_t *args, char **buf)
865 {
866         const struct ast_sip_endpoint *endpoint = obj;
867         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.pvtfile);
868         return 0;
869 }
870
871 static int dtlscipher_to_str(const void *obj, const intptr_t *args, char **buf)
872 {
873         const struct ast_sip_endpoint *endpoint = obj;
874         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cipher);
875         return 0;
876 }
877
878 static int dtlscafile_to_str(const void *obj, const intptr_t *args, char **buf)
879 {
880         const struct ast_sip_endpoint *endpoint = obj;
881         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.cafile);
882         return 0;
883 }
884
885 static int dtlscapath_to_str(const void *obj, const intptr_t *args, char **buf)
886 {
887         const struct ast_sip_endpoint *endpoint = obj;
888         *buf = ast_strdup(endpoint->media.rtp.dtls_cfg.capath);
889         return 0;
890 }
891
892 static const char *ast_rtp_dtls_setup_map[] = {
893         [AST_RTP_DTLS_SETUP_ACTIVE] = "active",
894         [AST_RTP_DTLS_SETUP_PASSIVE] = "passive",
895         [AST_RTP_DTLS_SETUP_ACTPASS] = "actpass",
896         [AST_RTP_DTLS_SETUP_HOLDCONN] = "holdconn",
897 };
898
899 static int dtlssetup_to_str(const void *obj, const intptr_t *args, char **buf)
900 {
901         const struct ast_sip_endpoint *endpoint = obj;
902         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.default_setup, ast_rtp_dtls_setup_map)) {
903                 *buf = ast_strdup(ast_rtp_dtls_setup_map[endpoint->media.rtp.dtls_cfg.default_setup]);
904         }
905         return 0;
906 }
907
908 static const char *ast_rtp_dtls_fingerprint_map[] = {
909         [AST_RTP_DTLS_HASH_SHA256] = "SHA-256",
910         [AST_RTP_DTLS_HASH_SHA1] = "SHA-1",
911 };
912
913 static int dtlsfingerprint_to_str(const void *obj, const intptr_t *args, char **buf)
914 {
915         const struct ast_sip_endpoint *endpoint = obj;
916         if (ARRAY_IN_BOUNDS(endpoint->media.rtp.dtls_cfg.hash, ast_rtp_dtls_fingerprint_map)) {
917                 *buf = ast_strdup(ast_rtp_dtls_fingerprint_map[endpoint->media.rtp.dtls_cfg.hash]);
918         }
919         return 0;
920 }
921
922 static int t38udptl_ec_handler(const struct aco_option *opt,
923         struct ast_variable *var, void *obj)
924 {
925         struct ast_sip_endpoint *endpoint = obj;
926
927         if (!strcmp(var->value, "none")) {
928                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_NONE;
929         } else if (!strcmp(var->value, "fec")) {
930                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_FEC;
931         } else if (!strcmp(var->value, "redundancy")) {
932                 endpoint->media.t38.error_correction = UDPTL_ERROR_CORRECTION_REDUNDANCY;
933         } else {
934                 return -1;
935         }
936
937         return 0;
938 }
939
940 static const char *ast_t38_ec_modes_map[] = {
941         [UDPTL_ERROR_CORRECTION_NONE] = "none",
942         [UDPTL_ERROR_CORRECTION_FEC] = "fec",
943         [UDPTL_ERROR_CORRECTION_REDUNDANCY] = "redundancy"
944 };
945
946 static int t38udptl_ec_to_str(const void *obj, const intptr_t *args, char **buf)
947 {
948         const struct ast_sip_endpoint *endpoint = obj;
949         if (ARRAY_IN_BOUNDS(endpoint->media.t38.error_correction, ast_t38_ec_modes_map)) {
950                 *buf = ast_strdup(ast_t38_ec_modes_map[
951                                           endpoint->media.t38.error_correction]);
952         }
953         return 0;
954 }
955
956 static int tos_handler(const struct aco_option *opt,
957         struct ast_variable *var, void *obj)
958 {
959         struct ast_sip_endpoint *endpoint = obj;
960         unsigned int value;
961
962         if (ast_str2tos(var->value, &value)) {
963                 ast_log(LOG_ERROR, "Error configuring endpoint '%s' - Could not "
964                         "interpret '%s' value '%s'\n",
965                         ast_sorcery_object_get_id(endpoint), var->name, var->value);
966                 return -1;
967         }
968
969         if (!strcmp(var->name, "tos_audio")) {
970                 endpoint->media.tos_audio = value;
971         } else if (!strcmp(var->name, "tos_video")) {
972                 endpoint->media.tos_video = value;
973         } else {
974                 /* If we reach this point, someone called the tos_handler when they shouldn't have. */
975                 ast_assert(0);
976                 return -1;
977         }
978         return 0;
979 }
980
981 static int tos_audio_to_str(const void *obj, const intptr_t *args, char **buf)
982 {
983         const struct ast_sip_endpoint *endpoint = obj;
984
985         if (ast_asprintf(buf, "%u", endpoint->media.tos_audio) == -1) {
986                 return -1;
987         }
988         return 0;
989 }
990
991 static int tos_video_to_str(const void *obj, const intptr_t *args, char **buf)
992 {
993         const struct ast_sip_endpoint *endpoint = obj;
994
995         if (ast_asprintf(buf, "%u", endpoint->media.tos_video) == -1) {
996                 return -1;
997         }
998         return 0;
999 }
1000
1001 static int set_var_handler(const struct aco_option *opt,
1002         struct ast_variable *var, void *obj)
1003 {
1004         struct ast_sip_endpoint *endpoint = obj;
1005         struct ast_variable *new_var;
1006         char *name;
1007         char *val;
1008
1009         if (ast_strlen_zero(var->value)) {
1010                 return 0;
1011         }
1012
1013         name = ast_strdupa(var->value);
1014         val = strchr(name, '=');
1015
1016         if (!val) {
1017                 return -1;
1018         }
1019
1020         *val++ = '\0';
1021
1022         if (!(new_var = ast_variable_new(name, val, ""))) {
1023                 return -1;
1024         }
1025
1026         ast_variable_list_append(&endpoint->channel_vars, new_var);
1027
1028         return 0;
1029 }
1030
1031 static int set_var_to_str(const void *obj, const intptr_t *args, char **buf)
1032 {
1033         struct ast_str *str = ast_str_create(MAX_OBJECT_FIELD);
1034         const struct ast_sip_endpoint *endpoint = obj;
1035         struct ast_variable *var;
1036
1037         for (var = endpoint->channel_vars; var; var = var->next) {
1038                 ast_str_append(&str, 0, "%s=%s,", var->name, var->value);
1039         }
1040
1041         *buf = ast_strdup(ast_str_truncate(str, -1));
1042         ast_free(str);
1043         return 0;
1044 }
1045
1046 static int set_var_to_vl(const void *obj, struct ast_variable **fields)
1047 {
1048         const struct ast_sip_endpoint *endpoint = obj;
1049         if (endpoint->channel_vars) {
1050                 *fields = ast_variables_dup(endpoint->channel_vars);
1051         }
1052         return 0;
1053 }
1054
1055 static int voicemail_extension_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
1056 {
1057         struct ast_sip_endpoint *endpoint = obj;
1058
1059         endpoint->subscription.mwi.voicemail_extension = ast_strdup(var->value);
1060
1061         return endpoint->subscription.mwi.voicemail_extension ? 0 : -1;
1062 }
1063
1064 static int voicemail_extension_to_str(const void *obj, const intptr_t *args, char **buf)
1065 {
1066         const struct ast_sip_endpoint *endpoint = obj;
1067
1068         *buf = ast_strdup(endpoint->subscription.mwi.voicemail_extension);
1069
1070         return 0;
1071 }
1072
1073 static void *sip_nat_hook_alloc(const char *name)
1074 {
1075         return ast_sorcery_generic_alloc(sizeof(struct ast_sip_nat_hook), NULL);
1076 }
1077
1078 /*! \brief Destructor function for persistent endpoint information */
1079 static void persistent_endpoint_destroy(void *obj)
1080 {
1081         struct sip_persistent_endpoint *persistent = obj;
1082
1083         ast_endpoint_shutdown(persistent->endpoint);
1084         ast_free(persistent->aors);
1085 }
1086
1087 /*! \brief Internal function which finds (or creates) persistent endpoint information */
1088 static struct ast_endpoint *persistent_endpoint_find_or_create(const struct ast_sip_endpoint *endpoint)
1089 {
1090         RAII_VAR(struct sip_persistent_endpoint *, persistent, NULL, ao2_cleanup);
1091         SCOPED_AO2LOCK(lock, persistent_endpoints);
1092
1093         if (!(persistent = ao2_find(persistent_endpoints, ast_sorcery_object_get_id(endpoint), OBJ_KEY | OBJ_NOLOCK))) {
1094                 if (!(persistent = ao2_alloc(sizeof(*persistent), persistent_endpoint_destroy))) {
1095                         return NULL;
1096                 }
1097
1098                 if (!(persistent->endpoint = ast_endpoint_create("PJSIP", ast_sorcery_object_get_id(endpoint)))) {
1099                         return NULL;
1100                 }
1101
1102                 persistent->aors = ast_strdup(endpoint->aors);
1103
1104                 if (ast_strlen_zero(persistent->aors)) {
1105                         ast_endpoint_set_state(persistent->endpoint, AST_ENDPOINT_UNKNOWN);
1106                 } else {
1107                         persistent_endpoint_update_state(persistent, NULL, 0);
1108                 }
1109
1110                 ao2_link_flags(persistent_endpoints, persistent, OBJ_NOLOCK);
1111         }
1112
1113         ao2_ref(persistent->endpoint, +1);
1114         return persistent->endpoint;
1115 }
1116
1117 /*! \brief Callback function for when an object is finalized */
1118 static int sip_endpoint_apply_handler(const struct ast_sorcery *sorcery, void *obj)
1119 {
1120         struct ast_sip_endpoint *endpoint = obj;
1121
1122         if (!(endpoint->persistent = persistent_endpoint_find_or_create(endpoint))) {
1123                 return -1;
1124         }
1125
1126         if (endpoint->extensions.timer.min_se < 90) {
1127                 ast_log(LOG_ERROR, "Session timer minimum expires time must be 90 or greater on endpoint '%s'\n",
1128                         ast_sorcery_object_get_id(endpoint));
1129                 return -1;
1130         } else if (endpoint->extensions.timer.sess_expires < endpoint->extensions.timer.min_se) {
1131                 ast_log(LOG_ERROR, "Session timer expires must be greater than minimum session expires time on endpoint '%s'\n",
1132                         ast_sorcery_object_get_id(endpoint));
1133                 return -1;
1134         }
1135
1136         return 0;
1137 }
1138
1139 const char *ast_sip_get_device_state(const struct ast_sip_endpoint *endpoint)
1140 {
1141         char device[MAX_OBJECT_FIELD];
1142
1143         snprintf(device, MAX_OBJECT_FIELD, "PJSIP/%s", ast_sorcery_object_get_id(endpoint));
1144         return ast_devstate2str(ast_device_state(device));
1145 }
1146
1147 struct ast_endpoint_snapshot *ast_sip_get_endpoint_snapshot(
1148         const struct ast_sip_endpoint *endpoint)
1149 {
1150         return ast_endpoint_latest_snapshot(
1151                 ast_endpoint_get_tech(endpoint->persistent),
1152                 ast_endpoint_get_resource(endpoint->persistent));
1153 }
1154
1155 int ast_sip_for_each_channel_snapshot(
1156         const struct ast_endpoint_snapshot *endpoint_snapshot,
1157         ao2_callback_fn on_channel_snapshot, void *arg)
1158 {
1159         int num, num_channels = endpoint_snapshot->num_channels;
1160
1161         if (!on_channel_snapshot || !num_channels) {
1162                 return 0;
1163         }
1164
1165         for (num = 0; num < num_channels; ++num) {
1166                 RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
1167                 int res;
1168
1169                 snapshot = ast_channel_snapshot_get_latest(endpoint_snapshot->channel_ids[num]);
1170                 if (!snapshot) {
1171                         continue;
1172                 }
1173
1174                 res = on_channel_snapshot(snapshot, arg, 0);
1175                 if (res) {
1176                         return -1;
1177                 }
1178         }
1179         return 0;
1180 }
1181
1182 int ast_sip_for_each_channel(
1183         const struct ast_sip_endpoint *endpoint,
1184         ao2_callback_fn on_channel_snapshot, void *arg)
1185 {
1186         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1187         return ast_sip_for_each_channel_snapshot(endpoint_snapshot, on_channel_snapshot, arg);
1188 }
1189
1190 static int active_channels_to_str_cb(void *object, void *arg, int flags)
1191 {
1192         const struct ast_channel_snapshot *snapshot = object;
1193         struct ast_str **buf = arg;
1194         ast_str_append(buf, 0, "%s,", snapshot->name);
1195         return 0;
1196 }
1197
1198 static void active_channels_to_str(const struct ast_sip_endpoint *endpoint,
1199                                    struct ast_str **str)
1200 {
1201
1202         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot,
1203                  ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1204
1205         if (endpoint_snapshot) {
1206                 return;
1207         }
1208
1209         ast_sip_for_each_channel_snapshot(endpoint_snapshot,
1210                                           active_channels_to_str_cb, str);
1211         ast_str_truncate(*str, -1);
1212 }
1213
1214 #define AMI_DEFAULT_STR_SIZE 512
1215
1216 struct ast_str *ast_sip_create_ami_event(const char *event, struct ast_sip_ami *ami)
1217 {
1218         struct ast_str *buf = ast_str_create(AMI_DEFAULT_STR_SIZE);
1219
1220         if (!(buf)) {
1221                 astman_send_error_va(ami->s, ami->m, "Unable create event "
1222                                      "for %s\n", event);
1223                 return NULL;
1224         }
1225
1226         ast_str_set(&buf, 0, "Event: %s\r\n", event);
1227         if (!ast_strlen_zero(ami->action_id)) {
1228                 ast_str_append(&buf, 0, "ActionID: %s\r\n", ami->action_id);
1229         }
1230         return buf;
1231 }
1232
1233 static void sip_sorcery_object_ami_set_type_name(const void *obj, struct ast_str **buf)
1234 {
1235         ast_str_append(buf, 0, "ObjectType: %s\r\n",
1236                        ast_sorcery_object_get_type(obj));
1237         ast_str_append(buf, 0, "ObjectName: %s\r\n",
1238                        ast_sorcery_object_get_id(obj));
1239 }
1240
1241 int ast_sip_sorcery_object_to_ami(const void *obj, struct ast_str **buf)
1242 {
1243         RAII_VAR(struct ast_variable *, objset, ast_sorcery_objectset_create2(
1244                          ast_sip_get_sorcery(), obj, AST_HANDLER_ONLY_STRING), ast_variables_destroy);
1245         struct ast_variable *i;
1246
1247         if (!objset) {
1248                 return -1;
1249         }
1250
1251         sip_sorcery_object_ami_set_type_name(obj, buf);
1252
1253         for (i = objset; i; i = i->next) {
1254                 RAII_VAR(char *, camel, ast_to_camel_case(i->name), ast_free);
1255                 ast_str_append(buf, 0, "%s: %s\r\n", camel, i->value);
1256         }
1257
1258         return 0;
1259 }
1260
1261 static int sip_endpoints_aors_ami(void *obj, void *arg, int flags)
1262 {
1263         struct ast_sip_aor *aor = obj;
1264         struct ast_str **buf = arg;
1265
1266         ast_str_append(buf, 0, "Contacts: ");
1267         ast_sip_for_each_contact(aor, ast_sip_contact_to_str, arg);
1268         ast_str_append(buf, 0, "\r\n");
1269
1270         return 0;
1271 }
1272
1273 static int sip_endpoint_to_ami(const struct ast_sip_endpoint *endpoint,
1274                                struct ast_str **buf)
1275 {
1276         if (ast_sip_sorcery_object_to_ami(endpoint, buf)) {
1277                 return -1;
1278         }
1279
1280         ast_str_append(buf, 0, "DeviceState: %s\r\n",
1281                        ast_sip_get_device_state(endpoint));
1282
1283         ast_str_append(buf, 0, "ActiveChannels: ");
1284         active_channels_to_str(endpoint, buf);
1285         ast_str_append(buf, 0, "\r\n");
1286
1287         return 0;
1288 }
1289
1290 static int format_ami_endpoint(const struct ast_sip_endpoint *endpoint,
1291                                struct ast_sip_ami *ami)
1292 {
1293         RAII_VAR(struct ast_str *, buf,
1294                  ast_sip_create_ami_event("EndpointDetail", ami), ast_free);
1295
1296         if (!buf) {
1297                 return -1;
1298         }
1299
1300         sip_endpoint_to_ami(endpoint, &buf);
1301         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1302         return 0;
1303 }
1304
1305 #define AMI_SHOW_ENDPOINTS "PJSIPShowEndpoints"
1306 #define AMI_SHOW_ENDPOINT "PJSIPShowEndpoint"
1307
1308 static int ami_show_endpoint(struct mansession *s, const struct message *m)
1309 {
1310         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"),
1311                 .count = 0, };
1312         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1313         const char *endpoint_name = astman_get_header(m, "Endpoint");
1314         int count = 0;
1315
1316         if (ast_strlen_zero(endpoint_name)) {
1317                 astman_send_error_va(s, m, "%s requires an endpoint name\n",
1318                         AMI_SHOW_ENDPOINT);
1319                 return 0;
1320         }
1321
1322         if (!strncasecmp(endpoint_name, "pjsip/", 6)) {
1323                 endpoint_name += 6;
1324         }
1325
1326         if (!(endpoint = ast_sorcery_retrieve_by_id(
1327                       ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1328                 astman_send_error_va(s, m, "Unable to retrieve endpoint %s\n",
1329                         endpoint_name);
1330                 return 0;
1331         }
1332
1333         astman_send_listack(s, m, "Following are Events for each object associated with the the Endpoint",
1334                 "start");
1335
1336         /* the endpoint detail needs to always come first so apply as such */
1337         if (format_ami_endpoint(endpoint, &ami) ||
1338             ast_sip_format_endpoint_ami(endpoint, &ami, &count)) {
1339                 astman_send_error_va(s, m, "Unable to format endpoint %s\n",
1340                         endpoint_name);
1341         }
1342
1343         astman_send_list_complete_start(s, m, "EndpointDetailComplete", ami.count + 1);
1344         astman_send_list_complete_end(s);
1345
1346         return 0;
1347 }
1348
1349 static int format_str_append_auth(const struct ast_sip_auth_vector *auths,
1350                                   struct ast_str **buf)
1351 {
1352         char *str = NULL;
1353         if (ast_sip_auths_to_str(auths, &str)) {
1354                 return -1;
1355         }
1356         ast_str_append(buf, 0, "%s", str ? str : "");
1357         ast_free(str);
1358         return 0;
1359 }
1360
1361 static int format_ami_endpoints(void *obj, void *arg, int flags)
1362 {
1363
1364         struct ast_sip_endpoint *endpoint = obj;
1365         struct ast_sip_ami *ami = arg;
1366         RAII_VAR(struct ast_str *, buf,
1367                  ast_sip_create_ami_event("EndpointList", ami), ast_free);
1368
1369         if (!buf) {
1370                 return CMP_STOP;
1371         }
1372
1373         sip_sorcery_object_ami_set_type_name(endpoint, &buf);
1374         ast_str_append(&buf, 0, "Transport: %s\r\n",
1375                        endpoint->transport);
1376         ast_str_append(&buf, 0, "Aor: %s\r\n",
1377                        endpoint->aors);
1378
1379         ast_str_append(&buf, 0, "Auths: ");
1380         format_str_append_auth(&endpoint->inbound_auths, &buf);
1381         ast_str_append(&buf, 0, "\r\n");
1382
1383         ast_str_append(&buf, 0, "OutboundAuths: ");
1384         format_str_append_auth(&endpoint->outbound_auths, &buf);
1385         ast_str_append(&buf, 0, "\r\n");
1386
1387         ast_sip_for_each_aor(endpoint->aors,
1388                              sip_endpoints_aors_ami, &buf);
1389
1390         ast_str_append(&buf, 0, "DeviceState: %s\r\n",
1391                        ast_sip_get_device_state(endpoint));
1392
1393         ast_str_append(&buf, 0, "ActiveChannels: ");
1394         active_channels_to_str(endpoint, &buf);
1395         ast_str_append(&buf, 0, "\r\n");
1396
1397         astman_append(ami->s, "%s\r\n", ast_str_buffer(buf));
1398         return 0;
1399 }
1400
1401 static int ami_show_endpoints(struct mansession *s, const struct message *m)
1402 {
1403         struct ast_sip_ami ami = { .s = s, .m = m, .action_id = astman_get_header(m, "ActionID"), };
1404         RAII_VAR(struct ao2_container *, endpoints, NULL, ao2_cleanup);
1405         int num;
1406
1407         endpoints = ast_sip_get_endpoints();
1408         if (!endpoints) {
1409                 astman_send_error(s, m, "Could not get endpoints\n");
1410                 return 0;
1411         }
1412
1413         if (!(num = ao2_container_count(endpoints))) {
1414                 astman_send_error(s, m, "No endpoints found\n");
1415                 return 0;
1416         }
1417
1418         astman_send_listack(s, m, "A listing of Endpoints follows, presented as EndpointList events",
1419                 "start");
1420
1421         ao2_callback(endpoints, OBJ_NODATA, format_ami_endpoints, &ami);
1422
1423         astman_send_list_complete_start(s, m, "EndpointListComplete", num);
1424         astman_send_list_complete_end(s);
1425         return 0;
1426 }
1427
1428 static struct ao2_container *cli_endpoint_get_container(const char *regex)
1429 {
1430         RAII_VAR(struct ao2_container *, container, NULL, ao2_cleanup);
1431         struct ao2_container *s_container;
1432
1433         container = ast_sorcery_retrieve_by_regex(sip_sorcery, "endpoint", regex);
1434         if (!container) {
1435                 return NULL;
1436         }
1437
1438         s_container = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_NOLOCK, 0,
1439                 (void *)ast_sorcery_object_id_sort, (void *)ast_sorcery_object_id_compare);
1440         if (!s_container) {
1441                 return NULL;
1442         }
1443
1444         if (ao2_container_dup(s_container, container, 0)) {
1445                 ao2_ref(s_container, -1);
1446                 return NULL;
1447         }
1448
1449         return s_container;
1450 }
1451
1452 static int cli_endpoint_iterate(void *obj, ao2_callback_fn callback, void *args)
1453 {
1454         ao2_callback(obj, OBJ_NODATA, callback, args);
1455
1456         return 0;
1457 }
1458
1459 static void *cli_endpoint_retrieve_by_id(const char *id)
1460 {
1461         return ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", id);
1462 }
1463
1464 static void cli_endpoint_print_child_header(char *type, struct ast_sip_cli_context *context)
1465 {
1466         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1467
1468         formatter_entry = ast_sip_lookup_cli_formatter(type);
1469         if (formatter_entry) {
1470                 formatter_entry->print_header(NULL, context, 0);
1471         }
1472 }
1473
1474 static int cli_endpoint_print_header(void *obj, void *arg, int flags)
1475 {
1476         struct ast_sip_cli_context *context = arg;
1477
1478         ast_assert(context->output_buffer != NULL);
1479
1480         ast_str_append(&context->output_buffer, 0,
1481                         " Endpoint:  <Endpoint/CID.....................................>  <State.....>  <Channels.>\n");
1482
1483         if (context->recurse) {
1484                 context->indent_level++;
1485                 cli_endpoint_print_child_header("auth", context);
1486                 cli_endpoint_print_child_header("aor", context);
1487                 cli_endpoint_print_child_header("transport", context);
1488                 cli_endpoint_print_child_header("identify", context);
1489                 cli_endpoint_print_child_header("channel", context);
1490                 context->indent_level--;
1491         }
1492
1493         return 0;
1494 }
1495
1496 static void cli_endpoint_print_child_body(char *type, const void *obj, struct ast_sip_cli_context *context)
1497 {
1498         RAII_VAR(struct ast_sip_cli_formatter_entry *, formatter_entry, NULL, ao2_cleanup);
1499
1500         formatter_entry = ast_sip_lookup_cli_formatter(type);
1501         if (formatter_entry) {
1502                 formatter_entry->iterate((void *)obj, formatter_entry->print_body, context);
1503         }
1504 }
1505
1506 static int cli_endpoint_print_body(void *obj, void *arg, int flags)
1507 {
1508         struct ast_sip_endpoint *endpoint = obj;
1509         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, ast_sip_get_endpoint_snapshot(endpoint), ao2_cleanup);
1510         struct ast_sip_cli_context *context = arg;
1511         const char *id = ast_sorcery_object_get_id(endpoint);
1512         char *print_name = NULL;
1513         int print_name_len;
1514         char *number = S_COR(endpoint->id.self.number.valid,
1515                 endpoint->id.self.number.str, NULL);
1516         int indent;
1517         int flexwidth;
1518
1519         ast_assert(context->output_buffer != NULL);
1520
1521         if (number) {
1522                 print_name_len = strlen(id) + strlen(number) + 2;
1523                 if (!(print_name = alloca(print_name_len))) {
1524                         return -1;
1525                 }
1526                 snprintf(print_name, print_name_len, "%s/%s", id, number);
1527         }
1528
1529         indent = CLI_INDENT_TO_SPACES(context->indent_level);
1530         flexwidth = CLI_LAST_TABSTOP - indent - 2;
1531
1532         ast_str_append(&context->output_buffer, 0, "%*s:  %-*.*s  %-12.12s  %d of %.0f\n",
1533                 indent, "Endpoint",
1534                 flexwidth, flexwidth, print_name ? print_name : id,
1535                 ast_sip_get_device_state(endpoint),
1536                 endpoint_snapshot->num_channels,
1537                 (double) endpoint->devicestate_busy_at ? endpoint->devicestate_busy_at :
1538                                                                                                                 INFINITY
1539                                                                                                                 );
1540
1541         if (context->recurse) {
1542                 context->indent_level++;
1543
1544                 context->auth_direction = "Out";
1545                 cli_endpoint_print_child_body("auth", &endpoint->outbound_auths, context);
1546                 context->auth_direction = "In";
1547                 cli_endpoint_print_child_body("auth", &endpoint->inbound_auths, context);
1548
1549                 cli_endpoint_print_child_body("aor", endpoint->aors, context);
1550                 cli_endpoint_print_child_body("transport", endpoint, context);
1551                 cli_endpoint_print_child_body("identify", endpoint, context);
1552                 cli_endpoint_print_child_body("channel", endpoint, context);
1553
1554                 context->indent_level--;
1555
1556                 if (context->indent_level == 0) {
1557                         ast_str_append(&context->output_buffer, 0, "\n");
1558                 }
1559         }
1560
1561         if (context->show_details || (context->show_details_only_level_0 && context->indent_level == 0)) {
1562                 ast_str_append(&context->output_buffer, 0, "\n");
1563                 ast_sip_cli_print_sorcery_objectset(endpoint, context, 0);
1564         }
1565
1566         return 0;
1567 }
1568
1569 static struct ast_cli_entry cli_commands[] = {
1570         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "List PJSIP Endpoints",
1571                 .command = "pjsip list endpoints",
1572                 .usage = "Usage: pjsip list endpoints [ like <pattern> ]\n"
1573                                 "       List the configured PJSIP endpoints\n"
1574                                 "       Optional regular expression pattern is used to filter the list.\n"),
1575         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoints",
1576                 .command = "pjsip show endpoints",
1577                 .usage = "Usage: pjsip show endpoints [ like <pattern> ]\n"
1578                                 "       List(detailed) the configured PJSIP endpoints\n"
1579                                 "       Optional regular expression pattern is used to filter the list.\n"),
1580         AST_CLI_DEFINE(ast_sip_cli_traverse_objects, "Show PJSIP Endpoint",
1581                 .command = "pjsip show endpoint",
1582                 .usage = "Usage: pjsip show endpoint <id>\n"
1583                                  "       Show the configured PJSIP endpoint\n"),
1584 };
1585
1586 struct ast_sip_cli_formatter_entry *channel_formatter;
1587 struct ast_sip_cli_formatter_entry *endpoint_formatter;
1588
1589 int ast_res_pjsip_initialize_configuration(void)
1590 {
1591         if (ast_manager_register_xml(AMI_SHOW_ENDPOINTS, EVENT_FLAG_SYSTEM, ami_show_endpoints) ||
1592             ast_manager_register_xml(AMI_SHOW_ENDPOINT, EVENT_FLAG_SYSTEM, ami_show_endpoint)) {
1593                 return -1;
1594         }
1595
1596         if (!(persistent_endpoints = ao2_container_alloc(PERSISTENT_BUCKETS, persistent_endpoint_hash, persistent_endpoint_cmp))) {
1597                 return -1;
1598         }
1599
1600         if (!(sip_sorcery = ast_sorcery_open())) {
1601                 ast_log(LOG_ERROR, "Failed to open SIP sorcery failed to open\n");
1602                 return -1;
1603         }
1604
1605         ast_sip_initialize_cli();
1606
1607         if (ast_sip_initialize_sorcery_auth()) {
1608                 ast_log(LOG_ERROR, "Failed to register SIP authentication support\n");
1609                 ast_sorcery_unref(sip_sorcery);
1610                 sip_sorcery = NULL;
1611                 return -1;
1612         }
1613
1614         ast_sorcery_apply_default(sip_sorcery, "endpoint", "config", "pjsip.conf,criteria=type=endpoint");
1615         ast_sorcery_apply_default(sip_sorcery, "nat_hook", "memory", NULL);
1616
1617         if (ast_sorcery_object_register(sip_sorcery, "endpoint", ast_sip_endpoint_alloc, NULL, sip_endpoint_apply_handler)) {
1618                 ast_log(LOG_ERROR, "Failed to register SIP endpoint object with sorcery\n");
1619                 ast_sorcery_unref(sip_sorcery);
1620                 sip_sorcery = NULL;
1621                 return -1;
1622         }
1623
1624         if (ast_sorcery_internal_object_register(sip_sorcery, "nat_hook", sip_nat_hook_alloc, NULL, NULL)) {
1625                 ast_log(LOG_ERROR, "Failed to register nat_hook\n");
1626         }
1627
1628         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "type", "", OPT_NOOP_T, 0, 0);
1629         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "context", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, context));
1630         ast_sorcery_object_field_register_alias(sip_sorcery, "endpoint", "disallow", "", OPT_CODEC_T, 0, FLDSET(struct ast_sip_endpoint, media.codecs));
1631         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow", "", OPT_CODEC_T, 1, FLDSET(struct ast_sip_endpoint, media.codecs));
1632         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtmf_mode", "rfc4733", dtmf_handler, dtmf_to_str, NULL, 0, 0);
1633         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ipv6));
1634         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_symmetric", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.symmetric));
1635         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "ice_support", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.ice_support));
1636         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_ptime", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_ptime));
1637         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_rport", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.force_rport));
1638         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rewrite_contact", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, nat.rewrite_contact));
1639         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "transport", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, transport));
1640         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "outbound_proxy", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, outbound_proxy));
1641         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_suggest", "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, mohsuggest));
1642         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "100rel", "yes", prack_handler, prack_to_str, NULL, 0, 0);
1643         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "timers", "yes", timers_handler, timers_to_str, NULL, 0, 0);
1644         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));
1645         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));
1646         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "auth", "", inbound_auth_handler, inbound_auths_to_str, NULL, 0, 0);
1647         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "outbound_auth", "", outbound_auth_handler, outbound_auths_to_str, NULL, 0, 0);
1648         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aors", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, aors));
1649         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "media_address", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.address));
1650         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));
1651         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "identify_by", "username", ident_handler, ident_to_str, NULL, 0, 0);
1652         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "direct_media", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.direct_media.enabled));
1653         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);
1654         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);
1655         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);
1656         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));
1657         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid", "", caller_id_handler, caller_id_to_str, NULL, 0, 0);
1658         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);
1659         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "callerid_tag", "", caller_id_tag_handler, caller_id_tag_to_str, NULL, 0, 0);
1660         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_inbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_inbound));
1661         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "trust_id_outbound", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.trust_outbound));
1662         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_pai", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_pai));
1663         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_rpid", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_rpid));
1664         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rpid_immediate", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.rpid_immediate));
1665         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "send_diversion", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, id.send_diversion));
1666         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mailboxes", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.mailboxes));
1667         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "voicemail_extension", "", voicemail_extension_handler, voicemail_extension_to_str, NULL, 0, 0);
1668         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "aggregate_mwi", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.aggregate));
1669         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_subscribe_replaces_unsolicited", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.mwi.subscribe_replaces_unsolicited));
1670         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "media_encryption", "no", media_encryption_handler, media_encryption_to_str, NULL, 0, 0);
1671         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "use_avpf", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.use_avpf));
1672         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "force_avp", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.rtp.force_avp));
1673         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));
1674         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_keepalive", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.keepalive));
1675         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_timeout", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.rtp.timeout));
1676         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));
1677         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "one_touch_recording", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, info.recording.enabled));
1678         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "inband_progress", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, inband_progress));
1679         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "call_group", "", group_handler, callgroup_to_str, NULL, 0, 0);
1680         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "pickup_group", "", group_handler, pickupgroup_to_str, NULL, 0, 0);
1681         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_call_group", "", named_groups_handler, named_callgroups_to_str, NULL, 0, 0);
1682         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "named_pickup_group", "", named_groups_handler, named_pickupgroups_to_str, NULL, 0, 0);
1683         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));
1684         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.enabled));
1685         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "t38_udptl_ec", "none", t38udptl_ec_handler, t38udptl_ec_to_str, NULL, 0, 0);
1686         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_maxdatagram", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.t38.maxdatagram));
1687         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "fax_detect", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, faxdetect));
1688         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_nat", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.nat));
1689         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "t38_udptl_ipv6", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, media.t38.ipv6));
1690         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "tone_zone", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, zone));
1691         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "language", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, language));
1692         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_on_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.onfeature));
1693         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "record_off_feature", "automixmon", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, info.recording.offfeature));
1694         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_transfer", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, allowtransfer));
1695         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "user_eq_phone", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, usereqphone));
1696         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "moh_passthrough", "no", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, moh_passthrough));
1697         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_owner", "-", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpowner));
1698         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sdp_session", "Asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.sdpsession));
1699         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_audio", "0", tos_handler, tos_audio_to_str, NULL, 0, 0);
1700         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "tos_video", "0", tos_handler, tos_video_to_str, NULL, 0, 0);
1701         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_audio", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_audio));
1702         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "cos_video", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, media.cos_video));
1703         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "allow_subscribe", "yes", OPT_BOOL_T, 1, FLDSET(struct ast_sip_endpoint, subscription.allow));
1704         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "sub_min_expiry", "0", OPT_UINT_T, 0, FLDSET(struct ast_sip_endpoint, subscription.minexpiry));
1705         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromuser));
1706         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "from_domain", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, fromdomain));
1707         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "mwi_from_user", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, subscription.mwi.fromuser));
1708         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "rtp_engine", "asterisk", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, media.rtp.engine));
1709         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_verify", "no", dtls_handler, dtlsverify_to_str, NULL, 0, 0);
1710         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_rekey", "0", dtls_handler, dtlsrekey_to_str, NULL, 0, 0);
1711         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cert_file", "", dtls_handler, dtlscertfile_to_str, NULL, 0, 0);
1712         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_private_key", "", dtls_handler, dtlsprivatekey_to_str, NULL, 0, 0);
1713         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_cipher", "", dtls_handler, dtlscipher_to_str, NULL, 0, 0);
1714         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_file", "", dtls_handler, dtlscafile_to_str, NULL, 0, 0);
1715         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_ca_path", "", dtls_handler, dtlscapath_to_str, NULL, 0, 0);
1716         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_setup", "", dtls_handler, dtlssetup_to_str, NULL, 0, 0);
1717         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "dtls_fingerprint", "", dtls_handler, dtlsfingerprint_to_str, NULL, 0, 0);
1718         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));
1719         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));
1720         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));
1721         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "redirect_method", "user", redirect_handler, NULL, NULL, 0, 0);
1722         ast_sorcery_object_field_register_custom(sip_sorcery, "endpoint", "set_var", "", set_var_handler, set_var_to_str, set_var_to_vl, 0, 0);
1723         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "message_context", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, message_context));
1724         ast_sorcery_object_field_register(sip_sorcery, "endpoint", "accountcode", "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_sip_endpoint, accountcode));
1725
1726         if (ast_sip_initialize_sorcery_transport()) {
1727                 ast_log(LOG_ERROR, "Failed to register SIP transport support with sorcery\n");
1728                 ast_sorcery_unref(sip_sorcery);
1729                 sip_sorcery = NULL;
1730                 return -1;
1731         }
1732
1733         if (ast_sip_initialize_sorcery_location()) {
1734                 ast_log(LOG_ERROR, "Failed to register SIP location support with sorcery\n");
1735                 ast_sorcery_unref(sip_sorcery);
1736                 sip_sorcery = NULL;
1737                 return -1;
1738         }
1739
1740         if (ast_sip_initialize_sorcery_qualify()) {
1741                 ast_log(LOG_ERROR, "Failed to register SIP qualify support with sorcery\n");
1742                 ast_sorcery_unref(sip_sorcery);
1743                 sip_sorcery = NULL;
1744                 return -1;
1745         }
1746
1747         ast_sorcery_observer_add(sip_sorcery, "endpoint", &endpoint_observers);
1748         ast_sorcery_observer_add(sip_sorcery, "contact", &state_contact_observer);
1749         ast_sorcery_observer_add(sip_sorcery, CONTACT_STATUS, &state_contact_status_observer);
1750
1751         if (ast_sip_initialize_sorcery_domain_alias()) {
1752                 ast_log(LOG_ERROR, "Failed to register SIP domain aliases support with sorcery\n");
1753                 ast_sorcery_unref(sip_sorcery);
1754                 sip_sorcery = NULL;
1755                 return -1;
1756         }
1757
1758         if (ast_sip_initialize_sorcery_global()) {
1759                 ast_log(LOG_ERROR, "Failed to register SIP Global support\n");
1760                 ast_sorcery_unref(sip_sorcery);
1761                 sip_sorcery = NULL;
1762                 return -1;
1763         }
1764
1765         endpoint_formatter = ao2_alloc(sizeof(struct ast_sip_cli_formatter_entry), NULL);
1766         if (!endpoint_formatter) {
1767                 ast_log(LOG_ERROR, "Unable to allocate memory for endpoint_formatter\n");
1768                 ast_sorcery_unref(sip_sorcery);
1769                 sip_sorcery = NULL;
1770                 return -1;
1771         }
1772         endpoint_formatter->name = "endpoint";
1773         endpoint_formatter->print_header = cli_endpoint_print_header;
1774         endpoint_formatter->print_body = cli_endpoint_print_body;
1775         endpoint_formatter->get_container = cli_endpoint_get_container;
1776         endpoint_formatter->iterate = cli_endpoint_iterate;
1777         endpoint_formatter->retrieve_by_id = cli_endpoint_retrieve_by_id;
1778         endpoint_formatter->get_id = ast_sorcery_object_get_id;
1779
1780         ast_sip_register_cli_formatter(endpoint_formatter);
1781         ast_cli_register_multiple(cli_commands, ARRAY_LEN(cli_commands));
1782
1783         ast_sorcery_load(sip_sorcery);
1784
1785         return 0;
1786 }
1787
1788 void ast_res_pjsip_destroy_configuration(void)
1789 {
1790         if (!sip_sorcery) {
1791                 return;
1792         }
1793
1794         ast_sorcery_observer_remove(sip_sorcery, CONTACT_STATUS, &state_contact_status_observer);
1795         ast_sorcery_observer_remove(sip_sorcery, "contact", &state_contact_observer);
1796         ast_sip_destroy_sorcery_global();
1797         ast_sip_destroy_sorcery_location();
1798         ast_sip_destroy_sorcery_auth();
1799         ast_sip_destroy_sorcery_transport();
1800         ast_sorcery_unref(sip_sorcery);
1801         sip_sorcery = NULL;
1802         ast_manager_unregister(AMI_SHOW_ENDPOINT);
1803         ast_manager_unregister(AMI_SHOW_ENDPOINTS);
1804         ast_cli_unregister_multiple(cli_commands, ARRAY_LEN(cli_commands));
1805         ast_sip_unregister_cli_formatter(endpoint_formatter);
1806         ast_sip_destroy_cli();
1807         ao2_cleanup(persistent_endpoints);
1808 }
1809
1810 int ast_res_pjsip_reload_configuration(void)
1811 {
1812         if (sip_sorcery) {
1813                 ast_sorcery_reload(sip_sorcery);
1814         }
1815         return 0;
1816 }
1817
1818 static void subscription_configuration_destroy(struct ast_sip_endpoint_subscription_configuration *subscription)
1819 {
1820         ast_string_field_free_memory(&subscription->mwi);
1821         ast_free(subscription->mwi.voicemail_extension);
1822 }
1823
1824 static void info_configuration_destroy(struct ast_sip_endpoint_info_configuration *info)
1825 {
1826         ast_string_field_free_memory(&info->recording);
1827 }
1828
1829 static void media_configuration_destroy(struct ast_sip_endpoint_media_configuration *media)
1830 {
1831         ast_string_field_free_memory(&media->rtp);
1832         ast_string_field_free_memory(media);
1833 }
1834
1835 static void endpoint_destructor(void* obj)
1836 {
1837         struct ast_sip_endpoint *endpoint = obj;
1838
1839         ast_string_field_free_memory(endpoint);
1840
1841         ao2_ref(endpoint->media.codecs, -1);
1842         subscription_configuration_destroy(&endpoint->subscription);
1843         info_configuration_destroy(&endpoint->info);
1844         media_configuration_destroy(&endpoint->media);
1845         ast_sip_auth_vector_destroy(&endpoint->inbound_auths);
1846         ast_sip_auth_vector_destroy(&endpoint->outbound_auths);
1847         ast_party_id_free(&endpoint->id.self);
1848         endpoint->pickup.named_callgroups = ast_unref_namedgroups(endpoint->pickup.named_callgroups);
1849         endpoint->pickup.named_pickupgroups = ast_unref_namedgroups(endpoint->pickup.named_pickupgroups);
1850         ao2_cleanup(endpoint->persistent);
1851         ast_variables_destroy(endpoint->channel_vars);
1852 }
1853
1854 static int init_subscription_configuration(struct ast_sip_endpoint_subscription_configuration *subscription)
1855 {
1856         return ast_string_field_init(&subscription->mwi, 64);
1857 }
1858
1859 static int init_info_configuration(struct ast_sip_endpoint_info_configuration *info)
1860 {
1861         return ast_string_field_init(&info->recording, 32);
1862 }
1863
1864 static int init_media_configuration(struct ast_sip_endpoint_media_configuration *media)
1865 {
1866         return ast_string_field_init(media, 64) || ast_string_field_init(&media->rtp, 32);
1867 }
1868
1869 void *ast_sip_endpoint_alloc(const char *name)
1870 {
1871         struct ast_sip_endpoint *endpoint = ast_sorcery_generic_alloc(sizeof(*endpoint), endpoint_destructor);
1872         if (!endpoint) {
1873                 return NULL;
1874         }
1875         if (ast_string_field_init(endpoint, 64)) {
1876                 ao2_cleanup(endpoint);
1877                 return NULL;
1878         }
1879         if (!(endpoint->media.codecs = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1880                 ao2_cleanup(endpoint);
1881                 return NULL;
1882         }
1883         if (init_subscription_configuration(&endpoint->subscription)) {
1884                 ao2_cleanup(endpoint);
1885                 return NULL;
1886         }
1887         if (init_info_configuration(&endpoint->info)) {
1888                 ao2_cleanup(endpoint);
1889                 return NULL;
1890         }
1891         if (init_media_configuration(&endpoint->media)) {
1892                 ao2_cleanup(endpoint);
1893                 return NULL;
1894         }
1895         ast_party_id_init(&endpoint->id.self);
1896         return endpoint;
1897 }
1898
1899 struct ao2_container *ast_sip_get_endpoints(void)
1900 {
1901         struct ao2_container *endpoints;
1902
1903         endpoints = ast_sorcery_retrieve_by_fields(sip_sorcery, "endpoint", AST_RETRIEVE_FLAG_MULTIPLE | AST_RETRIEVE_FLAG_ALL, NULL);
1904
1905         return endpoints;
1906 }
1907
1908 struct ast_sip_endpoint *ast_sip_default_outbound_endpoint(void)
1909 {
1910         RAII_VAR(char *, name, ast_sip_global_default_outbound_endpoint(), ast_free);
1911         return ast_strlen_zero(name) ? NULL : ast_sorcery_retrieve_by_id(
1912                 sip_sorcery, "endpoint", name);
1913 }
1914
1915 int ast_sip_retrieve_auths(const struct ast_sip_auth_vector *auths, struct ast_sip_auth **out)
1916 {
1917         int i;
1918
1919         for (i = 0; i < AST_VECTOR_SIZE(auths); ++i) {
1920                 /* Using AST_VECTOR_GET is safe since the vector is immutable */
1921                 const char *name = AST_VECTOR_GET(auths, i);
1922                 out[i] = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), SIP_SORCERY_AUTH_TYPE, name);
1923                 if (!out[i]) {
1924                         ast_log(LOG_NOTICE, "Couldn't find auth '%s'. Cannot authenticate\n", name);
1925                         return -1;
1926                 }
1927         }
1928
1929         return 0;
1930 }
1931
1932 void ast_sip_cleanup_auths(struct ast_sip_auth *auths[], size_t num_auths)
1933 {
1934         int i;
1935         for (i = 0; i < num_auths; ++i) {
1936                 ao2_cleanup(auths[i]);
1937         }
1938 }
1939
1940 struct ast_sorcery *ast_sip_get_sorcery(void)
1941 {
1942         return sip_sorcery;
1943 }