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