json: Fix off-nominal json ref counting issues.
[asterisk/asterisk.git] / main / sorcery.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2012 - 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Sorcery Data Access Layer API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include "asterisk/logger.h"
35 #include "asterisk/sorcery.h"
36 #include "asterisk/astobj2.h"
37 #include "asterisk/format.h"
38 #include "asterisk/format_cap.h"
39 #include "asterisk/strings.h"
40 #include "asterisk/config_options.h"
41 #include "asterisk/netsock2.h"
42 #include "asterisk/module.h"
43 #include "asterisk/taskprocessor.h"
44 #include "asterisk/threadpool.h"
45 #include "asterisk/json.h"
46 #include "asterisk/format_pref.h"
47
48 /* To prevent DEBUG_FD_LEAKS from interfering with things we undef open and close */
49 #undef open
50 #undef close
51
52 /*! \brief Number of buckets for wizards (should be prime for performance reasons) */
53 #define WIZARD_BUCKETS 7
54
55 /*! \brief Number of buckets for types (should be prime for performance reasons) */
56 #define TYPE_BUCKETS 53
57
58 /*! \brief Number of buckets for instances (should be prime for performance reasons) */
59 #define INSTANCE_BUCKETS 17
60
61 /*! \brief Thread pool for observers */
62 static struct ast_threadpool *threadpool;
63
64 /*! \brief Structure for internal sorcery object information */
65 struct ast_sorcery_object {
66         /*! \brief Unique identifier of this object */
67         char *id;
68
69         /*! \brief Type of object */
70         char type[MAX_OBJECT_TYPE];
71
72         /*! \brief Optional object destructor */
73         ao2_destructor_fn destructor;
74
75         /*! \brief Extended object fields */
76         struct ast_variable *extended;
77 };
78
79 /*! \brief Structure for registered object type */
80 struct ast_sorcery_object_type {
81         /*! \brief Unique name of the object type */
82         char name[MAX_OBJECT_TYPE];
83
84         /*! \brief Optional transformation callback */
85         sorcery_transform_handler transform;
86
87         /*! \brief Optional object set apply callback */
88         sorcery_apply_handler apply;
89
90         /*! \brief Optional object copy callback */
91         sorcery_copy_handler copy;
92
93         /*! \brief Optional object diff callback */
94         sorcery_diff_handler diff;
95
96         /*! \brief Wizard instances */
97         struct ao2_container *wizards;
98
99         /*! \brief Object fields */
100         struct ao2_container *fields;
101
102         /*! \brief Configuration framework general information */
103         struct aco_info *info;
104
105         /*! \brief Configuration framework file information */
106         struct aco_file *file;
107
108         /*! \brief Type details */
109         struct aco_type type;
110
111         /*! \brief Observers */
112         struct ao2_container *observers;
113
114         /*! \brief Serializer for observers */
115         struct ast_taskprocessor *serializer;
116
117         /*! \brief Specifies if object type is reloadable or not */
118         unsigned int reloadable:1;
119 };
120
121 /*! \brief Structure for registered object type observer */
122 struct ast_sorcery_object_type_observer {
123         /*! \brief Pointer to the observer implementation */
124         const struct ast_sorcery_observer *callbacks;
125 };
126
127 /*! \brief Structure used for observer invocations */
128 struct sorcery_observer_invocation {
129         /*! \brief Pointer to the object type */
130         struct ast_sorcery_object_type *object_type;
131
132         /*! \brief Pointer to the object */
133         void *object;
134 };
135
136 /*! \brief Structure for registered object field */
137 struct ast_sorcery_object_field {
138         /*! \brief Name of the field */
139         char name[MAX_OBJECT_FIELD];
140
141         /*! \brief Callback function for translation of a single value */
142         sorcery_field_handler handler;
143
144         /*! \brief Callback function for translation of multiple values */
145         sorcery_fields_handler multiple_handler;
146
147         /*! \brief Position of the field */
148         intptr_t args[];
149 };
150
151 /*! \brief Structure for a wizard instance which operates on objects */
152 struct ast_sorcery_object_wizard {
153         /*! \brief Wizard interface itself */
154         struct ast_sorcery_wizard *wizard;
155
156         /*! \brief Unique data for the wizard */
157         void *data;
158
159         /*! \brief Wizard is acting as an object cache */
160         unsigned int caching:1;
161 };
162
163 /*! \brief Full structure for sorcery */
164 struct ast_sorcery {
165         /*! \brief Container for known object types */
166         struct ao2_container *types;
167         /*! \brief The name of the module owning this sorcery instance */
168         char module_name[0];
169 };
170
171 /*! \brief Structure for passing load/reload details */
172 struct sorcery_load_details {
173         /*! \brief Sorcery structure in use */
174         const struct ast_sorcery *sorcery;
175
176         /*! \brief Type of object being loaded */
177         const char *type;
178
179         /*! \brief Whether this is a reload or not */
180         unsigned int reload:1;
181 };
182
183 /*! \brief Registered sorcery wizards */
184 static struct ao2_container *wizards;
185
186 /*! \brief Registered sorcery instances */
187 static struct ao2_container *instances;
188
189 static int int_handler_fn(const void *obj, const intptr_t *args, char **buf)
190 {
191         int *field = (int *)(obj + args[0]);
192         return (ast_asprintf(buf, "%d", *field) < 0) ? -1 : 0;
193 }
194
195 static int uint_handler_fn(const void *obj, const intptr_t *args, char **buf)
196 {
197         unsigned int *field = (unsigned int *)(obj + args[0]);
198         return (ast_asprintf(buf, "%u", *field) < 0) ? -1 : 0;
199 }
200
201 static int double_handler_fn(const void *obj, const intptr_t *args, char **buf)
202 {
203         double *field = (double *)(obj + args[0]);
204         return (ast_asprintf(buf, "%f", *field) < 0) ? -1 : 0;
205 }
206
207 static int stringfield_handler_fn(const void *obj, const intptr_t *args, char **buf)
208 {
209         ast_string_field *field = (const char **)(obj + args[0]);
210         return !(*buf = ast_strdup(*field)) ? -1 : 0;
211 }
212
213 static int bool_handler_fn(const void *obj, const intptr_t *args, char **buf)
214 {
215         unsigned int *field = (unsigned int *)(obj + args[0]);
216         return !(*buf = ast_strdup(*field ? "true" : "false")) ? -1 : 0;
217 }
218
219 static int sockaddr_handler_fn(const void *obj, const intptr_t *args, char **buf)
220 {
221         struct ast_sockaddr *field = (struct ast_sockaddr *)(obj + args[0]);
222         return !(*buf = ast_strdup(ast_sockaddr_stringify(field))) ? -1 : 0;
223 }
224
225 static int chararray_handler_fn(const void *obj, const intptr_t *args, char **buf)
226 {
227         char *field = (char *)(obj + args[0]);
228         return !(*buf = ast_strdup(field)) ? -1 : 0;
229 }
230
231 static int codec_handler_fn(const void *obj, const intptr_t *args, char **buf)
232 {
233         char tmp_buf[256];
234         struct ast_codec_pref *pref = (struct ast_codec_pref *)(obj + args[0]);
235         ast_codec_pref_string(pref, tmp_buf, sizeof(tmp_buf));
236         return !(*buf = ast_strdup(tmp_buf));
237 }
238
239 static sorcery_field_handler sorcery_field_default_handler(enum aco_option_type type)
240 {
241         switch(type) {
242         case OPT_BOOL_T: return bool_handler_fn;
243         case OPT_CHAR_ARRAY_T: return chararray_handler_fn;
244         case OPT_CODEC_T: return codec_handler_fn;
245         case OPT_DOUBLE_T: return double_handler_fn;
246         case OPT_INT_T: return int_handler_fn;
247         case OPT_SOCKADDR_T: return sockaddr_handler_fn;
248         case OPT_STRINGFIELD_T: return stringfield_handler_fn;
249         case OPT_UINT_T: return uint_handler_fn;
250
251         default:
252         case OPT_CUSTOM_T: return NULL;
253         }
254
255         return NULL;
256 }
257
258 /*! \brief Hashing function for sorcery wizards */
259 static int sorcery_wizard_hash(const void *obj, const int flags)
260 {
261     const struct ast_sorcery_wizard *object;
262     const char *key;
263
264     switch (flags & OBJ_SEARCH_MASK) {
265     case OBJ_SEARCH_KEY:
266         key = obj;
267         break;
268     case OBJ_SEARCH_OBJECT:
269         object = obj;
270         key = object->name;
271         break;
272     default:
273         ast_assert(0);
274         return 0;
275     }
276     return ast_str_hash(key);
277 }
278
279 /*! \brief Comparator function for sorcery wizards */
280 static int sorcery_wizard_cmp(void *obj, void *arg, int flags)
281 {
282         const struct ast_sorcery_wizard *object_left = obj;
283         const struct ast_sorcery_wizard *object_right = arg;
284         const char *right_key = arg;
285         int cmp;
286
287         switch (flags & OBJ_SEARCH_MASK) {
288         case OBJ_SEARCH_OBJECT:
289                 right_key = object_right->name;
290                 /* Fall through */
291         case OBJ_SEARCH_KEY:
292                 cmp = strcmp(object_left->name, right_key);
293                 break;
294         case OBJ_SEARCH_PARTIAL_KEY:
295                 cmp = strncmp(object_left->name, right_key, strlen(right_key));
296                 break;
297         default:
298                 cmp = 0;
299                 break;
300         }
301         if (cmp) {
302                 return 0;
303         }
304         return CMP_MATCH;
305 }
306
307 /*! \brief Cleanup function */
308 static void sorcery_exit(void)
309 {
310         ast_threadpool_shutdown(threadpool);
311         threadpool = NULL;
312 }
313
314 /*! \brief Cleanup function for graceful shutdowns */
315 static void sorcery_cleanup(void)
316 {
317         ao2_cleanup(wizards);
318         wizards = NULL;
319         ao2_cleanup(instances);
320         instances = NULL;
321 }
322
323 /*! \brief Compare function for sorcery instances */
324 static int sorcery_instance_cmp(void *obj, void *arg, int flags)
325 {
326         const struct ast_sorcery *object_left = obj;
327         const struct ast_sorcery *object_right = arg;
328         const char *right_key = arg;
329         int cmp;
330
331         switch (flags & OBJ_SEARCH_MASK) {
332         case OBJ_SEARCH_OBJECT:
333                 right_key = object_right->module_name;
334                 /* Fall through */
335         case OBJ_SEARCH_KEY:
336                 cmp = strcmp(object_left->module_name, right_key);
337                 break;
338         case OBJ_SEARCH_PARTIAL_KEY:
339                 cmp = strncmp(object_left->module_name, right_key, strlen(right_key));
340                 break;
341         default:
342                 cmp = 0;
343                 break;
344         }
345         if (cmp) {
346                 return 0;
347         }
348         return CMP_MATCH;
349 }
350
351 /*! \brief Hashing function for sorcery instances */
352 static int sorcery_instance_hash(const void *obj, const int flags)
353 {
354     const struct ast_sorcery *object;
355     const char *key;
356
357     switch (flags & OBJ_SEARCH_MASK) {
358     case OBJ_SEARCH_KEY:
359         key = obj;
360         break;
361     case OBJ_SEARCH_OBJECT:
362         object = obj;
363         key = object->module_name;
364         break;
365     default:
366         ast_assert(0);
367         return 0;
368     }
369     return ast_str_hash(key);
370 }
371
372 int ast_sorcery_init(void)
373 {
374         struct ast_threadpool_options options = {
375                 .version = AST_THREADPOOL_OPTIONS_VERSION,
376                 .auto_increment = 1,
377                 .max_size = 0,
378                 .idle_timeout = 60,
379                 .initial_size = 0,
380         };
381         ast_assert(wizards == NULL);
382
383         if (!(threadpool = ast_threadpool_create("Sorcery", NULL, &options))) {
384                 threadpool = NULL;
385                 return -1;
386         }
387
388         if (!(wizards = ao2_container_alloc(WIZARD_BUCKETS, sorcery_wizard_hash, sorcery_wizard_cmp))) {
389                 ast_threadpool_shutdown(threadpool);
390                 return -1;
391         }
392
393         instances = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_RWLOCK, INSTANCE_BUCKETS,
394                 sorcery_instance_hash, sorcery_instance_cmp);
395         if (!instances) {
396                 sorcery_cleanup();
397                 sorcery_exit();
398                 return -1;
399         }
400
401         ast_register_cleanup(sorcery_cleanup);
402         ast_register_atexit(sorcery_exit);
403
404         return 0;
405 }
406
407 int __ast_sorcery_wizard_register(const struct ast_sorcery_wizard *interface, struct ast_module *module)
408 {
409         struct ast_sorcery_wizard *wizard;
410         int res = -1;
411
412         ast_assert(!ast_strlen_zero(interface->name));
413
414         ao2_lock(wizards);
415
416         if ((wizard = ao2_find(wizards, interface->name, OBJ_KEY | OBJ_NOLOCK))) {
417                 ast_log(LOG_WARNING, "Attempted to register sorcery wizard '%s' twice\n",
418                         interface->name);
419                 goto done;
420         }
421
422         if (!(wizard = ao2_alloc(sizeof(*wizard), NULL))) {
423                 goto done;
424         }
425
426         *wizard = *interface;
427         wizard->module = module;
428
429         ao2_link_flags(wizards, wizard, OBJ_NOLOCK);
430         res = 0;
431
432         ast_verb(2, "Sorcery registered wizard '%s'\n", interface->name);
433
434 done:
435         ao2_cleanup(wizard);
436         ao2_unlock(wizards);
437
438         return res;
439 }
440
441 int ast_sorcery_wizard_unregister(const struct ast_sorcery_wizard *interface)
442 {
443         RAII_VAR(struct ast_sorcery_wizard *, wizard, ao2_find(wizards, interface->name, OBJ_KEY | OBJ_UNLINK), ao2_cleanup);
444
445         if (wizard) {
446                 ast_verb(2, "Sorcery unregistered wizard '%s'\n", interface->name);
447                 return 0;
448         } else {
449                 return -1;
450         }
451 }
452
453 /*! \brief Destructor called when sorcery structure is destroyed */
454 static void sorcery_destructor(void *obj)
455 {
456         struct ast_sorcery *sorcery = obj;
457
458         ao2_cleanup(sorcery->types);
459 }
460
461 /*! \brief Hashing function for sorcery types */
462 static int sorcery_type_hash(const void *obj, const int flags)
463 {
464     const struct ast_sorcery_object_type *object;
465     const char *key;
466
467     switch (flags & OBJ_SEARCH_MASK) {
468     case OBJ_SEARCH_KEY:
469         key = obj;
470         break;
471     case OBJ_SEARCH_OBJECT:
472         object = obj;
473         key = object->name;
474         break;
475     default:
476         ast_assert(0);
477         return 0;
478     }
479     return ast_str_hash(key);
480 }
481
482 /*! \brief Comparator function for sorcery types */
483 static int sorcery_type_cmp(void *obj, void *arg, int flags)
484 {
485         const struct ast_sorcery_object_type *object_left = obj;
486         const struct ast_sorcery_object_type *object_right = arg;
487         const char *right_key = arg;
488         int cmp;
489
490         switch (flags & OBJ_SEARCH_MASK) {
491         case OBJ_SEARCH_OBJECT:
492                 right_key = object_right->name;
493                 /* Fall through */
494         case OBJ_SEARCH_KEY:
495                 cmp = strcmp(object_left->name, right_key);
496                 break;
497         case OBJ_SEARCH_PARTIAL_KEY:
498                 cmp = strncmp(object_left->name, right_key, strlen(right_key));
499                 break;
500         default:
501                 cmp = 0;
502                 break;
503         }
504         if (cmp) {
505                 return 0;
506         }
507         return CMP_MATCH;
508 }
509
510 struct ast_sorcery *__ast_sorcery_open(const char *module_name)
511 {
512         struct ast_sorcery *sorcery;
513
514         ast_assert(module_name != NULL);
515
516         ao2_wrlock(instances);
517         if ((sorcery = ao2_find(instances, module_name, OBJ_SEARCH_KEY | OBJ_NOLOCK))) {
518                 goto done;
519         }
520
521         if (!(sorcery = ao2_alloc(sizeof(*sorcery) + strlen(module_name) + 1, sorcery_destructor))) {
522                 goto done;
523         }
524
525         if (!(sorcery->types = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_RWLOCK, TYPE_BUCKETS, sorcery_type_hash, sorcery_type_cmp))) {
526                 ao2_ref(sorcery, -1);
527                 sorcery = NULL;
528                 goto done;
529         }
530
531         strcpy(sorcery->module_name, module_name); /* Safe */
532         ao2_link_flags(instances, sorcery, OBJ_NOLOCK);
533
534 done:
535         ao2_unlock(instances);
536         return sorcery;
537 }
538
539 /*! \brief Search function for sorcery instances */
540 struct ast_sorcery *ast_sorcery_retrieve_by_module_name(const char *module_name)
541 {
542         return ao2_find(instances, module_name, OBJ_SEARCH_KEY);
543 }
544
545 /*! \brief Destructor function for object types */
546 static void sorcery_object_type_destructor(void *obj)
547 {
548         struct ast_sorcery_object_type *object_type = obj;
549
550         ao2_cleanup(object_type->wizards);
551         ao2_cleanup(object_type->fields);
552         ao2_cleanup(object_type->observers);
553
554         if (object_type->info) {
555                 aco_info_destroy(object_type->info);
556                 ast_free(object_type->info);
557         }
558
559         ast_free(object_type->file);
560
561         ast_taskprocessor_unreference(object_type->serializer);
562 }
563
564 /*! \brief Internal function which allocates an object type structure */
565 static struct ast_sorcery_object_type *sorcery_object_type_alloc(const char *type, const char *module)
566 {
567         struct ast_sorcery_object_type *object_type;
568         char uuid[AST_UUID_STR_LEN];
569
570         if (!(object_type = ao2_alloc(sizeof(*object_type), sorcery_object_type_destructor))) {
571                 return NULL;
572         }
573
574         /* Order matters for object wizards */
575         if (!(object_type->wizards = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 1, NULL, NULL))) {
576                 ao2_ref(object_type, -1);
577                 return NULL;
578         }
579
580         if (!(object_type->fields = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 1, NULL, NULL))) {
581                 ao2_ref(object_type, -1);
582                 return NULL;
583         }
584
585         if (!(object_type->observers = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_RWLOCK, 1, NULL, NULL))) {
586                 ao2_ref(object_type, -1);
587                 return NULL;
588         }
589
590         if (!(object_type->info = ast_calloc(1, sizeof(*object_type->info) + 2 * sizeof(object_type->info->files[0])))) {
591                 ao2_ref(object_type, -1);
592                 return NULL;
593         }
594
595         if (!(object_type->file = ast_calloc(1, sizeof(*object_type->file) + 2 * sizeof(object_type->file->types[0])))) {
596                 ao2_ref(object_type, -1);
597                 return NULL;
598         }
599
600         if (!ast_uuid_generate_str(uuid, sizeof(uuid))) {
601                 ao2_ref(object_type, -1);
602                 return NULL;
603         }
604
605         if (!(object_type->serializer = ast_threadpool_serializer(uuid, threadpool))) {
606                 ao2_ref(object_type, -1);
607                 return NULL;
608         }
609
610         object_type->info->files[0] = object_type->file;
611         object_type->info->files[1] = NULL;
612         object_type->info->module = module;
613
614         ast_copy_string(object_type->name, type, sizeof(object_type->name));
615
616         return object_type;
617 }
618
619 /*! \brief Object wizard destructor */
620 static void sorcery_object_wizard_destructor(void *obj)
621 {
622         struct ast_sorcery_object_wizard *object_wizard = obj;
623
624         if (object_wizard->data) {
625                 object_wizard->wizard->close(object_wizard->data);
626         }
627
628         if (object_wizard->wizard) {
629                 ast_module_unref(object_wizard->wizard->module);
630         }
631 }
632
633 /*! \brief Internal function which creates an object type and adds a wizard mapping */
634 static int sorcery_apply_wizard_mapping(struct ast_sorcery *sorcery, const char *type, const char *module, const char *name, const char *data, unsigned int caching)
635 {
636         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
637         RAII_VAR(struct ast_sorcery_wizard *, wizard, ao2_find(wizards, name, OBJ_KEY), ao2_cleanup);
638         RAII_VAR(struct ast_sorcery_object_wizard *, object_wizard, ao2_alloc(sizeof(*object_wizard), sorcery_object_wizard_destructor), ao2_cleanup);
639         int created = 0;
640
641         if (!wizard || !object_wizard) {
642                 return -1;
643         }
644
645         if (!object_type) {
646                 if (!(object_type = sorcery_object_type_alloc(type, module))) {
647                         return -1;
648                 }
649                 created = 1;
650         }
651
652         if (wizard->open && !(object_wizard->data = wizard->open(data))) {
653                 return -1;
654         }
655
656         ast_module_ref(wizard->module);
657
658         object_wizard->wizard = wizard;
659         object_wizard->caching = caching;
660
661         ao2_link(object_type->wizards, object_wizard);
662
663         if (created) {
664                 ao2_link(sorcery->types, object_type);
665         }
666
667         return 0;
668 }
669
670 int __ast_sorcery_apply_config(struct ast_sorcery *sorcery, const char *name, const char *module)
671 {
672         struct ast_flags flags = { 0 };
673         struct ast_config *config = ast_config_load2("sorcery.conf", "sorcery", flags);
674         struct ast_variable *mapping;
675         int res = 0;
676
677         if (!config || config == CONFIG_STATUS_FILEINVALID) {
678                 return -1;
679         }
680
681         for (mapping = ast_variable_browse(config, name); mapping; mapping = mapping->next) {
682                 RAII_VAR(char *, mapping_name, ast_strdup(mapping->name), ast_free);
683                 RAII_VAR(char *, mapping_value, ast_strdup(mapping->value), ast_free);
684                 char *options = mapping_name;
685                 char *type = strsep(&options, "/");
686                 char *data = mapping_value;
687                 char *wizard = strsep(&data, ",");
688                 unsigned int caching = 0;
689
690                 /* If no object type or wizard exists just skip, nothing we can do */
691                 if (ast_strlen_zero(type) || ast_strlen_zero(wizard)) {
692                         continue;
693                 }
694
695                 /* If the wizard is configured as a cache treat it as such */
696                 if (!ast_strlen_zero(options) && strstr(options, "cache")) {
697                         caching = 1;
698                 }
699
700                 /* Any error immediately causes us to stop */
701                 if (sorcery_apply_wizard_mapping(sorcery, type, module, wizard, data, caching)) {
702                         res = -1;
703                         break;
704                 }
705         }
706
707         ast_config_destroy(config);
708
709         return res;
710 }
711
712 int __ast_sorcery_apply_default(struct ast_sorcery *sorcery, const char *type, const char *module, const char *name, const char *data)
713 {
714         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
715
716         /* Defaults can not be added if any existing mapping exists */
717         if (object_type) {
718                 return -1;
719         }
720
721         return sorcery_apply_wizard_mapping(sorcery, type, module, name, data, 0);
722 }
723
724 static int sorcery_extended_config_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
725 {
726         return ast_sorcery_object_set_extended(obj, var->name, var->value);
727 }
728
729 static int sorcery_extended_fields_handler(const void *obj, struct ast_variable **fields)
730 {
731         const struct ast_sorcery_object_details *details = obj;
732
733         if (details->object->extended) {
734                 *fields = ast_variables_dup(details->object->extended);
735         } else {
736                 *fields = NULL;
737         }
738
739         return 0;
740 }
741
742 int __ast_sorcery_object_register(struct ast_sorcery *sorcery, const char *type, unsigned int hidden, unsigned int reloadable, aco_type_item_alloc alloc, sorcery_transform_handler transform, sorcery_apply_handler apply)
743 {
744         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
745
746         if (!object_type || object_type->type.item_alloc) {
747                 return -1;
748         }
749
750         object_type->type.name = object_type->name;
751         object_type->type.type = ACO_ITEM;
752         object_type->type.category = ".?";
753         object_type->type.item_alloc = alloc;
754         object_type->type.hidden = hidden;
755
756         object_type->reloadable = reloadable;
757         object_type->transform = transform;
758         object_type->apply = apply;
759         object_type->file->types[0] = &object_type->type;
760         object_type->file->types[1] = NULL;
761
762         if (aco_info_init(object_type->info)) {
763                 return -1;
764         }
765
766         if (ast_sorcery_object_fields_register(sorcery, type, "^@", sorcery_extended_config_handler, sorcery_extended_fields_handler)) {
767                 return -1;
768         }
769
770         return 0;
771 }
772
773 void ast_sorcery_object_set_copy_handler(struct ast_sorcery *sorcery, const char *type, sorcery_copy_handler copy)
774 {
775         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
776
777         if (!object_type) {
778                 return;
779         }
780
781         object_type->copy = copy;
782 }
783
784 void ast_sorcery_object_set_diff_handler(struct ast_sorcery *sorcery, const char *type, sorcery_diff_handler diff)
785 {
786         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
787
788         if (!object_type) {
789                 return;
790         }
791
792         object_type->diff = diff;
793 }
794
795 int ast_sorcery_object_fields_register(struct ast_sorcery *sorcery, const char *type, const char *regex, aco_option_handler config_handler, sorcery_fields_handler sorcery_handler)
796 {
797         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
798         RAII_VAR(struct ast_sorcery_object_field *, object_field, NULL, ao2_cleanup);
799
800         if (!object_type || !object_type->type.item_alloc || !config_handler || !(object_field = ao2_alloc(sizeof(*object_field), NULL))) {
801                 return -1;
802         }
803
804         ast_copy_string(object_field->name, regex, sizeof(object_field->name));
805         object_field->multiple_handler = sorcery_handler;
806
807         ao2_link(object_type->fields, object_field);
808         __aco_option_register(object_type->info, regex, ACO_REGEX, object_type->file->types, "", OPT_CUSTOM_T, config_handler, 0, 1, 0);
809
810         return 0;
811 }
812
813 int __ast_sorcery_object_field_register(struct ast_sorcery *sorcery, const char *type, const char *name, const char *default_val, enum aco_option_type opt_type,
814                                         aco_option_handler config_handler, sorcery_field_handler sorcery_handler, unsigned int flags, unsigned int no_doc, size_t argc, ...)
815 {
816         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
817         RAII_VAR(struct ast_sorcery_object_field *, object_field, NULL, ao2_cleanup);
818         int pos;
819         va_list args;
820
821         if (!strcmp(type, "id") || !object_type || !object_type->type.item_alloc) {
822                 return -1;
823         }
824
825         if (!sorcery_handler) {
826                 sorcery_handler = sorcery_field_default_handler(opt_type);
827         }
828
829         if (!(object_field = ao2_alloc(sizeof(*object_field) + argc * sizeof(object_field->args[0]), NULL))) {
830                 return -1;
831         }
832
833         ast_copy_string(object_field->name, name, sizeof(object_field->name));
834         object_field->handler = sorcery_handler;
835
836         va_start(args, argc);
837         for (pos = 0; pos < argc; pos++) {
838                 object_field->args[pos] = va_arg(args, size_t);
839         }
840         va_end(args);
841
842         ao2_link(object_type->fields, object_field);
843
844         /* TODO: Improve this hack */
845         if (!argc) {
846                 __aco_option_register(object_type->info, name, ACO_EXACT, object_type->file->types, default_val, opt_type, config_handler, flags, no_doc, argc);
847         } else if (argc == 1) {
848                 __aco_option_register(object_type->info, name, ACO_EXACT, object_type->file->types, default_val, opt_type, config_handler, flags, no_doc, argc,
849                         object_field->args[0]);
850         } else if (argc == 2) {
851                 __aco_option_register(object_type->info, name, ACO_EXACT, object_type->file->types, default_val, opt_type, config_handler, flags, no_doc, argc,
852                         object_field->args[0], object_field->args[1]);
853         } else if (argc == 3) {
854                 __aco_option_register(object_type->info, name, ACO_EXACT, object_type->file->types, default_val, opt_type, config_handler, flags, no_doc, argc,
855                         object_field->args[0], object_field->args[1], object_field->args[2]);
856         } else {
857                 ast_assert(0); /* The hack... she does us no good for this */
858         }
859
860         return 0;
861 }
862
863 /*! \brief Retrieves whether or not the type is reloadable */
864 static int sorcery_reloadable(const struct ast_sorcery *sorcery, const char *type)
865 {
866         RAII_VAR(struct ast_sorcery_object_type *, object_type,
867                  ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
868         return object_type && object_type->reloadable;
869 }
870
871 static int sorcery_wizard_load(void *obj, void *arg, int flags)
872 {
873         struct ast_sorcery_object_wizard *wizard = obj;
874         struct sorcery_load_details *details = arg;
875         void (*load)(void *data, const struct ast_sorcery *sorcery, const char *type);
876
877         if (details->reload && !sorcery_reloadable(details->sorcery, details->type)) {
878                 ast_log(LOG_NOTICE, "Type '%s' is not reloadable, "
879                         "maintaining previous values\n", details->type);
880                 return 0;
881         }
882
883         load = !details->reload ? wizard->wizard->load : wizard->wizard->reload;
884
885         if (load) {
886                 load(wizard->data, details->sorcery, details->type);
887         }
888
889         return 0;
890 }
891
892 /*! \brief Destructor for observer invocation */
893 static void sorcery_observer_invocation_destroy(void *obj)
894 {
895         struct sorcery_observer_invocation *invocation = obj;
896
897         ao2_cleanup(invocation->object_type);
898         ao2_cleanup(invocation->object);
899 }
900
901 /*! \brief Allocator function for observer invocation */
902 static struct sorcery_observer_invocation *sorcery_observer_invocation_alloc(struct ast_sorcery_object_type *object_type, void *object)
903 {
904         struct sorcery_observer_invocation *invocation = ao2_alloc(sizeof(*invocation), sorcery_observer_invocation_destroy);
905
906         if (!invocation) {
907                 return NULL;
908         }
909
910         ao2_ref(object_type, +1);
911         invocation->object_type = object_type;
912
913         if (object) {
914                 ao2_ref(object, +1);
915                 invocation->object = object;
916         }
917
918         return invocation;
919 }
920
921 /*! \brief Internal callback function which notifies an individual observer that an object type has been loaded */
922 static int sorcery_observer_notify_loaded(void *obj, void *arg, int flags)
923 {
924         const struct ast_sorcery_object_type_observer *observer = obj;
925
926         if (observer->callbacks->loaded) {
927                 observer->callbacks->loaded(arg);
928         }
929
930         return 0;
931 }
932
933 /*! \brief Internal callback function which notifies observers that an object type has been loaded */
934 static int sorcery_observers_notify_loaded(void *data)
935 {
936         struct sorcery_observer_invocation *invocation = data;
937
938         ao2_callback(invocation->object_type->observers, OBJ_NODATA, sorcery_observer_notify_loaded, invocation->object_type->name);
939         ao2_cleanup(invocation);
940
941         return 0;
942 }
943
944 static int sorcery_object_load(void *obj, void *arg, int flags)
945 {
946         struct ast_sorcery_object_type *type = obj;
947         struct sorcery_load_details *details = arg;
948
949         details->type = type->name;
950         ao2_callback(type->wizards, OBJ_NODATA, sorcery_wizard_load, details);
951
952         if (ao2_container_count(type->observers)) {
953                 struct sorcery_observer_invocation *invocation = sorcery_observer_invocation_alloc(type, NULL);
954
955                 if (invocation && ast_taskprocessor_push(type->serializer, sorcery_observers_notify_loaded, invocation)) {
956                         ao2_cleanup(invocation);
957                 }
958         }
959
960         return 0;
961 }
962
963 void ast_sorcery_load(const struct ast_sorcery *sorcery)
964 {
965         struct sorcery_load_details details = {
966                 .sorcery = sorcery,
967                 .reload = 0,
968         };
969
970         ao2_callback(sorcery->types, OBJ_NODATA, sorcery_object_load, &details);
971 }
972
973 void ast_sorcery_load_object(const struct ast_sorcery *sorcery, const char *type)
974 {
975         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
976         struct sorcery_load_details details = {
977                 .sorcery = sorcery,
978                 .reload = 0,
979         };
980
981         if (!object_type) {
982                 return;
983         }
984
985         sorcery_object_load(object_type, &details, 0);
986 }
987
988 void ast_sorcery_reload(const struct ast_sorcery *sorcery)
989 {
990         struct sorcery_load_details details = {
991                 .sorcery = sorcery,
992                 .reload = 1,
993         };
994
995         ao2_callback(sorcery->types, OBJ_NODATA, sorcery_object_load, &details);
996 }
997
998 void ast_sorcery_reload_object(const struct ast_sorcery *sorcery, const char *type)
999 {
1000         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
1001         struct sorcery_load_details details = {
1002                 .sorcery = sorcery,
1003                 .reload = 1,
1004         };
1005
1006         if (!object_type) {
1007                 return;
1008         }
1009
1010         sorcery_object_load(object_type, &details, 0);
1011 }
1012
1013 void ast_sorcery_ref(struct ast_sorcery *sorcery)
1014 {
1015         ao2_ref(sorcery, +1);
1016 }
1017
1018 struct ast_variable *ast_sorcery_objectset_create(const struct ast_sorcery *sorcery, const void *object)
1019 {
1020         const struct ast_sorcery_object_details *details = object;
1021         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1022         struct ao2_iterator i;
1023         struct ast_sorcery_object_field *object_field;
1024         struct ast_variable *fields = NULL;
1025         int res = 0;
1026
1027         if (!object_type) {
1028                 return NULL;
1029         }
1030
1031         i = ao2_iterator_init(object_type->fields, 0);
1032
1033         for (; (object_field = ao2_iterator_next(&i)) && !res; ao2_ref(object_field, -1)) {
1034                 struct ast_variable *tmp = NULL;
1035
1036                 if (object_field->multiple_handler) {
1037                         if ((res = object_field->multiple_handler(object, &tmp))) {
1038                                 ast_variables_destroy(tmp);
1039                         }
1040                 } else if (object_field->handler) {
1041                         char *buf = NULL;
1042
1043                         if ((res = object_field->handler(object, object_field->args, &buf)) ||
1044                                 !(tmp = ast_variable_new(object_field->name, S_OR(buf, ""), ""))) {
1045                                 res = -1;
1046                         }
1047
1048                         ast_free(buf);
1049                 } else {
1050                         continue;
1051                 }
1052
1053                 if (!res && tmp) {
1054                         tmp->next = fields;
1055                         fields = tmp;
1056                 }
1057         }
1058
1059         ao2_iterator_destroy(&i);
1060
1061         /* If any error occurs we destroy all fields handled before so a partial objectset is not returned */
1062         if (res) {
1063                 ast_variables_destroy(fields);
1064                 fields = NULL;
1065         }
1066
1067         return fields;
1068 }
1069
1070 struct ast_json *ast_sorcery_objectset_json_create(const struct ast_sorcery *sorcery, const void *object)
1071 {
1072         const struct ast_sorcery_object_details *details = object;
1073         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1074         struct ao2_iterator i;
1075         struct ast_sorcery_object_field *object_field;
1076         struct ast_json *json = ast_json_object_create();
1077         int res = 0;
1078
1079         if (!object_type || !json) {
1080                 return NULL;
1081         }
1082
1083         i = ao2_iterator_init(object_type->fields, 0);
1084
1085         for (; (object_field = ao2_iterator_next(&i)) && !res; ao2_ref(object_field, -1)) {
1086                 if (object_field->multiple_handler) {
1087                         struct ast_variable *tmp = NULL;
1088                         struct ast_variable *field;
1089
1090                         if ((res = object_field->multiple_handler(object, &tmp))) {
1091                                 ao2_ref(object_field, -1);
1092                                 break;
1093                         }
1094
1095                         for (field = tmp; field; field = field->next) {
1096                                 struct ast_json *value = ast_json_string_create(field->value);
1097
1098                                 if (!value || ast_json_object_set(json, field->name, value)) {
1099                                         res = -1;
1100                                 }
1101                         }
1102
1103                         ast_variables_destroy(tmp);
1104                 } else if (object_field->handler) {
1105                         char *buf = NULL;
1106                         struct ast_json *value = NULL;
1107
1108                         if ((res = object_field->handler(object, object_field->args, &buf))
1109                                 || !(value = ast_json_string_create(buf))
1110                                 || ast_json_object_set(json, object_field->name, value)) {
1111                                 res = -1;
1112                         }
1113
1114                         ast_free(buf);
1115                 } else {
1116                         continue;
1117                 }
1118         }
1119
1120         ao2_iterator_destroy(&i);
1121
1122         /* If any error occurs we destroy the JSON object so a partial objectset is not returned */
1123         if (res) {
1124                 ast_json_unref(json);
1125                 json = NULL;
1126         }
1127
1128         return json;
1129 }
1130
1131 int ast_sorcery_objectset_apply(const struct ast_sorcery *sorcery, void *object, struct ast_variable *objectset)
1132 {
1133         const struct ast_sorcery_object_details *details = object;
1134         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1135         RAII_VAR(struct ast_variable *, transformed, NULL, ast_variables_destroy);
1136         struct ast_variable *field;
1137         int res = 0;
1138
1139         if (!object_type) {
1140                 return -1;
1141         }
1142
1143         if (object_type->transform && (transformed = object_type->transform(objectset))) {
1144                 field = transformed;
1145         } else {
1146                 field = objectset;
1147         }
1148
1149         for (; field; field = field->next) {
1150                 if ((res = aco_process_var(&object_type->type, details->object->id, field, object))) {
1151                         break;
1152                 }
1153         }
1154
1155         if (!res && object_type->apply) {
1156                 res = object_type->apply(sorcery, object);
1157         }
1158
1159         return res;
1160 }
1161
1162 static const struct ast_variable *sorcery_find_field(const struct ast_variable *fields, const char *name)
1163 {
1164         const struct ast_variable *field;
1165
1166         /* Search the linked list of fields to find the correct one */
1167         for (field = fields; field; field = field->next) {
1168                 if (!strcmp(field->name, name)) {
1169                         return field;
1170                 }
1171         }
1172
1173         return NULL;
1174 }
1175
1176 int ast_sorcery_changeset_create(const struct ast_variable *original, const struct ast_variable *modified, struct ast_variable **changes)
1177 {
1178         const struct ast_variable *field;
1179         int res = 0;
1180
1181         *changes = NULL;
1182
1183         /* Unless the ast_variable list changes when examined... it can't differ from itself */
1184         if (original == modified) {
1185                 return 0;
1186         }
1187
1188         for (field = modified; field; field = field->next) {
1189                 const struct ast_variable *old = sorcery_find_field(original, field->name);
1190
1191                 if (!old || strcmp(old->value, field->value)) {
1192                         struct ast_variable *tmp;
1193
1194                         if (!(tmp = ast_variable_new(field->name, field->value, ""))) {
1195                                 res = -1;
1196                                 break;
1197                         }
1198
1199                         tmp->next = *changes;
1200                         *changes = tmp;
1201                 }
1202         }
1203
1204         /* If an error occurred do not return a partial changeset */
1205         if (res) {
1206                 ast_variables_destroy(*changes);
1207                 *changes = NULL;
1208         }
1209
1210         return res;
1211 }
1212
1213 static void sorcery_object_destructor(void *object)
1214 {
1215         struct ast_sorcery_object_details *details = object;
1216
1217         if (details->object->destructor) {
1218                 details->object->destructor(object);
1219         }
1220
1221         ast_variables_destroy(details->object->extended);
1222         ast_free(details->object->id);
1223 }
1224
1225 void *ast_sorcery_generic_alloc(size_t size, ao2_destructor_fn destructor)
1226 {
1227         void *object = ao2_alloc_options(size + sizeof(struct ast_sorcery_object), sorcery_object_destructor, AO2_ALLOC_OPT_LOCK_NOLOCK);
1228         struct ast_sorcery_object_details *details = object;
1229
1230         if (!object) {
1231                 return NULL;
1232         }
1233
1234         details->object = object + size;
1235         details->object->destructor = destructor;
1236
1237         return object;
1238 }
1239
1240 void *ast_sorcery_alloc(const struct ast_sorcery *sorcery, const char *type, const char *id)
1241 {
1242         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
1243         struct ast_sorcery_object_details *details;
1244
1245         if (!object_type || !object_type->type.item_alloc ||
1246                 !(details = object_type->type.item_alloc(id))) {
1247                 return NULL;
1248         }
1249
1250         if (ast_strlen_zero(id)) {
1251                 char uuid[AST_UUID_STR_LEN];
1252
1253                 ast_uuid_generate_str(uuid, sizeof(uuid));
1254                 details->object->id = ast_strdup(uuid);
1255         } else {
1256                 details->object->id = ast_strdup(id);
1257         }
1258
1259         ast_copy_string(details->object->type, type, sizeof(details->object->type));
1260
1261         if (aco_set_defaults(&object_type->type, id, details)) {
1262                 ao2_ref(details, -1);
1263                 return NULL;
1264         }
1265
1266         return details;
1267 }
1268
1269 void *ast_sorcery_copy(const struct ast_sorcery *sorcery, const void *object)
1270 {
1271         const struct ast_sorcery_object_details *details = object;
1272         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1273         struct ast_sorcery_object_details *copy = ast_sorcery_alloc(sorcery, details->object->type, details->object->id);
1274         RAII_VAR(struct ast_variable *, objectset, NULL, ast_variables_destroy);
1275         int res = 0;
1276
1277         if (!copy) {
1278                 return NULL;
1279         } else if (object_type->copy) {
1280                 res = object_type->copy(object, copy);
1281         } else if ((objectset = ast_sorcery_objectset_create(sorcery, object))) {
1282                 res = ast_sorcery_objectset_apply(sorcery, copy, objectset);
1283         } else {
1284                 /* No native copy available and could not create an objectset, this copy has failed */
1285                 res = -1;
1286         }
1287
1288         if (res) {
1289                 ao2_cleanup(copy);
1290                 copy = NULL;
1291         }
1292
1293         return copy;
1294 }
1295
1296 int ast_sorcery_diff(const struct ast_sorcery *sorcery, const void *original, const void *modified, struct ast_variable **changes)
1297 {
1298         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, ast_sorcery_object_get_type(original), OBJ_KEY), ao2_cleanup);
1299
1300         *changes = NULL;
1301
1302         if (strcmp(ast_sorcery_object_get_type(original), ast_sorcery_object_get_type(modified))) {
1303                 return -1;
1304         }
1305
1306         if (original == modified) {
1307                 return 0;
1308         } else if (!object_type->diff) {
1309                 RAII_VAR(struct ast_variable *, objectset1, NULL, ast_variables_destroy);
1310                 RAII_VAR(struct ast_variable *, objectset2, NULL, ast_variables_destroy);
1311
1312                 objectset1 = ast_sorcery_objectset_create(sorcery, original);
1313                 objectset2 = ast_sorcery_objectset_create(sorcery, modified);
1314
1315                 return ast_sorcery_changeset_create(objectset1, objectset2, changes);
1316         } else {
1317                 return object_type->diff(original, modified, changes);
1318         }
1319 }
1320
1321 /*! \brief Structure used when calling create, update, or delete */
1322 struct sorcery_details {
1323         /*! \brief Pointer to the sorcery instance */
1324         const struct ast_sorcery *sorcery;
1325         /*! \brief Pointer to the object itself */
1326         void *obj;
1327 };
1328
1329 /*! \brief Internal function used to create an object in caching wizards */
1330 static int sorcery_cache_create(void *obj, void *arg, int flags)
1331 {
1332         const struct ast_sorcery_object_wizard *object_wizard = obj;
1333         const struct sorcery_details *details = arg;
1334
1335         if (!object_wizard->caching || !object_wizard->wizard->create) {
1336                 return 0;
1337         }
1338
1339         object_wizard->wizard->create(details->sorcery, object_wizard->data, details->obj);
1340
1341         return 0;
1342 }
1343
1344 void *ast_sorcery_retrieve_by_id(const struct ast_sorcery *sorcery, const char *type, const char *id)
1345 {
1346         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
1347         void *object = NULL;
1348         struct ao2_iterator i;
1349         struct ast_sorcery_object_wizard *wizard;
1350         unsigned int cached = 0;
1351
1352         if (!object_type || ast_strlen_zero(id)) {
1353                 return NULL;
1354         }
1355
1356         i = ao2_iterator_init(object_type->wizards, 0);
1357         for (; (wizard = ao2_iterator_next(&i)); ao2_ref(wizard, -1)) {
1358                 if (wizard->wizard->retrieve_id &&
1359                         !(object = wizard->wizard->retrieve_id(sorcery, wizard->data, object_type->name, id))) {
1360                         continue;
1361                 }
1362
1363                 cached = wizard->caching;
1364
1365                 ao2_ref(wizard, -1);
1366                 break;
1367         }
1368         ao2_iterator_destroy(&i);
1369
1370         if (!cached && object) {
1371                 ao2_callback(object_type->wizards, 0, sorcery_cache_create, object);
1372         }
1373
1374         return object;
1375 }
1376
1377 void *ast_sorcery_retrieve_by_fields(const struct ast_sorcery *sorcery, const char *type, unsigned int flags, struct ast_variable *fields)
1378 {
1379         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
1380         void *object = NULL;
1381         struct ao2_iterator i;
1382         struct ast_sorcery_object_wizard *wizard;
1383         unsigned int cached = 0;
1384
1385         if (!object_type) {
1386                 return NULL;
1387         }
1388
1389         /* If returning multiple objects create a container to store them in */
1390         if ((flags & AST_RETRIEVE_FLAG_MULTIPLE)) {
1391                 if (!(object = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 1, NULL, NULL))) {
1392                         return NULL;
1393                 }
1394         }
1395
1396         /* Inquire with the available wizards for retrieval */
1397         i = ao2_iterator_init(object_type->wizards, 0);
1398         for (; (wizard = ao2_iterator_next(&i)); ao2_ref(wizard, -1)) {
1399                 if ((flags & AST_RETRIEVE_FLAG_MULTIPLE)) {
1400                         if (wizard->wizard->retrieve_multiple) {
1401                                 wizard->wizard->retrieve_multiple(sorcery, wizard->data, object_type->name, object, fields);
1402                         }
1403                 } else if (fields && wizard->wizard->retrieve_fields) {
1404                         if (wizard->wizard->retrieve_fields) {
1405                                 object = wizard->wizard->retrieve_fields(sorcery, wizard->data, object_type->name, fields);
1406                         }
1407                 }
1408
1409                 if ((flags & AST_RETRIEVE_FLAG_MULTIPLE) || !object) {
1410                         continue;
1411                 }
1412
1413                 cached = wizard->caching;
1414
1415                 ao2_ref(wizard, -1);
1416                 break;
1417         }
1418         ao2_iterator_destroy(&i);
1419
1420         /* If we are returning a single object and it came from a non-cache source create it in any caches */
1421         if (!(flags & AST_RETRIEVE_FLAG_MULTIPLE) && !cached && object) {
1422                 ao2_callback(object_type->wizards, 0, sorcery_cache_create, object);
1423         }
1424
1425         return object;
1426 }
1427
1428 struct ao2_container *ast_sorcery_retrieve_by_regex(const struct ast_sorcery *sorcery, const char *type, const char *regex)
1429 {
1430         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
1431         struct ao2_container *objects;
1432         struct ao2_iterator i;
1433         struct ast_sorcery_object_wizard *wizard;
1434
1435         if (!object_type || !(objects = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 1, NULL, NULL))) {
1436                 return NULL;
1437         }
1438
1439         i = ao2_iterator_init(object_type->wizards, 0);
1440         for (; (wizard = ao2_iterator_next(&i)); ao2_ref(wizard, -1)) {
1441                 if (!wizard->wizard->retrieve_regex) {
1442                         continue;
1443                 }
1444
1445                 wizard->wizard->retrieve_regex(sorcery, wizard->data, object_type->name, objects, regex);
1446         }
1447         ao2_iterator_destroy(&i);
1448
1449         return objects;
1450 }
1451
1452 /*! \brief Internal function which returns if the wizard has created the object */
1453 static int sorcery_wizard_create(void *obj, void *arg, int flags)
1454 {
1455         const struct ast_sorcery_object_wizard *object_wizard = obj;
1456         const struct sorcery_details *details = arg;
1457
1458         return (!object_wizard->caching && !object_wizard->wizard->create(details->sorcery, object_wizard->data, details->obj)) ? CMP_MATCH | CMP_STOP : 0;
1459 }
1460
1461 /*! \brief Internal callback function which notifies an individual observer that an object has been created */
1462 static int sorcery_observer_notify_create(void *obj, void *arg, int flags)
1463 {
1464         const struct ast_sorcery_object_type_observer *observer = obj;
1465
1466         if (observer->callbacks->created) {
1467                 observer->callbacks->created(arg);
1468         }
1469
1470         return 0;
1471 }
1472
1473 /*! \brief Internal callback function which notifies observers that an object has been created */
1474 static int sorcery_observers_notify_create(void *data)
1475 {
1476         struct sorcery_observer_invocation *invocation = data;
1477
1478         ao2_callback(invocation->object_type->observers, OBJ_NODATA, sorcery_observer_notify_create, invocation->object);
1479         ao2_cleanup(invocation);
1480
1481         return 0;
1482 }
1483
1484 int ast_sorcery_create(const struct ast_sorcery *sorcery, void *object)
1485 {
1486         const struct ast_sorcery_object_details *details = object;
1487         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1488         RAII_VAR(struct ast_sorcery_object_wizard *, object_wizard, NULL, ao2_cleanup);
1489         struct sorcery_details sdetails = {
1490                 .sorcery = sorcery,
1491                 .obj = object,
1492         };
1493
1494         if (!object_type) {
1495                 return -1;
1496         }
1497
1498         if ((object_wizard = ao2_callback(object_type->wizards, 0, sorcery_wizard_create, &sdetails)) &&
1499                 ao2_container_count(object_type->observers)) {
1500                 struct sorcery_observer_invocation *invocation = sorcery_observer_invocation_alloc(object_type, object);
1501
1502                 if (invocation && ast_taskprocessor_push(object_type->serializer, sorcery_observers_notify_create, invocation)) {
1503                         ao2_cleanup(invocation);
1504                 }
1505         }
1506
1507         return object_wizard ? 0 : -1;
1508 }
1509
1510 /*! \brief Internal callback function which notifies an individual observer that an object has been updated */
1511 static int sorcery_observer_notify_update(void *obj, void *arg, int flags)
1512 {
1513         const struct ast_sorcery_object_type_observer *observer = obj;
1514
1515         if (observer->callbacks->updated) {
1516                 observer->callbacks->updated(arg);
1517         }
1518
1519         return 0;
1520 }
1521
1522 /*! \brief Internal callback function which notifies observers that an object has been updated */
1523 static int sorcery_observers_notify_update(void *data)
1524 {
1525         struct sorcery_observer_invocation *invocation = data;
1526
1527         ao2_callback(invocation->object_type->observers, OBJ_NODATA, sorcery_observer_notify_update, invocation->object);
1528         ao2_cleanup(invocation);
1529
1530         return 0;
1531 }
1532
1533 /*! \brief Internal function which returns if a wizard has updated the object */
1534 static int sorcery_wizard_update(void *obj, void *arg, int flags)
1535 {
1536         const struct ast_sorcery_object_wizard *object_wizard = obj;
1537         const struct sorcery_details *details = arg;
1538
1539         return (object_wizard->wizard->update && !object_wizard->wizard->update(details->sorcery, object_wizard->data, details->obj) &&
1540                 !object_wizard->caching) ? CMP_MATCH | CMP_STOP : 0;
1541 }
1542
1543 int ast_sorcery_update(const struct ast_sorcery *sorcery, void *object)
1544 {
1545         const struct ast_sorcery_object_details *details = object;
1546         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1547         RAII_VAR(struct ast_sorcery_object_wizard *, object_wizard, NULL, ao2_cleanup);
1548         struct sorcery_details sdetails = {
1549                 .sorcery = sorcery,
1550                 .obj = object,
1551         };
1552
1553         if (!object_type) {
1554                 return -1;
1555         }
1556
1557         if ((object_wizard = ao2_callback(object_type->wizards, 0, sorcery_wizard_update, &sdetails)) &&
1558                 ao2_container_count(object_type->observers)) {
1559                 struct sorcery_observer_invocation *invocation = sorcery_observer_invocation_alloc(object_type, object);
1560
1561                 if (invocation && ast_taskprocessor_push(object_type->serializer, sorcery_observers_notify_update, invocation)) {
1562                         ao2_cleanup(invocation);
1563                 }
1564         }
1565
1566         return object_wizard ? 0 : -1;
1567 }
1568
1569 /*! \brief Internal callback function which notifies an individual observer that an object has been deleted */
1570 static int sorcery_observer_notify_delete(void *obj, void *arg, int flags)
1571 {
1572         const struct ast_sorcery_object_type_observer *observer = obj;
1573
1574         if (observer->callbacks->deleted) {
1575                 observer->callbacks->deleted(arg);
1576         }
1577
1578         return 0;
1579 }
1580
1581 /*! \brief Internal callback function which notifies observers that an object has been deleted */
1582 static int sorcery_observers_notify_delete(void *data)
1583 {
1584         struct sorcery_observer_invocation *invocation = data;
1585
1586         ao2_callback(invocation->object_type->observers, OBJ_NODATA, sorcery_observer_notify_delete, invocation->object);
1587         ao2_cleanup(invocation);
1588
1589         return 0;
1590 }
1591
1592 /*! \brief Internal function which returns if a wizard has deleted the object */
1593 static int sorcery_wizard_delete(void *obj, void *arg, int flags)
1594 {
1595         const struct ast_sorcery_object_wizard *object_wizard = obj;
1596         const struct sorcery_details *details = arg;
1597
1598         return (object_wizard->wizard->delete && !object_wizard->wizard->delete(details->sorcery, object_wizard->data, details->obj) &&
1599                 !object_wizard->caching) ? CMP_MATCH | CMP_STOP : 0;
1600 }
1601
1602 int ast_sorcery_delete(const struct ast_sorcery *sorcery, void *object)
1603 {
1604         const struct ast_sorcery_object_details *details = object;
1605         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, details->object->type, OBJ_KEY), ao2_cleanup);
1606         RAII_VAR(struct ast_sorcery_object_wizard *, object_wizard, NULL, ao2_cleanup);
1607         struct sorcery_details sdetails = {
1608                 .sorcery = sorcery,
1609                 .obj = object,
1610         };
1611
1612         if (!object_type) {
1613                 return -1;
1614         }
1615
1616         if ((object_wizard = ao2_callback(object_type->wizards, 0, sorcery_wizard_delete, &sdetails)) &&
1617                 ao2_container_count(object_type->observers)) {
1618                 struct sorcery_observer_invocation *invocation = sorcery_observer_invocation_alloc(object_type, object);
1619
1620                 if (invocation && ast_taskprocessor_push(object_type->serializer, sorcery_observers_notify_delete, invocation)) {
1621                         ao2_cleanup(invocation);
1622                 }
1623         }
1624
1625         return object_wizard ? 0 : -1;
1626 }
1627
1628 void ast_sorcery_unref(struct ast_sorcery *sorcery)
1629 {
1630         if (sorcery) {
1631                 /* One ref for what we just released, the other for the instances container. */
1632                 ao2_wrlock(instances);
1633                 if (ao2_ref(sorcery, -1) == 2) {
1634                         ao2_unlink_flags(instances, sorcery, OBJ_NOLOCK);
1635                 }
1636                 ao2_unlock(instances);
1637         }
1638 }
1639
1640 const char *ast_sorcery_object_get_id(const void *object)
1641 {
1642         const struct ast_sorcery_object_details *details = object;
1643         return details->object->id;
1644 }
1645
1646 const char *ast_sorcery_object_get_type(const void *object)
1647 {
1648         const struct ast_sorcery_object_details *details = object;
1649         return details->object->type;
1650 }
1651
1652 const char *ast_sorcery_object_get_extended(const void *object, const char *name)
1653 {
1654         const struct ast_sorcery_object_details *details = object;
1655         struct ast_variable *field;
1656
1657         for (field = details->object->extended; field; field = field->next) {
1658                 if (!strcmp(field->name + 1, name)) {
1659                         return field->value;
1660                 }
1661         }
1662
1663         return NULL;
1664 }
1665
1666 int ast_sorcery_object_set_extended(const void *object, const char *name, const char *value)
1667 {
1668         RAII_VAR(struct ast_variable *, field, NULL, ast_variables_destroy);
1669         struct ast_variable *extended = ast_variable_new(name, value, ""), *previous = NULL;
1670         const struct ast_sorcery_object_details *details = object;
1671
1672         if (!extended) {
1673                 return -1;
1674         }
1675
1676         for (field = details->object->extended; field; previous = field, field = field->next) {
1677                 if (!strcmp(field->name, name)) {
1678                         if (previous) {
1679                                 previous->next = field->next;
1680                         } else {
1681                                 details->object->extended = field->next;
1682                         }
1683                         field->next = NULL;
1684                         break;
1685                 }
1686         }
1687
1688         extended->next = details->object->extended;
1689         details->object->extended = extended;
1690
1691         return 0;
1692 }
1693
1694 int ast_sorcery_observer_add(const struct ast_sorcery *sorcery, const char *type, const struct ast_sorcery_observer *callbacks)
1695 {
1696         RAII_VAR(struct ast_sorcery_object_type *, object_type, ao2_find(sorcery->types, type, OBJ_KEY), ao2_cleanup);
1697         struct ast_sorcery_object_type_observer *observer;
1698         int res;
1699
1700         if (!object_type || !callbacks) {
1701                 return -1;
1702         }
1703
1704         if (!(observer = ao2_alloc(sizeof(*observer), NULL))) {
1705                 return -1;
1706         }
1707
1708         observer->callbacks = callbacks;
1709         res = 0;
1710         if (!ao2_link(object_type->observers, observer)) {
1711                 res = -1;
1712         }
1713         ao2_ref(observer, -1);
1714
1715         return res;
1716 }
1717
1718 /*! \brief Internal callback function for removing an observer */
1719 static int sorcery_observer_remove(void *obj, void *arg, int flags)
1720 {
1721         const struct ast_sorcery_object_type_observer *observer = obj;
1722
1723         return (observer->callbacks == arg) ? CMP_MATCH | CMP_STOP : 0;
1724 }
1725
1726 void ast_sorcery_observer_remove(const struct ast_sorcery *sorcery, const char *type, const struct ast_sorcery_observer *callbacks)
1727 {
1728         RAII_VAR(struct ast_sorcery_object_type *, object_type, NULL, ao2_cleanup);
1729         struct ast_sorcery_observer *cbs = (struct ast_sorcery_observer *) callbacks;/* Remove const for traversal. */
1730
1731         if (!sorcery) {
1732                 return;
1733         }
1734         object_type = ao2_find(sorcery->types, type, OBJ_KEY);
1735         if (!object_type) {
1736                 return;
1737         }
1738
1739         ao2_callback(object_type->observers, OBJ_NODATA | OBJ_UNLINK,
1740                 sorcery_observer_remove, cbs);
1741 }
1742
1743 int ast_sorcery_object_id_compare(const void *obj_left, const void *obj_right, int flags)
1744 {
1745         if (!obj_left || !obj_right) {
1746                 return 0;
1747         }
1748         return strcmp(ast_sorcery_object_get_id(obj_left), ast_sorcery_object_get_id(obj_right));
1749 }