Add support for child provider to up_ref/free their parent
[openssl.git] / crypto / provider_core.c
1 /*
2  * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <assert.h>
11 #include <openssl/core.h>
12 #include <openssl/core_dispatch.h>
13 #include <openssl/core_names.h>
14 #include <openssl/provider.h>
15 #include <openssl/params.h>
16 #include <openssl/opensslv.h>
17 #include "crypto/cryptlib.h"
18 #include "crypto/evp.h" /* evp_method_store_flush */
19 #include "crypto/rand.h"
20 #include "internal/nelem.h"
21 #include "internal/thread_once.h"
22 #include "internal/provider.h"
23 #include "internal/refcount.h"
24 #include "internal/bio.h"
25 #include "internal/core.h"
26 #include "provider_local.h"
27 #ifndef FIPS_MODULE
28 # include <openssl/self_test.h>
29 #endif
30
31 static OSSL_PROVIDER *provider_new(const char *name,
32                                    OSSL_provider_init_fn *init_function);
33
34 /*-
35  * Provider Object structure
36  * =========================
37  */
38
39 typedef struct {
40     char *name;
41     char *value;
42 } INFOPAIR;
43 DEFINE_STACK_OF(INFOPAIR)
44
45 typedef struct {
46     OSSL_PROVIDER *prov;
47     int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
48     void (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
49     void *cbdata;
50 } OSSL_PROVIDER_CHILD_CB;
51 DEFINE_STACK_OF(OSSL_PROVIDER_CHILD_CB)
52
53 struct provider_store_st;        /* Forward declaration */
54
55 struct ossl_provider_st {
56     /* Flag bits */
57     unsigned int flag_initialized:1;
58     unsigned int flag_activated:1;
59     unsigned int flag_fallback:1; /* Can be used as fallback */
60
61     /* Getting and setting the flags require synchronization */
62     CRYPTO_RWLOCK *flag_lock;
63
64     /* OpenSSL library side data */
65     CRYPTO_REF_COUNT refcnt;
66     CRYPTO_RWLOCK *refcnt_lock;  /* For the ref counter */
67     int activatecnt;
68     char *name;
69     char *path;
70     DSO *module;
71     OSSL_provider_init_fn *init_function;
72     STACK_OF(INFOPAIR) *parameters;
73     OSSL_LIB_CTX *libctx; /* The library context this instance is in */
74     struct provider_store_st *store; /* The store this instance belongs to */
75 #ifndef FIPS_MODULE
76     /*
77      * In the FIPS module inner provider, this isn't needed, since the
78      * error upcalls are always direct calls to the outer provider.
79      */
80     int error_lib;     /* ERR library number, one for each provider */
81 # ifndef OPENSSL_NO_ERR
82     ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */
83 # endif
84 #endif
85
86     /* Provider side functions */
87     OSSL_FUNC_provider_teardown_fn *teardown;
88     OSSL_FUNC_provider_gettable_params_fn *gettable_params;
89     OSSL_FUNC_provider_get_params_fn *get_params;
90     OSSL_FUNC_provider_get_capabilities_fn *get_capabilities;
91     OSSL_FUNC_provider_self_test_fn *self_test;
92     OSSL_FUNC_provider_query_operation_fn *query_operation;
93     OSSL_FUNC_provider_unquery_operation_fn *unquery_operation;
94
95     /*
96      * Cache of bit to indicate of query_operation() has been called on
97      * a specific operation or not.
98      */
99     unsigned char *operation_bits;
100     size_t operation_bits_sz;
101     CRYPTO_RWLOCK *opbits_lock;
102
103     /* Whether this provider is the child of some other provider */
104     const OSSL_CORE_HANDLE *handle;
105     unsigned int ischild:1;
106
107     /* Provider side data */
108     void *provctx;
109     const OSSL_DISPATCH *dispatch;
110 };
111 DEFINE_STACK_OF(OSSL_PROVIDER)
112
113 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
114                              const OSSL_PROVIDER * const *b)
115 {
116     return strcmp((*a)->name, (*b)->name);
117 }
118
119 /*-
120  * Provider Object store
121  * =====================
122  *
123  * The Provider Object store is a library context object, and therefore needs
124  * an index.
125  */
126
127 struct provider_store_st {
128     OSSL_LIB_CTX *libctx;
129     STACK_OF(OSSL_PROVIDER) *providers;
130     STACK_OF(OSSL_PROVIDER_CHILD_CB) *child_cbs;
131     CRYPTO_RWLOCK *default_path_lock;
132     CRYPTO_RWLOCK *lock;
133     char *default_path;
134     unsigned int use_fallbacks:1;
135     unsigned int freeing:1;
136 };
137
138 /*
139  * provider_deactivate_free() is a wrapper around ossl_provider_deactivate()
140  * and ossl_provider_free(), called as needed.
141  * Since this is only called when the provider store is being emptied, we
142  * don't need to care about any lock.
143  */
144 static void provider_deactivate_free(OSSL_PROVIDER *prov)
145 {
146     if (prov->flag_activated)
147         ossl_provider_deactivate(prov);
148     ossl_provider_free(prov);
149 }
150
151 static void ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB *cb)
152 {
153     OPENSSL_free(cb);
154 }
155
156 static void provider_store_free(void *vstore)
157 {
158     struct provider_store_st *store = vstore;
159
160     if (store == NULL)
161         return;
162     store->freeing = 1;
163     OPENSSL_free(store->default_path);
164     sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free);
165     sk_OSSL_PROVIDER_CHILD_CB_pop_free(store->child_cbs,
166                                        ossl_provider_child_cb_free);
167     CRYPTO_THREAD_lock_free(store->default_path_lock);
168     CRYPTO_THREAD_lock_free(store->lock);
169     OPENSSL_free(store);
170 }
171
172 static void *provider_store_new(OSSL_LIB_CTX *ctx)
173 {
174     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
175     const struct predefined_providers_st *p = NULL;
176
177     if (store == NULL
178         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
179         || (store->default_path_lock = CRYPTO_THREAD_lock_new()) == NULL
180         || (store->child_cbs = sk_OSSL_PROVIDER_CHILD_CB_new_null()) == NULL
181         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
182         provider_store_free(store);
183         return NULL;
184     }
185     store->libctx = ctx;
186     store->use_fallbacks = 1;
187
188     for (p = ossl_predefined_providers; p->name != NULL; p++) {
189         OSSL_PROVIDER *prov = NULL;
190
191         /*
192          * We use the internal constructor directly here,
193          * otherwise we get a call loop
194          */
195         prov = provider_new(p->name, p->init);
196
197         if (prov == NULL
198             || sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
199             ossl_provider_free(prov);
200             provider_store_free(store);
201             ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
202             return NULL;
203         }
204         prov->libctx = ctx;
205         prov->store = store;
206 #ifndef FIPS_MODULE
207         prov->error_lib = ERR_get_next_error_library();
208 #endif
209         if(p->is_fallback)
210             ossl_provider_set_fallback(prov);
211     }
212
213     return store;
214 }
215
216 static const OSSL_LIB_CTX_METHOD provider_store_method = {
217     /* Needs to be freed before the child provider data is freed */
218     OSSL_LIB_CTX_METHOD_PRIORITY_1,
219     provider_store_new,
220     provider_store_free,
221 };
222
223 static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx)
224 {
225     struct provider_store_st *store = NULL;
226
227     store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX,
228                                   &provider_store_method);
229     if (store == NULL)
230         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
231     return store;
232 }
233
234 int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx)
235 {
236     struct provider_store_st *store;
237
238     if ((store = get_provider_store(libctx)) != NULL) {
239         if (!CRYPTO_THREAD_write_lock(store->lock))
240             return 0;
241         store->use_fallbacks = 0;
242         CRYPTO_THREAD_unlock(store->lock);
243         return 1;
244     }
245     return 0;
246 }
247
248 OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
249                                   int noconfig)
250 {
251     struct provider_store_st *store = NULL;
252     OSSL_PROVIDER *prov = NULL;
253
254     if ((store = get_provider_store(libctx)) != NULL) {
255         OSSL_PROVIDER tmpl = { 0, };
256         int i;
257
258 #ifndef FIPS_MODULE
259         /*
260          * Make sure any providers are loaded from config before we try to find
261          * them.
262          */
263         if (!noconfig) {
264             if (ossl_lib_ctx_is_default(libctx))
265                 OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
266             if (ossl_lib_ctx_is_child(libctx)
267                     && !ossl_provider_init_child_providers(libctx))
268                 return NULL;
269         }
270 #endif
271
272         tmpl.name = (char *)name;
273         if (!CRYPTO_THREAD_read_lock(store->lock))
274             return NULL;
275         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) == -1
276             || (prov = sk_OSSL_PROVIDER_value(store->providers, i)) == NULL
277             || !ossl_provider_up_ref(prov))
278             prov = NULL;
279         CRYPTO_THREAD_unlock(store->lock);
280     }
281
282     return prov;
283 }
284
285 /*-
286  * Provider Object methods
287  * =======================
288  */
289
290 static OSSL_PROVIDER *provider_new(const char *name,
291                                    OSSL_provider_init_fn *init_function)
292 {
293     OSSL_PROVIDER *prov = NULL;
294
295     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
296 #ifndef HAVE_ATOMICS
297         || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
298 #endif
299         || !ossl_provider_up_ref(prov) /* +1 One reference to be returned */
300         || (prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL
301         || (prov->flag_lock = CRYPTO_THREAD_lock_new()) == NULL
302         || (prov->name = OPENSSL_strdup(name)) == NULL) {
303         ossl_provider_free(prov);
304         ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
305         return NULL;
306     }
307
308     prov->init_function = init_function;
309     return prov;
310 }
311
312 int ossl_provider_up_ref(OSSL_PROVIDER *prov)
313 {
314     int ref = 0;
315
316     if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0)
317         return 0;
318
319 #ifndef FIPS_MODULE
320     if (prov->ischild) {
321         if (!ossl_provider_up_ref_parent(prov, 0)) {
322             ossl_provider_free(prov);
323             return 0;
324         }
325     }
326 #endif
327
328     return ref;
329 }
330
331 #ifndef FIPS_MODULE
332 static int provider_up_ref_intern(OSSL_PROVIDER *prov, int activate)
333 {
334     if (activate)
335         return ossl_provider_activate(prov, 0, 1);
336
337     return ossl_provider_up_ref(prov);
338 }
339
340 static int provider_free_intern(OSSL_PROVIDER *prov, int deactivate)
341 {
342     if (deactivate)
343         return ossl_provider_deactivate(prov);
344
345     ossl_provider_free(prov);
346     return 1;
347 }
348 #endif
349
350 OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
351                                  OSSL_provider_init_fn *init_function,
352                                  int noconfig)
353 {
354     struct provider_store_st *store = NULL;
355     OSSL_PROVIDER *prov = NULL;
356
357     if ((store = get_provider_store(libctx)) == NULL)
358         return NULL;
359
360     if ((prov = ossl_provider_find(libctx, name,
361                                    noconfig)) != NULL) { /* refcount +1 */
362         ossl_provider_free(prov); /* refcount -1 */
363         ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_ALREADY_EXISTS,
364                        "name=%s", name);
365         return NULL;
366     }
367
368     /* provider_new() generates an error, so no need here */
369     if ((prov = provider_new(name, init_function)) == NULL)
370         return NULL;
371
372     if (!CRYPTO_THREAD_write_lock(store->lock))
373         return NULL;
374     if (!ossl_provider_up_ref(prov)) { /* +1 One reference for the store */
375         ossl_provider_free(prov); /* -1 Reference that was to be returned */
376         prov = NULL;
377     } else if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
378         ossl_provider_free(prov); /* -1 Store reference */
379         ossl_provider_free(prov); /* -1 Reference that was to be returned */
380         prov = NULL;
381     } else {
382         prov->libctx = libctx;
383         prov->store = store;
384 #ifndef FIPS_MODULE
385         prov->error_lib = ERR_get_next_error_library();
386 #endif
387     }
388     CRYPTO_THREAD_unlock(store->lock);
389
390     if (prov == NULL)
391         ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
392
393     /*
394      * At this point, the provider is only partially "loaded".  To be
395      * fully "loaded", ossl_provider_activate() must also be called.
396      */
397
398     return prov;
399 }
400
401 static void free_infopair(INFOPAIR *pair)
402 {
403     OPENSSL_free(pair->name);
404     OPENSSL_free(pair->value);
405     OPENSSL_free(pair);
406 }
407
408 void ossl_provider_free(OSSL_PROVIDER *prov)
409 {
410     if (prov != NULL) {
411         int ref = 0;
412
413         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
414
415         /*
416          * When the refcount drops to zero, we clean up the provider.
417          * Note that this also does teardown, which may seem late,
418          * considering that init happens on first activation.  However,
419          * there may be other structures hanging on to the provider after
420          * the last deactivation and may therefore need full access to the
421          * provider's services.  Therefore, we deinit late.
422          */
423         if (ref == 0) {
424             if (prov->flag_initialized) {
425                 ossl_provider_teardown(prov);
426 #ifndef OPENSSL_NO_ERR
427 # ifndef FIPS_MODULE
428                 if (prov->error_strings != NULL) {
429                     ERR_unload_strings(prov->error_lib, prov->error_strings);
430                     OPENSSL_free(prov->error_strings);
431                     prov->error_strings = NULL;
432                 }
433 # endif
434 #endif
435                 OPENSSL_free(prov->operation_bits);
436                 prov->operation_bits = NULL;
437                 prov->operation_bits_sz = 0;
438                 prov->flag_initialized = 0;
439             }
440
441 #ifndef FIPS_MODULE
442             /*
443              * We deregister thread handling whether or not the provider was
444              * initialized. If init was attempted but was not successful then
445              * the provider may still have registered a thread handler.
446              */
447             ossl_init_thread_deregister(prov);
448             DSO_free(prov->module);
449 #endif
450             OPENSSL_free(prov->name);
451             OPENSSL_free(prov->path);
452             sk_INFOPAIR_pop_free(prov->parameters, free_infopair);
453             CRYPTO_THREAD_lock_free(prov->opbits_lock);
454             CRYPTO_THREAD_lock_free(prov->flag_lock);
455 #ifndef HAVE_ATOMICS
456             CRYPTO_THREAD_lock_free(prov->refcnt_lock);
457 #endif
458             OPENSSL_free(prov);
459         }
460 #ifndef FIPS_MODULE
461         else if (prov->ischild) {
462             ossl_provider_free_parent(prov, 0);
463         }
464 #endif
465     }
466 }
467
468 /* Setters */
469 int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path)
470 {
471     OPENSSL_free(prov->path);
472     if (module_path == NULL)
473         return 1;
474     if ((prov->path = OPENSSL_strdup(module_path)) != NULL)
475         return 1;
476     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
477     return 0;
478 }
479
480 int ossl_provider_add_parameter(OSSL_PROVIDER *prov,
481                                 const char *name, const char *value)
482 {
483     INFOPAIR *pair = NULL;
484
485     if ((pair = OPENSSL_zalloc(sizeof(*pair))) != NULL
486         && (prov->parameters != NULL
487             || (prov->parameters = sk_INFOPAIR_new_null()) != NULL)
488         && (pair->name = OPENSSL_strdup(name)) != NULL
489         && (pair->value = OPENSSL_strdup(value)) != NULL
490         && sk_INFOPAIR_push(prov->parameters, pair) > 0)
491         return 1;
492
493     if (pair != NULL) {
494         OPENSSL_free(pair->name);
495         OPENSSL_free(pair->value);
496         OPENSSL_free(pair);
497     }
498     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
499     return 0;
500 }
501
502 /*
503  * Provider activation.
504  *
505  * What "activation" means depends on the provider form; for built in
506  * providers (in the library or the application alike), the provider
507  * can already be considered to be loaded, all that's needed is to
508  * initialize it.  However, for dynamically loadable provider modules,
509  * we must first load that module.
510  *
511  * Built in modules are distinguished from dynamically loaded modules
512  * with an already assigned init function.
513  */
514 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
515
516 int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx,
517                                           const char *path)
518 {
519     struct provider_store_st *store;
520     char *p = NULL;
521
522     if (path != NULL) {
523         p = OPENSSL_strdup(path);
524         if (p == NULL) {
525             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
526             return 0;
527         }
528     }
529     if ((store = get_provider_store(libctx)) != NULL
530             && CRYPTO_THREAD_write_lock(store->default_path_lock)) {
531         OPENSSL_free(store->default_path);
532         store->default_path = p;
533         CRYPTO_THREAD_unlock(store->default_path_lock);
534         return 1;
535     }
536     OPENSSL_free(p);
537     return 0;
538 }
539
540 /*
541  * Internal version that doesn't affect the store flags, and thereby avoid
542  * locking.  Direct callers must remember to set the store flags when
543  * appropriate.
544  */
545 static int provider_init(OSSL_PROVIDER *prov, int flag_lock)
546 {
547     const OSSL_DISPATCH *provider_dispatch = NULL;
548     void *tmp_provctx = NULL;    /* safety measure */
549 #ifndef OPENSSL_NO_ERR
550 # ifndef FIPS_MODULE
551     OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL;
552 # endif
553 #endif
554     int ok = 0;
555
556     /*
557      * The flag lock is used to lock init, not only because the flag is
558      * checked here and set at the end, but also because this function
559      * modifies a number of things in the provider structure that this
560      * function needs to perform under lock anyway.
561      */
562     if (flag_lock && !CRYPTO_THREAD_write_lock(prov->flag_lock))
563         goto end;
564     if (prov->flag_initialized) {
565         ok = 1;
566         goto end;
567     }
568
569     /*
570      * If the init function isn't set, it indicates that this provider is
571      * a loadable module.
572      */
573     if (prov->init_function == NULL) {
574 #ifdef FIPS_MODULE
575         goto end;
576 #else
577         if (prov->module == NULL) {
578             char *allocated_path = NULL;
579             const char *module_path = NULL;
580             char *merged_path = NULL;
581             const char *load_dir = NULL;
582             char *allocated_load_dir = NULL;
583             struct provider_store_st *store;
584
585             if ((prov->module = DSO_new()) == NULL) {
586                 /* DSO_new() generates an error already */
587                 goto end;
588             }
589
590             if ((store = get_provider_store(prov->libctx)) == NULL
591                     || !CRYPTO_THREAD_read_lock(store->default_path_lock))
592                 goto end;
593
594             if (store->default_path != NULL) {
595                 allocated_load_dir = OPENSSL_strdup(store->default_path);
596                 CRYPTO_THREAD_unlock(store->default_path_lock);
597                 if (allocated_load_dir == NULL) {
598                     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
599                     goto end;
600                 }
601                 load_dir = allocated_load_dir;
602             } else {
603                 CRYPTO_THREAD_unlock(store->default_path_lock);
604             }
605
606             if (load_dir == NULL) {
607                 load_dir = ossl_safe_getenv("OPENSSL_MODULES");
608                 if (load_dir == NULL)
609                     load_dir = MODULESDIR;
610             }
611
612             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
613                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
614
615             module_path = prov->path;
616             if (module_path == NULL)
617                 module_path = allocated_path =
618                     DSO_convert_filename(prov->module, prov->name);
619             if (module_path != NULL)
620                 merged_path = DSO_merge(prov->module, module_path, load_dir);
621
622             if (merged_path == NULL
623                 || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) {
624                 DSO_free(prov->module);
625                 prov->module = NULL;
626             }
627
628             OPENSSL_free(merged_path);
629             OPENSSL_free(allocated_path);
630             OPENSSL_free(allocated_load_dir);
631         }
632
633         if (prov->module != NULL)
634             prov->init_function = (OSSL_provider_init_fn *)
635                 DSO_bind_func(prov->module, "OSSL_provider_init");
636 #endif
637     }
638
639     /* Call the initialise function for the provider. */
640     if (prov->init_function == NULL
641         || !prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch,
642                                 &provider_dispatch, &tmp_provctx)) {
643         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL,
644                        "name=%s", prov->name);
645         goto end;
646     }
647     prov->provctx = tmp_provctx;
648     prov->dispatch = provider_dispatch;
649
650     for (; provider_dispatch->function_id != 0; provider_dispatch++) {
651         switch (provider_dispatch->function_id) {
652         case OSSL_FUNC_PROVIDER_TEARDOWN:
653             prov->teardown =
654                 OSSL_FUNC_provider_teardown(provider_dispatch);
655             break;
656         case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS:
657             prov->gettable_params =
658                 OSSL_FUNC_provider_gettable_params(provider_dispatch);
659             break;
660         case OSSL_FUNC_PROVIDER_GET_PARAMS:
661             prov->get_params =
662                 OSSL_FUNC_provider_get_params(provider_dispatch);
663             break;
664         case OSSL_FUNC_PROVIDER_SELF_TEST:
665             prov->self_test =
666                 OSSL_FUNC_provider_self_test(provider_dispatch);
667             break;
668         case OSSL_FUNC_PROVIDER_GET_CAPABILITIES:
669             prov->get_capabilities =
670                 OSSL_FUNC_provider_get_capabilities(provider_dispatch);
671             break;
672         case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
673             prov->query_operation =
674                 OSSL_FUNC_provider_query_operation(provider_dispatch);
675             break;
676         case OSSL_FUNC_PROVIDER_UNQUERY_OPERATION:
677             prov->unquery_operation =
678                 OSSL_FUNC_provider_unquery_operation(provider_dispatch);
679             break;
680 #ifndef OPENSSL_NO_ERR
681 # ifndef FIPS_MODULE
682         case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS:
683             p_get_reason_strings =
684                 OSSL_FUNC_provider_get_reason_strings(provider_dispatch);
685             break;
686 # endif
687 #endif
688         }
689     }
690
691 #ifndef OPENSSL_NO_ERR
692 # ifndef FIPS_MODULE
693     if (p_get_reason_strings != NULL) {
694         const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx);
695         size_t cnt, cnt2;
696
697         /*
698          * ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM,
699          * although they are essentially the same type.
700          * Furthermore, ERR_load_strings() patches the array's error number
701          * with the error library number, so we need to make a copy of that
702          * array either way.
703          */
704         cnt = 0;
705         while (reasonstrings[cnt].id != 0) {
706             if (ERR_GET_LIB(reasonstrings[cnt].id) != 0)
707                 goto end;
708             cnt++;
709         }
710         cnt++;                   /* One for the terminating item */
711
712         /* Allocate one extra item for the "library" name */
713         prov->error_strings =
714             OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1));
715         if (prov->error_strings == NULL)
716             goto end;
717
718         /*
719          * Set the "library" name.
720          */
721         prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0);
722         prov->error_strings[0].string = prov->name;
723         /*
724          * Copy reasonstrings item 0..cnt-1 to prov->error_trings positions
725          * 1..cnt.
726          */
727         for (cnt2 = 1; cnt2 <= cnt; cnt2++) {
728             prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id;
729             prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr;
730         }
731
732         ERR_load_strings(prov->error_lib, prov->error_strings);
733     }
734 # endif
735 #endif
736
737     /* With this flag set, this provider has become fully "loaded". */
738     prov->flag_initialized = 1;
739     ok = 1;
740
741  end:
742     if (flag_lock)
743         CRYPTO_THREAD_unlock(prov->flag_lock);
744     return ok;
745 }
746
747 /*
748  * Deactivate a provider.
749  * Return -1 on failure and the activation count on success
750  */
751 static int provider_deactivate(OSSL_PROVIDER *prov)
752 {
753     int count;
754     struct provider_store_st *store;
755
756     if (!ossl_assert(prov != NULL))
757         return -1;
758
759     store = get_provider_store(prov->libctx);
760     if (store == NULL)
761         return 0;
762
763     if (!CRYPTO_THREAD_read_lock(store->lock))
764         return 0;
765     if (!CRYPTO_THREAD_write_lock(prov->flag_lock))
766         return -1;
767
768 #ifndef FIPS_MODULE
769     if (prov->activatecnt == 2 && prov->ischild) {
770         /*
771          * We have had a direct activation in this child libctx so we need to
772          * now down the ref count in the parent provider.
773          */
774         ossl_provider_free_parent(prov, 1);
775     }
776 #endif
777
778     if ((count = --prov->activatecnt) < 1) {
779         int i, max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
780         OSSL_PROVIDER_CHILD_CB *child_cb;
781
782         prov->flag_activated = 0;
783         for (i = 0; i < max; i++) {
784             child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
785             child_cb->remove_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
786         }
787     }
788
789     CRYPTO_THREAD_unlock(prov->flag_lock);
790     CRYPTO_THREAD_unlock(store->lock);
791
792     /* We don't deinit here, that's done in ossl_provider_free() */
793     return count;
794 }
795
796 /*
797  * Activate a provider.
798  * Return -1 on failure and the activation count on success
799  */
800 static int provider_activate(OSSL_PROVIDER *prov, int lock, int upcalls)
801 {
802     int count = -1;
803
804     if (provider_init(prov, lock)) {
805         int ret = 1;
806         int i, max;
807         OSSL_PROVIDER_CHILD_CB *child_cb;
808         struct provider_store_st *store;
809
810         store = get_provider_store(prov->libctx);
811         if (store == NULL)
812             return 0;
813
814         if (lock && !CRYPTO_THREAD_read_lock(store->lock))
815             return 0;
816
817         max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
818         if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock))
819             return 0;
820
821 #ifndef FIPS_MODULE
822         if (prov->ischild && upcalls)
823             ret = ossl_provider_up_ref_parent(prov, 1);
824 #endif
825
826         if (ret) {
827             count = ++prov->activatecnt;
828             prov->flag_activated = 1;
829
830             if (prov->activatecnt == 1) {
831                 for (i = 0; i < max; i++) {
832                     /*
833                      * This is newly activated (activatecnt == 1), so we need to
834                      * create child providers as necessary.
835                      */
836                     child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs,
837                                                                i);
838                     ret &= child_cb->create_cb((OSSL_CORE_HANDLE *)prov,
839                                                child_cb->cbdata);
840                 }
841             }
842         }
843
844         if (lock) {
845             CRYPTO_THREAD_unlock(prov->flag_lock);
846             CRYPTO_THREAD_unlock(store->lock);
847         }
848         if (!ret)
849             return -1;
850     }
851
852     return count;
853 }
854
855 static int provider_flush_store_cache(const OSSL_PROVIDER *prov)
856 {
857     struct provider_store_st *store;
858     int freeing;
859
860     if ((store = get_provider_store(prov->libctx)) == NULL)
861         return 0;
862
863     if (!CRYPTO_THREAD_read_lock(store->lock))
864         return 0;
865     freeing = store->freeing;
866     CRYPTO_THREAD_unlock(store->lock);
867
868     if (!freeing)
869         return evp_method_store_flush(prov->libctx);
870     return 1;
871 }
872
873 int ossl_provider_activate(OSSL_PROVIDER *prov, int retain_fallbacks,
874                            int upcalls)
875 {
876     int count;
877
878     if (prov == NULL)
879         return 0;
880     if ((count = provider_activate(prov, 1, upcalls)) > 0) {
881         if (!retain_fallbacks) {
882             if (!CRYPTO_THREAD_write_lock(prov->store->lock)) {
883                 provider_deactivate(prov);
884                 return 0;
885             }
886             prov->store->use_fallbacks = 0;
887             CRYPTO_THREAD_unlock(prov->store->lock);
888         }
889         return count == 1 ? provider_flush_store_cache(prov) : 1;
890     }
891     return 0;
892 }
893
894 int ossl_provider_deactivate(OSSL_PROVIDER *prov)
895 {
896     int count;
897
898     if (prov == NULL || (count = provider_deactivate(prov)) < 0)
899         return 0;
900     return count == 0 ? provider_flush_store_cache(prov) : 1;
901 }
902
903 void *ossl_provider_ctx(const OSSL_PROVIDER *prov)
904 {
905     return prov->provctx;
906 }
907
908 /*
909  * This function only does something once when store->use_fallbacks == 1,
910  * and then sets store->use_fallbacks = 0, so the second call and so on is
911  * effectively a no-op.
912  */
913 static void provider_activate_fallbacks(struct provider_store_st *store)
914 {
915     int use_fallbacks;
916     int num_provs;
917     int activated_fallback_count = 0;
918     int i;
919
920     if (!CRYPTO_THREAD_read_lock(store->lock))
921         return;
922     use_fallbacks = store->use_fallbacks;
923     CRYPTO_THREAD_unlock(store->lock);
924     if (!use_fallbacks)
925         return;
926
927     if (!CRYPTO_THREAD_write_lock(store->lock))
928         return;
929     /* Check again, just in case another thread changed it */
930     use_fallbacks = store->use_fallbacks;
931     if (!use_fallbacks) {
932         CRYPTO_THREAD_unlock(store->lock);
933         return;
934     }
935
936     num_provs = sk_OSSL_PROVIDER_num(store->providers);
937     for (i = 0; i < num_provs; i++) {
938         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(store->providers, i);
939
940         if (ossl_provider_up_ref(prov)) {
941             if (CRYPTO_THREAD_write_lock(prov->flag_lock)) {
942                 if (prov->flag_fallback) {
943                     if (provider_activate(prov, 0, 0) > 0)
944                         activated_fallback_count++;
945                 }
946                 CRYPTO_THREAD_unlock(prov->flag_lock);
947             }
948             ossl_provider_free(prov);
949         }
950     }
951
952     /*
953      * We assume that all fallbacks have been added to the store before
954      * any fallback is activated.
955      * TODO: We may have to reconsider this, IF we find ourselves adding
956      * fallbacks after any previous fallback has been activated.
957      */
958     if (activated_fallback_count > 0)
959         store->use_fallbacks = 0;
960
961     CRYPTO_THREAD_unlock(store->lock);
962 }
963
964 int ossl_provider_doall_activated(OSSL_LIB_CTX *ctx,
965                                   int (*cb)(OSSL_PROVIDER *provider,
966                                             void *cbdata),
967                                   void *cbdata)
968 {
969     int ret = 0, curr, max;
970     struct provider_store_st *store = get_provider_store(ctx);
971     STACK_OF(OSSL_PROVIDER) *provs = NULL;
972
973 #ifndef FIPS_MODULE
974     /*
975      * Make sure any providers are loaded from config before we try to use
976      * them.
977      */
978     if (ossl_lib_ctx_is_default(ctx))
979         OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
980     if (ossl_lib_ctx_is_child(ctx)
981             && !ossl_provider_init_child_providers(ctx))
982         return 0;
983 #endif
984
985     if (store == NULL)
986         return 1;
987     provider_activate_fallbacks(store);
988
989     /*
990      * Under lock, grab a copy of the provider list and up_ref each
991      * provider so that they don't disappear underneath us.
992      */
993     if (!CRYPTO_THREAD_read_lock(store->lock))
994         return 0;
995     provs = sk_OSSL_PROVIDER_dup(store->providers);
996     if (provs == NULL) {
997         CRYPTO_THREAD_unlock(store->lock);
998         return 0;
999     }
1000     max = sk_OSSL_PROVIDER_num(provs);
1001     /*
1002      * We work backwards through the stack so that we can safely delete items
1003      * as we go.
1004      */
1005     for (curr = max - 1; curr >= 0; curr--) {
1006         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1007
1008         if (!CRYPTO_THREAD_write_lock(prov->flag_lock))
1009             goto err_unlock;
1010         if (prov->flag_activated) {
1011             if (!ossl_provider_up_ref(prov)){
1012                 CRYPTO_THREAD_unlock(prov->flag_lock);
1013                 goto err_unlock;
1014             }
1015             /*
1016              * It's already activated, but we up the activated count to ensure
1017              * it remains activated until after we've called the user callback.
1018              */
1019             if (provider_activate(prov, 0, 1) < 0) {
1020                 ossl_provider_free(prov);
1021                 CRYPTO_THREAD_unlock(prov->flag_lock);
1022                 goto err_unlock;
1023             }
1024         } else {
1025             sk_OSSL_PROVIDER_delete(provs, curr);
1026             max--;
1027         }
1028         CRYPTO_THREAD_unlock(prov->flag_lock);
1029     }
1030     CRYPTO_THREAD_unlock(store->lock);
1031
1032     /*
1033      * Now, we sweep through all providers not under lock
1034      */
1035     for (curr = 0; curr < max; curr++) {
1036         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1037
1038         if (!cb(prov, cbdata))
1039             goto finish;
1040     }
1041     curr = -1;
1042
1043     ret = 1;
1044     goto finish;
1045
1046  err_unlock:
1047     CRYPTO_THREAD_unlock(store->lock);
1048  finish:
1049     /*
1050      * The pop_free call doesn't do what we want on an error condition. We
1051      * either start from the first item in the stack, or part way through if
1052      * we only processed some of the items.
1053      */
1054     for (curr++; curr < max; curr++) {
1055         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1056
1057         provider_deactivate(prov);
1058         ossl_provider_free(prov);
1059     }
1060     sk_OSSL_PROVIDER_free(provs);
1061     return ret;
1062 }
1063
1064 int ossl_provider_available(OSSL_PROVIDER *prov)
1065 {
1066     int ret;
1067
1068     if (prov != NULL) {
1069         provider_activate_fallbacks(prov->store);
1070
1071         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
1072             return 0;
1073         ret = prov->flag_activated;
1074         CRYPTO_THREAD_unlock(prov->flag_lock);
1075         return ret;
1076     }
1077     return 0;
1078 }
1079
1080 /* Setters of Provider Object data */
1081 int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
1082 {
1083     if (prov == NULL)
1084         return 0;
1085
1086     prov->flag_fallback = 1;
1087     return 1;
1088 }
1089
1090 /* Getters of Provider Object data */
1091 const char *ossl_provider_name(const OSSL_PROVIDER *prov)
1092 {
1093     return prov->name;
1094 }
1095
1096 const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov)
1097 {
1098     return prov->module;
1099 }
1100
1101 const char *ossl_provider_module_name(const OSSL_PROVIDER *prov)
1102 {
1103 #ifdef FIPS_MODULE
1104     return NULL;
1105 #else
1106     return DSO_get_filename(prov->module);
1107 #endif
1108 }
1109
1110 const char *ossl_provider_module_path(const OSSL_PROVIDER *prov)
1111 {
1112 #ifdef FIPS_MODULE
1113     return NULL;
1114 #else
1115     /* FIXME: Ensure it's a full path */
1116     return DSO_get_filename(prov->module);
1117 #endif
1118 }
1119
1120 void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov)
1121 {
1122     if (prov != NULL)
1123         return prov->provctx;
1124
1125     return NULL;
1126 }
1127
1128 const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov)
1129 {
1130     if (prov != NULL)
1131         return prov->dispatch;
1132
1133     return NULL;
1134 }
1135
1136 OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov)
1137 {
1138     return prov != NULL ? prov->libctx : NULL;
1139 }
1140
1141 /* Wrappers around calls to the provider */
1142 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
1143 {
1144     if (prov->teardown != NULL && !prov->ischild)
1145         prov->teardown(prov->provctx);
1146 }
1147
1148 const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov)
1149 {
1150     return prov->gettable_params == NULL
1151         ? NULL : prov->gettable_params(prov->provctx);
1152 }
1153
1154 int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[])
1155 {
1156     return prov->get_params == NULL
1157         ? 0 : prov->get_params(prov->provctx, params);
1158 }
1159
1160 int ossl_provider_self_test(const OSSL_PROVIDER *prov)
1161 {
1162     int ret;
1163
1164     if (prov->self_test == NULL)
1165         return 1;
1166     ret = prov->self_test(prov->provctx);
1167     if (ret == 0)
1168         (void)provider_flush_store_cache(prov);
1169     return ret;
1170 }
1171
1172 int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
1173                                    const char *capability,
1174                                    OSSL_CALLBACK *cb,
1175                                    void *arg)
1176 {
1177     return prov->get_capabilities == NULL
1178         ? 1 : prov->get_capabilities(prov->provctx, capability, cb, arg);
1179 }
1180
1181 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
1182                                                     int operation_id,
1183                                                     int *no_cache)
1184 {
1185     const OSSL_ALGORITHM *res;
1186
1187     if (prov->query_operation == NULL)
1188         return NULL;
1189     res = prov->query_operation(prov->provctx, operation_id, no_cache);
1190 #if defined(OPENSSL_NO_CACHED_FETCH)
1191     /* Forcing the non-caching of queries */
1192     if (no_cache != NULL)
1193         *no_cache = 1;
1194 #endif
1195     return res;
1196 }
1197
1198 void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov,
1199                                      int operation_id,
1200                                      const OSSL_ALGORITHM *algs)
1201 {
1202     if (prov->unquery_operation != NULL)
1203         prov->unquery_operation(prov->provctx, operation_id, algs);
1204 }
1205
1206 int ossl_provider_clear_all_operation_bits(OSSL_LIB_CTX *libctx)
1207 {
1208     struct provider_store_st *store;
1209     OSSL_PROVIDER *provider;
1210     int i, num, res = 1;
1211
1212     if ((store = get_provider_store(libctx)) != NULL) {
1213         if (!CRYPTO_THREAD_read_lock(store->lock))
1214             return 0;
1215         num = sk_OSSL_PROVIDER_num(store->providers);
1216         for (i = 0; i < num; i++) {
1217             provider = sk_OSSL_PROVIDER_value(store->providers, i);
1218             if (!CRYPTO_THREAD_write_lock(provider->opbits_lock)) {
1219                 res = 0;
1220                 continue;
1221             }
1222             if (provider->operation_bits != NULL)
1223                 memset(provider->operation_bits, 0,
1224                        provider->operation_bits_sz);
1225             CRYPTO_THREAD_unlock(provider->opbits_lock);
1226         }
1227         CRYPTO_THREAD_unlock(store->lock);
1228         return res;
1229     }
1230     return 0;
1231 }
1232
1233 int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum)
1234 {
1235     size_t byte = bitnum / 8;
1236     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
1237
1238     if (!CRYPTO_THREAD_write_lock(provider->opbits_lock))
1239         return 0;
1240     if (provider->operation_bits_sz <= byte) {
1241         unsigned char *tmp = OPENSSL_realloc(provider->operation_bits,
1242                                              byte + 1);
1243
1244         if (tmp == NULL) {
1245             CRYPTO_THREAD_unlock(provider->opbits_lock);
1246             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
1247             return 0;
1248         }
1249         provider->operation_bits = tmp;
1250         memset(provider->operation_bits + provider->operation_bits_sz,
1251                '\0', byte + 1 - provider->operation_bits_sz);
1252         provider->operation_bits_sz = byte + 1;
1253     }
1254     provider->operation_bits[byte] |= bit;
1255     CRYPTO_THREAD_unlock(provider->opbits_lock);
1256     return 1;
1257 }
1258
1259 int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
1260                                      int *result)
1261 {
1262     size_t byte = bitnum / 8;
1263     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
1264
1265     if (!ossl_assert(result != NULL)) {
1266         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
1267         return 0;
1268     }
1269
1270     *result = 0;
1271     if (!CRYPTO_THREAD_read_lock(provider->opbits_lock))
1272         return 0;
1273     if (provider->operation_bits_sz > byte)
1274         *result = ((provider->operation_bits[byte] & bit) != 0);
1275     CRYPTO_THREAD_unlock(provider->opbits_lock);
1276     return 1;
1277 }
1278
1279 const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov)
1280 {
1281     return prov->handle;
1282 }
1283
1284 int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle)
1285 {
1286     struct provider_store_st *store = NULL;
1287
1288     if ((store = get_provider_store(prov->libctx)) == NULL)
1289         return 0;
1290
1291     prov->handle = handle;
1292     prov->ischild = 1;
1293
1294     if (!CRYPTO_THREAD_write_lock(store->lock))
1295         return 0;
1296
1297     CRYPTO_THREAD_unlock(store->lock);
1298     return 1;
1299 }
1300
1301 #ifndef FIPS_MODULE
1302 static int ossl_provider_register_child_cb(const OSSL_CORE_HANDLE *handle,
1303                                            int (*create_cb)(
1304                                                const OSSL_CORE_HANDLE *provider,
1305                                                void *cbdata),
1306                                            void (*remove_cb)(
1307                                                const OSSL_CORE_HANDLE *provider,
1308                                                void *cbdata),
1309                                            void *cbdata)
1310 {
1311     /*
1312      * This is really an OSSL_PROVIDER that we created and cast to
1313      * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
1314      */
1315     OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
1316     OSSL_PROVIDER *prov;
1317     OSSL_LIB_CTX *libctx = thisprov->libctx;
1318     struct provider_store_st *store = NULL;
1319     int ret = 0, i, max;
1320     OSSL_PROVIDER_CHILD_CB *child_cb;
1321
1322     if ((store = get_provider_store(libctx)) == NULL)
1323         return 0;
1324
1325     child_cb = OPENSSL_malloc(sizeof(*child_cb));
1326     if (child_cb == NULL)
1327         return 0;
1328     child_cb->prov = thisprov;
1329     child_cb->create_cb = create_cb;
1330     child_cb->remove_cb = remove_cb;
1331     child_cb->cbdata = cbdata;
1332
1333     if (!CRYPTO_THREAD_write_lock(store->lock)) {
1334         OPENSSL_free(child_cb);
1335         return 0;
1336     }
1337     max = sk_OSSL_PROVIDER_num(store->providers);
1338     for (i = 0; i < max; i++) {
1339         prov = sk_OSSL_PROVIDER_value(store->providers, i);
1340         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
1341             break;
1342         /*
1343          * We hold the lock while calling the user callback. This means that the
1344          * user callback must be short and simple and not do anything likely to
1345          * cause a deadlock.
1346          */
1347         if (prov->flag_activated
1348                 && !create_cb((OSSL_CORE_HANDLE *)prov, cbdata))
1349             break;
1350         CRYPTO_THREAD_unlock(prov->flag_lock);
1351     }
1352     if (i == max) {
1353         /* Success */
1354         ret = sk_OSSL_PROVIDER_CHILD_CB_push(store->child_cbs, child_cb);
1355     }
1356     if (i != max || ret <= 0) {
1357         /* Failed during creation. Remove everything we just added */
1358         for (; i >= 0; i--) {
1359             prov = sk_OSSL_PROVIDER_value(store->providers, i);
1360             remove_cb((OSSL_CORE_HANDLE *)prov, cbdata);
1361         }
1362         OPENSSL_free(child_cb);
1363         ret = 0;
1364     }
1365     CRYPTO_THREAD_unlock(store->lock);
1366
1367     return ret;
1368 }
1369
1370 static void ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE *handle)
1371 {
1372     /*
1373      * This is really an OSSL_PROVIDER that we created and cast to
1374      * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
1375      */
1376     OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
1377     OSSL_LIB_CTX *libctx = thisprov->libctx;
1378     struct provider_store_st *store = NULL;
1379     int i, max;
1380     OSSL_PROVIDER_CHILD_CB *child_cb;
1381
1382     if ((store = get_provider_store(libctx)) == NULL)
1383         return;
1384
1385     if (!CRYPTO_THREAD_write_lock(store->lock))
1386         return;
1387     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
1388     for (i = 0; i < max; i++) {
1389         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
1390         if (child_cb->prov == thisprov) {
1391             /* Found an entry */
1392             sk_OSSL_PROVIDER_CHILD_CB_delete(store->child_cbs, i);
1393             OPENSSL_free(child_cb);
1394             break;
1395         }
1396     }
1397     CRYPTO_THREAD_unlock(store->lock);
1398 }
1399 #endif
1400
1401 /*-
1402  * Core functions for the provider
1403  * ===============================
1404  *
1405  * This is the set of functions that the core makes available to the provider
1406  */
1407
1408 /*
1409  * This returns a list of Provider Object parameters with their types, for
1410  * discovery.  We do not expect that many providers will use this, but one
1411  * never knows.
1412  */
1413 static const OSSL_PARAM param_types[] = {
1414     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0),
1415     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR,
1416                     NULL, 0),
1417 #ifndef FIPS_MODULE
1418     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR,
1419                     NULL, 0),
1420 #endif
1421     OSSL_PARAM_END
1422 };
1423
1424 /*
1425  * Forward declare all the functions that are provided aa dispatch.
1426  * This ensures that the compiler will complain if they aren't defined
1427  * with the correct signature.
1428  */
1429 static OSSL_FUNC_core_gettable_params_fn core_gettable_params;
1430 static OSSL_FUNC_core_get_params_fn core_get_params;
1431 static OSSL_FUNC_core_thread_start_fn core_thread_start;
1432 static OSSL_FUNC_core_get_libctx_fn core_get_libctx;
1433 #ifndef FIPS_MODULE
1434 static OSSL_FUNC_core_new_error_fn core_new_error;
1435 static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug;
1436 static OSSL_FUNC_core_vset_error_fn core_vset_error;
1437 static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark;
1438 static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark;
1439 static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark;
1440 #endif
1441
1442 static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle)
1443 {
1444     return param_types;
1445 }
1446
1447 static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[])
1448 {
1449     int i;
1450     OSSL_PARAM *p;
1451     /*
1452      * We created this object originally and we know it is actually an
1453      * OSSL_PROVIDER *, so the cast is safe
1454      */
1455     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1456
1457     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL)
1458         OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR);
1459     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL)
1460         OSSL_PARAM_set_utf8_ptr(p, prov->name);
1461
1462 #ifndef FIPS_MODULE
1463     if ((p = OSSL_PARAM_locate(params,
1464                                OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL)
1465         OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov));
1466 #endif
1467
1468     if (prov->parameters == NULL)
1469         return 1;
1470
1471     for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) {
1472         INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i);
1473
1474         if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL)
1475             OSSL_PARAM_set_utf8_ptr(p, pair->value);
1476     }
1477     return 1;
1478 }
1479
1480 static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle)
1481 {
1482     /*
1483      * We created this object originally and we know it is actually an
1484      * OSSL_PROVIDER *, so the cast is safe
1485      */
1486     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1487
1488     /*
1489      * Using ossl_provider_libctx would be wrong as that returns
1490      * NULL for |prov| == NULL and NULL libctx has a special meaning
1491      * that does not apply here. Here |prov| == NULL can happen only in
1492      * case of a coding error.
1493      */
1494     assert(prov != NULL);
1495     return (OPENSSL_CORE_CTX *)prov->libctx;
1496 }
1497
1498 static int core_thread_start(const OSSL_CORE_HANDLE *handle,
1499                              OSSL_thread_stop_handler_fn handfn)
1500 {
1501     /*
1502      * We created this object originally and we know it is actually an
1503      * OSSL_PROVIDER *, so the cast is safe
1504      */
1505     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1506
1507     return ossl_init_thread_start(prov, prov->provctx, handfn);
1508 }
1509
1510 /*
1511  * The FIPS module inner provider doesn't implement these.  They aren't
1512  * needed there, since the FIPS module upcalls are always the outer provider
1513  * ones.
1514  */
1515 #ifndef FIPS_MODULE
1516 /*
1517  * These error functions should use |handle| to select the proper
1518  * library context to report in the correct error stack if error
1519  * stacks become tied to the library context.
1520  * We cannot currently do that since there's no support for it in the
1521  * ERR subsystem.
1522  */
1523 static void core_new_error(const OSSL_CORE_HANDLE *handle)
1524 {
1525     ERR_new();
1526 }
1527
1528 static void core_set_error_debug(const OSSL_CORE_HANDLE *handle,
1529                                  const char *file, int line, const char *func)
1530 {
1531     ERR_set_debug(file, line, func);
1532 }
1533
1534 static void core_vset_error(const OSSL_CORE_HANDLE *handle,
1535                             uint32_t reason, const char *fmt, va_list args)
1536 {
1537     /*
1538      * We created this object originally and we know it is actually an
1539      * OSSL_PROVIDER *, so the cast is safe
1540      */
1541     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1542
1543     /*
1544      * If the uppermost 8 bits are non-zero, it's an OpenSSL library
1545      * error and will be treated as such.  Otherwise, it's a new style
1546      * provider error and will be treated as such.
1547      */
1548     if (ERR_GET_LIB(reason) != 0) {
1549         ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args);
1550     } else {
1551         ERR_vset_error(prov->error_lib, (int)reason, fmt, args);
1552     }
1553 }
1554
1555 static int core_set_error_mark(const OSSL_CORE_HANDLE *handle)
1556 {
1557     return ERR_set_mark();
1558 }
1559
1560 static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle)
1561 {
1562     return ERR_clear_last_mark();
1563 }
1564
1565 static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle)
1566 {
1567     return ERR_pop_to_mark();
1568 }
1569 #endif /* FIPS_MODULE */
1570
1571 /*
1572  * Functions provided by the core.
1573  */
1574 static const OSSL_DISPATCH core_dispatch_[] = {
1575     { OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params },
1576     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
1577     { OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx },
1578     { OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start },
1579 #ifndef FIPS_MODULE
1580     { OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error },
1581     { OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug },
1582     { OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error },
1583     { OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark },
1584     { OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK,
1585       (void (*)(void))core_clear_last_error_mark },
1586     { OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark },
1587     { OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))ossl_core_bio_new_file },
1588     { OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))ossl_core_bio_new_mem_buf },
1589     { OSSL_FUNC_BIO_READ_EX, (void (*)(void))ossl_core_bio_read_ex },
1590     { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))ossl_core_bio_write_ex },
1591     { OSSL_FUNC_BIO_GETS, (void (*)(void))ossl_core_bio_gets },
1592     { OSSL_FUNC_BIO_PUTS, (void (*)(void))ossl_core_bio_puts },
1593     { OSSL_FUNC_BIO_CTRL, (void (*)(void))ossl_core_bio_ctrl },
1594     { OSSL_FUNC_BIO_UP_REF, (void (*)(void))ossl_core_bio_up_ref },
1595     { OSSL_FUNC_BIO_FREE, (void (*)(void))ossl_core_bio_free },
1596     { OSSL_FUNC_BIO_VPRINTF, (void (*)(void))ossl_core_bio_vprintf },
1597     { OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf },
1598     { OSSL_FUNC_SELF_TEST_CB, (void (*)(void))OSSL_SELF_TEST_get_callback },
1599     { OSSL_FUNC_GET_ENTROPY, (void (*)(void))ossl_rand_get_entropy },
1600     { OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))ossl_rand_cleanup_entropy },
1601     { OSSL_FUNC_GET_NONCE, (void (*)(void))ossl_rand_get_nonce },
1602     { OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))ossl_rand_cleanup_nonce },
1603 #endif
1604     { OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc },
1605     { OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc },
1606     { OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free },
1607     { OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free },
1608     { OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc },
1609     { OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc },
1610     { OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc },
1611     { OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc },
1612     { OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free },
1613     { OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE,
1614         (void (*)(void))CRYPTO_secure_clear_free },
1615     { OSSL_FUNC_CRYPTO_SECURE_ALLOCATED,
1616         (void (*)(void))CRYPTO_secure_allocated },
1617     { OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse },
1618 #ifndef FIPS_MODULE
1619     { OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB,
1620         (void (*)(void))ossl_provider_register_child_cb },
1621     { OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB,
1622         (void (*)(void))ossl_provider_deregister_child_cb },
1623     { OSSL_FUNC_PROVIDER_NAME,
1624         (void (*)(void))OSSL_PROVIDER_name },
1625     { OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX,
1626         (void (*)(void))OSSL_PROVIDER_get0_provider_ctx },
1627     { OSSL_FUNC_PROVIDER_GET0_DISPATCH,
1628         (void (*)(void))OSSL_PROVIDER_get0_dispatch },
1629     { OSSL_FUNC_PROVIDER_UP_REF,
1630         (void (*)(void))provider_up_ref_intern },
1631     { OSSL_FUNC_PROVIDER_FREE,
1632         (void (*)(void))provider_free_intern },
1633 #endif
1634     { 0, NULL }
1635 };
1636 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;