xref: /freebsd/crypto/openssl/crypto/provider_core.c (revision 44096ebd22ddd0081a357011714eff8963614b65)
1 /*
2  * Copyright 2019-2024 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 #ifndef FIPS_MODULE
19 #include "crypto/decoder.h" /* ossl_decoder_store_cache_flush */
20 #include "crypto/encoder.h" /* ossl_encoder_store_cache_flush */
21 #include "crypto/store.h" /* ossl_store_loader_store_cache_flush */
22 #endif
23 #include "crypto/evp.h" /* evp_method_store_cache_flush */
24 #include "crypto/rand.h"
25 #include "internal/nelem.h"
26 #include "internal/thread_once.h"
27 #include "internal/provider.h"
28 #include "internal/refcount.h"
29 #include "internal/bio.h"
30 #include "internal/core.h"
31 #include "provider_local.h"
32 #ifndef FIPS_MODULE
33 # include <openssl/self_test.h>
34 #endif
35 
36 /*
37  * This file defines and uses a number of different structures:
38  *
39  * OSSL_PROVIDER (provider_st): Used to represent all information related to a
40  * single instance of a provider.
41  *
42  * provider_store_st: Holds information about the collection of providers that
43  * are available within the current library context (OSSL_LIB_CTX). It also
44  * holds configuration information about providers that could be loaded at some
45  * future point.
46  *
47  * OSSL_PROVIDER_CHILD_CB: An instance of this structure holds the callbacks
48  * that have been registered for a child library context and the associated
49  * provider that registered those callbacks.
50  *
51  * Where a child library context exists then it has its own instance of the
52  * provider store. Each provider that exists in the parent provider store, has
53  * an associated child provider in the child library context's provider store.
54  * As providers get activated or deactivated this needs to be mirrored in the
55  * associated child providers.
56  *
57  * LOCKING
58  * =======
59  *
60  * There are a number of different locks used in this file and it is important
61  * to understand how they should be used in order to avoid deadlocks.
62  *
63  * Fields within a structure can often be "write once" on creation, and then
64  * "read many". Creation of a structure is done by a single thread, and
65  * therefore no lock is required for the "write once/read many" fields. It is
66  * safe for multiple threads to read these fields without a lock, because they
67  * will never be changed.
68  *
69  * However some fields may be changed after a structure has been created and
70  * shared between multiple threads. Where this is the case a lock is required.
71  *
72  * The locks available are:
73  *
74  * The provider flag_lock: Used to control updates to the various provider
75  * "flags" (flag_initialized, flag_activated, flag_fallback) and associated
76  * "counts" (activatecnt).
77  *
78  * The provider refcnt_lock: Only ever used to control updates to the provider
79  * refcnt value.
80  *
81  * The provider optbits_lock: Used to control access to the provider's
82  * operation_bits and operation_bits_sz fields.
83  *
84  * The store default_path_lock: Used to control access to the provider store's
85  * default search path value (default_path)
86  *
87  * The store lock: Used to control the stack of provider's held within the
88  * provider store, as well as the stack of registered child provider callbacks.
89  *
90  * As a general rule-of-thumb it is best to:
91  *  - keep the scope of the code that is protected by a lock to the absolute
92  *    minimum possible;
93  *  - try to keep the scope of the lock to within a single function (i.e. avoid
94  *    making calls to other functions while holding a lock);
95  *  - try to only ever hold one lock at a time.
96  *
97  * Unfortunately, it is not always possible to stick to the above guidelines.
98  * Where they are not adhered to there is always a danger of inadvertently
99  * introducing the possibility of deadlock. The following rules MUST be adhered
100  * to in order to avoid that:
101  *  - Holding multiple locks at the same time is only allowed for the
102  *    provider store lock, the provider flag_lock and the provider refcnt_lock.
103  *  - When holding multiple locks they must be acquired in the following order of
104  *    precedence:
105  *        1) provider store lock
106  *        2) provider flag_lock
107  *        3) provider refcnt_lock
108  *  - When releasing locks they must be released in the reverse order to which
109  *    they were acquired
110  *  - No locks may be held when making an upcall. NOTE: Some common functions
111  *    can make upcalls as part of their normal operation. If you need to call
112  *    some other function while holding a lock make sure you know whether it
113  *    will make any upcalls or not. For example ossl_provider_up_ref() can call
114  *    ossl_provider_up_ref_parent() which can call the c_prov_up_ref() upcall.
115  *  - It is permissible to hold the store and flag locks when calling child
116  *    provider callbacks. No other locks may be held during such callbacks.
117  */
118 
119 static OSSL_PROVIDER *provider_new(const char *name,
120                                    OSSL_provider_init_fn *init_function,
121                                    STACK_OF(INFOPAIR) *parameters);
122 
123 /*-
124  * Provider Object structure
125  * =========================
126  */
127 
128 #ifndef FIPS_MODULE
129 typedef struct {
130     OSSL_PROVIDER *prov;
131     int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
132     int (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata);
133     int (*global_props_cb)(const char *props, void *cbdata);
134     void *cbdata;
135 } OSSL_PROVIDER_CHILD_CB;
136 DEFINE_STACK_OF(OSSL_PROVIDER_CHILD_CB)
137 #endif
138 
139 struct provider_store_st;        /* Forward declaration */
140 
141 struct ossl_provider_st {
142     /* Flag bits */
143     unsigned int flag_initialized:1;
144     unsigned int flag_activated:1;
145     unsigned int flag_fallback:1; /* Can be used as fallback */
146 
147     /* Getting and setting the flags require synchronization */
148     CRYPTO_RWLOCK *flag_lock;
149 
150     /* OpenSSL library side data */
151     CRYPTO_REF_COUNT refcnt;
152     CRYPTO_RWLOCK *refcnt_lock;  /* For the ref counter */
153     int activatecnt;
154     char *name;
155     char *path;
156     DSO *module;
157     OSSL_provider_init_fn *init_function;
158     STACK_OF(INFOPAIR) *parameters;
159     OSSL_LIB_CTX *libctx; /* The library context this instance is in */
160     struct provider_store_st *store; /* The store this instance belongs to */
161 #ifndef FIPS_MODULE
162     /*
163      * In the FIPS module inner provider, this isn't needed, since the
164      * error upcalls are always direct calls to the outer provider.
165      */
166     int error_lib;     /* ERR library number, one for each provider */
167 # ifndef OPENSSL_NO_ERR
168     ERR_STRING_DATA *error_strings; /* Copy of what the provider gives us */
169 # endif
170 #endif
171 
172     /* Provider side functions */
173     OSSL_FUNC_provider_teardown_fn *teardown;
174     OSSL_FUNC_provider_gettable_params_fn *gettable_params;
175     OSSL_FUNC_provider_get_params_fn *get_params;
176     OSSL_FUNC_provider_get_capabilities_fn *get_capabilities;
177     OSSL_FUNC_provider_self_test_fn *self_test;
178     OSSL_FUNC_provider_query_operation_fn *query_operation;
179     OSSL_FUNC_provider_unquery_operation_fn *unquery_operation;
180 
181     /*
182      * Cache of bit to indicate of query_operation() has been called on
183      * a specific operation or not.
184      */
185     unsigned char *operation_bits;
186     size_t operation_bits_sz;
187     CRYPTO_RWLOCK *opbits_lock;
188 
189 #ifndef FIPS_MODULE
190     /* Whether this provider is the child of some other provider */
191     const OSSL_CORE_HANDLE *handle;
192     unsigned int ischild:1;
193 #endif
194 
195     /* Provider side data */
196     void *provctx;
197     const OSSL_DISPATCH *dispatch;
198 };
199 DEFINE_STACK_OF(OSSL_PROVIDER)
200 
201 static int ossl_provider_cmp(const OSSL_PROVIDER * const *a,
202                              const OSSL_PROVIDER * const *b)
203 {
204     return strcmp((*a)->name, (*b)->name);
205 }
206 
207 /*-
208  * Provider Object store
209  * =====================
210  *
211  * The Provider Object store is a library context object, and therefore needs
212  * an index.
213  */
214 
215 struct provider_store_st {
216     OSSL_LIB_CTX *libctx;
217     STACK_OF(OSSL_PROVIDER) *providers;
218     STACK_OF(OSSL_PROVIDER_CHILD_CB) *child_cbs;
219     CRYPTO_RWLOCK *default_path_lock;
220     CRYPTO_RWLOCK *lock;
221     char *default_path;
222     OSSL_PROVIDER_INFO *provinfo;
223     size_t numprovinfo;
224     size_t provinfosz;
225     unsigned int use_fallbacks:1;
226     unsigned int freeing:1;
227 };
228 
229 /*
230  * provider_deactivate_free() is a wrapper around ossl_provider_deactivate()
231  * and ossl_provider_free(), called as needed.
232  * Since this is only called when the provider store is being emptied, we
233  * don't need to care about any lock.
234  */
235 static void provider_deactivate_free(OSSL_PROVIDER *prov)
236 {
237     if (prov->flag_activated)
238         ossl_provider_deactivate(prov, 1);
239     ossl_provider_free(prov);
240 }
241 
242 #ifndef FIPS_MODULE
243 static void ossl_provider_child_cb_free(OSSL_PROVIDER_CHILD_CB *cb)
244 {
245     OPENSSL_free(cb);
246 }
247 #endif
248 
249 static void infopair_free(INFOPAIR *pair)
250 {
251     OPENSSL_free(pair->name);
252     OPENSSL_free(pair->value);
253     OPENSSL_free(pair);
254 }
255 
256 static INFOPAIR *infopair_copy(const INFOPAIR *src)
257 {
258     INFOPAIR *dest = OPENSSL_zalloc(sizeof(*dest));
259 
260     if (dest == NULL)
261         return NULL;
262     if (src->name != NULL) {
263         dest->name = OPENSSL_strdup(src->name);
264         if (dest->name == NULL)
265             goto err;
266     }
267     if (src->value != NULL) {
268         dest->value = OPENSSL_strdup(src->value);
269         if (dest->value == NULL)
270             goto err;
271     }
272     return dest;
273  err:
274     OPENSSL_free(dest->name);
275     OPENSSL_free(dest);
276     return NULL;
277 }
278 
279 void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info)
280 {
281     OPENSSL_free(info->name);
282     OPENSSL_free(info->path);
283     sk_INFOPAIR_pop_free(info->parameters, infopair_free);
284 }
285 
286 static void provider_store_free(void *vstore)
287 {
288     struct provider_store_st *store = vstore;
289     size_t i;
290 
291     if (store == NULL)
292         return;
293     store->freeing = 1;
294     OPENSSL_free(store->default_path);
295     sk_OSSL_PROVIDER_pop_free(store->providers, provider_deactivate_free);
296 #ifndef FIPS_MODULE
297     sk_OSSL_PROVIDER_CHILD_CB_pop_free(store->child_cbs,
298                                        ossl_provider_child_cb_free);
299 #endif
300     CRYPTO_THREAD_lock_free(store->default_path_lock);
301     CRYPTO_THREAD_lock_free(store->lock);
302     for (i = 0; i < store->numprovinfo; i++)
303         ossl_provider_info_clear(&store->provinfo[i]);
304     OPENSSL_free(store->provinfo);
305     OPENSSL_free(store);
306 }
307 
308 static void *provider_store_new(OSSL_LIB_CTX *ctx)
309 {
310     struct provider_store_st *store = OPENSSL_zalloc(sizeof(*store));
311 
312     if (store == NULL
313         || (store->providers = sk_OSSL_PROVIDER_new(ossl_provider_cmp)) == NULL
314         || (store->default_path_lock = CRYPTO_THREAD_lock_new()) == NULL
315 #ifndef FIPS_MODULE
316         || (store->child_cbs = sk_OSSL_PROVIDER_CHILD_CB_new_null()) == NULL
317 #endif
318         || (store->lock = CRYPTO_THREAD_lock_new()) == NULL) {
319         provider_store_free(store);
320         return NULL;
321     }
322     store->libctx = ctx;
323     store->use_fallbacks = 1;
324 
325     return store;
326 }
327 
328 static const OSSL_LIB_CTX_METHOD provider_store_method = {
329     /* Needs to be freed before the child provider data is freed */
330     OSSL_LIB_CTX_METHOD_PRIORITY_1,
331     provider_store_new,
332     provider_store_free,
333 };
334 
335 static struct provider_store_st *get_provider_store(OSSL_LIB_CTX *libctx)
336 {
337     struct provider_store_st *store = NULL;
338 
339     store = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_STORE_INDEX,
340                                   &provider_store_method);
341     if (store == NULL)
342         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
343     return store;
344 }
345 
346 int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx)
347 {
348     struct provider_store_st *store;
349 
350     if ((store = get_provider_store(libctx)) != NULL) {
351         if (!CRYPTO_THREAD_write_lock(store->lock))
352             return 0;
353         store->use_fallbacks = 0;
354         CRYPTO_THREAD_unlock(store->lock);
355         return 1;
356     }
357     return 0;
358 }
359 
360 #define BUILTINS_BLOCK_SIZE     10
361 
362 int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx,
363                                     OSSL_PROVIDER_INFO *entry)
364 {
365     struct provider_store_st *store = get_provider_store(libctx);
366     int ret = 0;
367 
368     if (entry->name == NULL) {
369         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
370         return 0;
371     }
372 
373     if (store == NULL) {
374         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
375         return 0;
376     }
377 
378     if (!CRYPTO_THREAD_write_lock(store->lock))
379         return 0;
380     if (store->provinfosz == 0) {
381         store->provinfo = OPENSSL_zalloc(sizeof(*store->provinfo)
382                                          * BUILTINS_BLOCK_SIZE);
383         if (store->provinfo == NULL) {
384             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
385             goto err;
386         }
387         store->provinfosz = BUILTINS_BLOCK_SIZE;
388     } else if (store->numprovinfo == store->provinfosz) {
389         OSSL_PROVIDER_INFO *tmpbuiltins;
390         size_t newsz = store->provinfosz + BUILTINS_BLOCK_SIZE;
391 
392         tmpbuiltins = OPENSSL_realloc(store->provinfo,
393                                       sizeof(*store->provinfo) * newsz);
394         if (tmpbuiltins == NULL) {
395             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
396             goto err;
397         }
398         store->provinfo = tmpbuiltins;
399         store->provinfosz = newsz;
400     }
401     store->provinfo[store->numprovinfo] = *entry;
402     store->numprovinfo++;
403 
404     ret = 1;
405  err:
406     CRYPTO_THREAD_unlock(store->lock);
407     return ret;
408 }
409 
410 OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
411                                   ossl_unused int noconfig)
412 {
413     struct provider_store_st *store = NULL;
414     OSSL_PROVIDER *prov = NULL;
415 
416     if ((store = get_provider_store(libctx)) != NULL) {
417         OSSL_PROVIDER tmpl = { 0, };
418         int i;
419 
420 #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
421         /*
422          * Make sure any providers are loaded from config before we try to find
423          * them.
424          */
425         if (!noconfig) {
426             if (ossl_lib_ctx_is_default(libctx))
427                 OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
428         }
429 #endif
430 
431         tmpl.name = (char *)name;
432         /*
433          * A "find" operation can sort the stack, and therefore a write lock is
434          * required.
435          */
436         if (!CRYPTO_THREAD_write_lock(store->lock))
437             return NULL;
438         if ((i = sk_OSSL_PROVIDER_find(store->providers, &tmpl)) != -1)
439             prov = sk_OSSL_PROVIDER_value(store->providers, i);
440         CRYPTO_THREAD_unlock(store->lock);
441         if (prov != NULL && !ossl_provider_up_ref(prov))
442             prov = NULL;
443     }
444 
445     return prov;
446 }
447 
448 /*-
449  * Provider Object methods
450  * =======================
451  */
452 
453 static OSSL_PROVIDER *provider_new(const char *name,
454                                    OSSL_provider_init_fn *init_function,
455                                    STACK_OF(INFOPAIR) *parameters)
456 {
457     OSSL_PROVIDER *prov = NULL;
458 
459     if ((prov = OPENSSL_zalloc(sizeof(*prov))) == NULL
460 #ifndef HAVE_ATOMICS
461         || (prov->refcnt_lock = CRYPTO_THREAD_lock_new()) == NULL
462 #endif
463        ) {
464         OPENSSL_free(prov);
465         ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
466         return NULL;
467     }
468 
469     prov->refcnt = 1; /* 1 One reference to be returned */
470 
471     if ((prov->opbits_lock = CRYPTO_THREAD_lock_new()) == NULL
472         || (prov->flag_lock = CRYPTO_THREAD_lock_new()) == NULL
473         || (prov->name = OPENSSL_strdup(name)) == NULL
474         || (prov->parameters = sk_INFOPAIR_deep_copy(parameters,
475                                                      infopair_copy,
476                                                      infopair_free)) == NULL) {
477         ossl_provider_free(prov);
478         ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
479         return NULL;
480     }
481 
482     prov->init_function = init_function;
483 
484     return prov;
485 }
486 
487 int ossl_provider_up_ref(OSSL_PROVIDER *prov)
488 {
489     int ref = 0;
490 
491     if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0)
492         return 0;
493 
494 #ifndef FIPS_MODULE
495     if (prov->ischild) {
496         if (!ossl_provider_up_ref_parent(prov, 0)) {
497             ossl_provider_free(prov);
498             return 0;
499         }
500     }
501 #endif
502 
503     return ref;
504 }
505 
506 #ifndef FIPS_MODULE
507 static int provider_up_ref_intern(OSSL_PROVIDER *prov, int activate)
508 {
509     if (activate)
510         return ossl_provider_activate(prov, 1, 0);
511 
512     return ossl_provider_up_ref(prov);
513 }
514 
515 static int provider_free_intern(OSSL_PROVIDER *prov, int deactivate)
516 {
517     if (deactivate)
518         return ossl_provider_deactivate(prov, 1);
519 
520     ossl_provider_free(prov);
521     return 1;
522 }
523 #endif
524 
525 /*
526  * We assume that the requested provider does not already exist in the store.
527  * The caller should check. If it does exist then adding it to the store later
528  * will fail.
529  */
530 OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
531                                  OSSL_provider_init_fn *init_function,
532                                  int noconfig)
533 {
534     struct provider_store_st *store = NULL;
535     OSSL_PROVIDER_INFO template;
536     OSSL_PROVIDER *prov = NULL;
537 
538     if ((store = get_provider_store(libctx)) == NULL)
539         return NULL;
540 
541     memset(&template, 0, sizeof(template));
542     if (init_function == NULL) {
543         const OSSL_PROVIDER_INFO *p;
544         size_t i;
545 
546         /* Check if this is a predefined builtin provider */
547         for (p = ossl_predefined_providers; p->name != NULL; p++) {
548             if (strcmp(p->name, name) == 0) {
549                 template = *p;
550                 break;
551             }
552         }
553         if (p->name == NULL) {
554             /* Check if this is a user added builtin provider */
555             if (!CRYPTO_THREAD_read_lock(store->lock))
556                 return NULL;
557             for (i = 0, p = store->provinfo; i < store->numprovinfo; p++, i++) {
558                 if (strcmp(p->name, name) == 0) {
559                     template = *p;
560                     break;
561                 }
562             }
563             CRYPTO_THREAD_unlock(store->lock);
564         }
565     } else {
566         template.init = init_function;
567     }
568 
569     /* provider_new() generates an error, so no need here */
570     prov = provider_new(name, template.init, template.parameters);
571 
572     if (prov == NULL)
573         return NULL;
574 
575     if (!ossl_provider_set_module_path(prov, template.path)) {
576         ossl_provider_free(prov);
577         return NULL;
578     }
579 
580     prov->libctx = libctx;
581 #ifndef FIPS_MODULE
582     prov->error_lib = ERR_get_next_error_library();
583 #endif
584 
585     /*
586      * At this point, the provider is only partially "loaded".  To be
587      * fully "loaded", ossl_provider_activate() must also be called and it must
588      * then be added to the provider store.
589      */
590 
591     return prov;
592 }
593 
594 /* Assumes that the store lock is held */
595 static int create_provider_children(OSSL_PROVIDER *prov)
596 {
597     int ret = 1;
598 #ifndef FIPS_MODULE
599     struct provider_store_st *store = prov->store;
600     OSSL_PROVIDER_CHILD_CB *child_cb;
601     int i, max;
602 
603     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
604     for (i = 0; i < max; i++) {
605         /*
606          * This is newly activated (activatecnt == 1), so we need to
607          * create child providers as necessary.
608          */
609         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
610         ret &= child_cb->create_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
611     }
612 #endif
613 
614     return ret;
615 }
616 
617 int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov,
618                                int retain_fallbacks)
619 {
620     struct provider_store_st *store;
621     int idx;
622     OSSL_PROVIDER tmpl = { 0, };
623     OSSL_PROVIDER *actualtmp = NULL;
624 
625     if (actualprov != NULL)
626         *actualprov = NULL;
627 
628     if ((store = get_provider_store(prov->libctx)) == NULL)
629         return 0;
630 
631     if (!CRYPTO_THREAD_write_lock(store->lock))
632         return 0;
633 
634     tmpl.name = (char *)prov->name;
635     idx = sk_OSSL_PROVIDER_find(store->providers, &tmpl);
636     if (idx == -1)
637         actualtmp = prov;
638     else
639         actualtmp = sk_OSSL_PROVIDER_value(store->providers, idx);
640 
641     if (idx == -1) {
642         if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0)
643             goto err;
644         prov->store = store;
645         if (!create_provider_children(prov)) {
646             sk_OSSL_PROVIDER_delete_ptr(store->providers, prov);
647             goto err;
648         }
649         if (!retain_fallbacks)
650             store->use_fallbacks = 0;
651     }
652 
653     CRYPTO_THREAD_unlock(store->lock);
654 
655     if (actualprov != NULL) {
656         if (!ossl_provider_up_ref(actualtmp)) {
657             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
658             actualtmp = NULL;
659             return 0;
660         }
661         *actualprov = actualtmp;
662     }
663 
664     if (idx >= 0) {
665         /*
666          * The provider is already in the store. Probably two threads
667          * independently initialised their own provider objects with the same
668          * name and raced to put them in the store. This thread lost. We
669          * deactivate the one we just created and use the one that already
670          * exists instead.
671          * If we get here then we know we did not create provider children
672          * above, so we inform ossl_provider_deactivate not to attempt to remove
673          * any.
674          */
675         ossl_provider_deactivate(prov, 0);
676         ossl_provider_free(prov);
677     }
678 
679     return 1;
680 
681  err:
682     CRYPTO_THREAD_unlock(store->lock);
683     return 0;
684 }
685 
686 void ossl_provider_free(OSSL_PROVIDER *prov)
687 {
688     if (prov != NULL) {
689         int ref = 0;
690 
691         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
692 
693         /*
694          * When the refcount drops to zero, we clean up the provider.
695          * Note that this also does teardown, which may seem late,
696          * considering that init happens on first activation.  However,
697          * there may be other structures hanging on to the provider after
698          * the last deactivation and may therefore need full access to the
699          * provider's services.  Therefore, we deinit late.
700          */
701         if (ref == 0) {
702             if (prov->flag_initialized) {
703                 ossl_provider_teardown(prov);
704 #ifndef OPENSSL_NO_ERR
705 # ifndef FIPS_MODULE
706                 if (prov->error_strings != NULL) {
707                     ERR_unload_strings(prov->error_lib, prov->error_strings);
708                     OPENSSL_free(prov->error_strings);
709                     prov->error_strings = NULL;
710                 }
711 # endif
712 #endif
713                 OPENSSL_free(prov->operation_bits);
714                 prov->operation_bits = NULL;
715                 prov->operation_bits_sz = 0;
716                 prov->flag_initialized = 0;
717             }
718 
719 #ifndef FIPS_MODULE
720             /*
721              * We deregister thread handling whether or not the provider was
722              * initialized. If init was attempted but was not successful then
723              * the provider may still have registered a thread handler.
724              */
725             ossl_init_thread_deregister(prov);
726             DSO_free(prov->module);
727 #endif
728             OPENSSL_free(prov->name);
729             OPENSSL_free(prov->path);
730             sk_INFOPAIR_pop_free(prov->parameters, infopair_free);
731             CRYPTO_THREAD_lock_free(prov->opbits_lock);
732             CRYPTO_THREAD_lock_free(prov->flag_lock);
733 #ifndef HAVE_ATOMICS
734             CRYPTO_THREAD_lock_free(prov->refcnt_lock);
735 #endif
736             OPENSSL_free(prov);
737         }
738 #ifndef FIPS_MODULE
739         else if (prov->ischild) {
740             ossl_provider_free_parent(prov, 0);
741         }
742 #endif
743     }
744 }
745 
746 /* Setters */
747 int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path)
748 {
749     OPENSSL_free(prov->path);
750     prov->path = NULL;
751     if (module_path == NULL)
752         return 1;
753     if ((prov->path = OPENSSL_strdup(module_path)) != NULL)
754         return 1;
755     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
756     return 0;
757 }
758 
759 static int infopair_add(STACK_OF(INFOPAIR) **infopairsk, const char *name,
760                         const char *value)
761 {
762     INFOPAIR *pair = NULL;
763 
764     if ((pair = OPENSSL_zalloc(sizeof(*pair))) != NULL
765         && (*infopairsk != NULL
766             || (*infopairsk = sk_INFOPAIR_new_null()) != NULL)
767         && (pair->name = OPENSSL_strdup(name)) != NULL
768         && (pair->value = OPENSSL_strdup(value)) != NULL
769         && sk_INFOPAIR_push(*infopairsk, pair) > 0)
770         return 1;
771 
772     if (pair != NULL) {
773         OPENSSL_free(pair->name);
774         OPENSSL_free(pair->value);
775         OPENSSL_free(pair);
776     }
777     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
778     return 0;
779 }
780 
781 int ossl_provider_add_parameter(OSSL_PROVIDER *prov,
782                                 const char *name, const char *value)
783 {
784     return infopair_add(&prov->parameters, name, value);
785 }
786 
787 int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo,
788                                      const char *name,
789                                      const char *value)
790 {
791     return infopair_add(&provinfo->parameters, name, value);
792 }
793 
794 /*
795  * Provider activation.
796  *
797  * What "activation" means depends on the provider form; for built in
798  * providers (in the library or the application alike), the provider
799  * can already be considered to be loaded, all that's needed is to
800  * initialize it.  However, for dynamically loadable provider modules,
801  * we must first load that module.
802  *
803  * Built in modules are distinguished from dynamically loaded modules
804  * with an already assigned init function.
805  */
806 static const OSSL_DISPATCH *core_dispatch; /* Define further down */
807 
808 int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *libctx,
809                                           const char *path)
810 {
811     struct provider_store_st *store;
812     char *p = NULL;
813 
814     if (path != NULL) {
815         p = OPENSSL_strdup(path);
816         if (p == NULL) {
817             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
818             return 0;
819         }
820     }
821     if ((store = get_provider_store(libctx)) != NULL
822             && CRYPTO_THREAD_write_lock(store->default_path_lock)) {
823         OPENSSL_free(store->default_path);
824         store->default_path = p;
825         CRYPTO_THREAD_unlock(store->default_path_lock);
826         return 1;
827     }
828     OPENSSL_free(p);
829     return 0;
830 }
831 
832 /*
833  * Internal version that doesn't affect the store flags, and thereby avoid
834  * locking.  Direct callers must remember to set the store flags when
835  * appropriate.
836  */
837 static int provider_init(OSSL_PROVIDER *prov)
838 {
839     const OSSL_DISPATCH *provider_dispatch = NULL;
840     void *tmp_provctx = NULL;    /* safety measure */
841 #ifndef OPENSSL_NO_ERR
842 # ifndef FIPS_MODULE
843     OSSL_FUNC_provider_get_reason_strings_fn *p_get_reason_strings = NULL;
844 # endif
845 #endif
846     int ok = 0;
847 
848     if (!ossl_assert(!prov->flag_initialized)) {
849         ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
850         goto end;
851     }
852 
853     /*
854      * If the init function isn't set, it indicates that this provider is
855      * a loadable module.
856      */
857     if (prov->init_function == NULL) {
858 #ifdef FIPS_MODULE
859         goto end;
860 #else
861         if (prov->module == NULL) {
862             char *allocated_path = NULL;
863             const char *module_path = NULL;
864             char *merged_path = NULL;
865             const char *load_dir = NULL;
866             char *allocated_load_dir = NULL;
867             struct provider_store_st *store;
868 
869             if ((prov->module = DSO_new()) == NULL) {
870                 /* DSO_new() generates an error already */
871                 goto end;
872             }
873 
874             if ((store = get_provider_store(prov->libctx)) == NULL
875                     || !CRYPTO_THREAD_read_lock(store->default_path_lock))
876                 goto end;
877 
878             if (store->default_path != NULL) {
879                 allocated_load_dir = OPENSSL_strdup(store->default_path);
880                 CRYPTO_THREAD_unlock(store->default_path_lock);
881                 if (allocated_load_dir == NULL) {
882                     ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
883                     goto end;
884                 }
885                 load_dir = allocated_load_dir;
886             } else {
887                 CRYPTO_THREAD_unlock(store->default_path_lock);
888             }
889 
890             if (load_dir == NULL) {
891                 load_dir = ossl_safe_getenv("OPENSSL_MODULES");
892                 if (load_dir == NULL)
893                     load_dir = MODULESDIR;
894             }
895 
896             DSO_ctrl(prov->module, DSO_CTRL_SET_FLAGS,
897                      DSO_FLAG_NAME_TRANSLATION_EXT_ONLY, NULL);
898 
899             module_path = prov->path;
900             if (module_path == NULL)
901                 module_path = allocated_path =
902                     DSO_convert_filename(prov->module, prov->name);
903             if (module_path != NULL)
904                 merged_path = DSO_merge(prov->module, module_path, load_dir);
905 
906             if (merged_path == NULL
907                 || (DSO_load(prov->module, merged_path, NULL, 0)) == NULL) {
908                 DSO_free(prov->module);
909                 prov->module = NULL;
910             }
911 
912             OPENSSL_free(merged_path);
913             OPENSSL_free(allocated_path);
914             OPENSSL_free(allocated_load_dir);
915         }
916 
917         if (prov->module == NULL) {
918             /* DSO has already recorded errors, this is just a tracepoint */
919             ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_DSO_LIB,
920                            "name=%s", prov->name);
921             goto end;
922         }
923 
924         prov->init_function = (OSSL_provider_init_fn *)
925             DSO_bind_func(prov->module, "OSSL_provider_init");
926 #endif
927     }
928 
929     /* Check for and call the initialise function for the provider. */
930     if (prov->init_function == NULL) {
931         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED,
932                        "name=%s, provider has no provider init function",
933                        prov->name);
934         goto end;
935     }
936 
937     if (!prov->init_function((OSSL_CORE_HANDLE *)prov, core_dispatch,
938                              &provider_dispatch, &tmp_provctx)) {
939         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL,
940                        "name=%s", prov->name);
941         goto end;
942     }
943     prov->provctx = tmp_provctx;
944     prov->dispatch = provider_dispatch;
945 
946     if (provider_dispatch != NULL) {
947         for (; provider_dispatch->function_id != 0; provider_dispatch++) {
948             switch (provider_dispatch->function_id) {
949             case OSSL_FUNC_PROVIDER_TEARDOWN:
950                 prov->teardown =
951                     OSSL_FUNC_provider_teardown(provider_dispatch);
952                 break;
953             case OSSL_FUNC_PROVIDER_GETTABLE_PARAMS:
954                 prov->gettable_params =
955                     OSSL_FUNC_provider_gettable_params(provider_dispatch);
956                 break;
957             case OSSL_FUNC_PROVIDER_GET_PARAMS:
958                 prov->get_params =
959                     OSSL_FUNC_provider_get_params(provider_dispatch);
960                 break;
961             case OSSL_FUNC_PROVIDER_SELF_TEST:
962                 prov->self_test =
963                     OSSL_FUNC_provider_self_test(provider_dispatch);
964                 break;
965             case OSSL_FUNC_PROVIDER_GET_CAPABILITIES:
966                 prov->get_capabilities =
967                     OSSL_FUNC_provider_get_capabilities(provider_dispatch);
968                 break;
969             case OSSL_FUNC_PROVIDER_QUERY_OPERATION:
970                 prov->query_operation =
971                     OSSL_FUNC_provider_query_operation(provider_dispatch);
972                 break;
973             case OSSL_FUNC_PROVIDER_UNQUERY_OPERATION:
974                 prov->unquery_operation =
975                     OSSL_FUNC_provider_unquery_operation(provider_dispatch);
976                 break;
977 #ifndef OPENSSL_NO_ERR
978 # ifndef FIPS_MODULE
979             case OSSL_FUNC_PROVIDER_GET_REASON_STRINGS:
980                 p_get_reason_strings =
981                     OSSL_FUNC_provider_get_reason_strings(provider_dispatch);
982                 break;
983 # endif
984 #endif
985             }
986         }
987     }
988 
989 #ifndef OPENSSL_NO_ERR
990 # ifndef FIPS_MODULE
991     if (p_get_reason_strings != NULL) {
992         const OSSL_ITEM *reasonstrings = p_get_reason_strings(prov->provctx);
993         size_t cnt, cnt2;
994 
995         /*
996          * ERR_load_strings() handles ERR_STRING_DATA rather than OSSL_ITEM,
997          * although they are essentially the same type.
998          * Furthermore, ERR_load_strings() patches the array's error number
999          * with the error library number, so we need to make a copy of that
1000          * array either way.
1001          */
1002         cnt = 0;
1003         while (reasonstrings[cnt].id != 0) {
1004             if (ERR_GET_LIB(reasonstrings[cnt].id) != 0)
1005                 goto end;
1006             cnt++;
1007         }
1008         cnt++;                   /* One for the terminating item */
1009 
1010         /* Allocate one extra item for the "library" name */
1011         prov->error_strings =
1012             OPENSSL_zalloc(sizeof(ERR_STRING_DATA) * (cnt + 1));
1013         if (prov->error_strings == NULL)
1014             goto end;
1015 
1016         /*
1017          * Set the "library" name.
1018          */
1019         prov->error_strings[0].error = ERR_PACK(prov->error_lib, 0, 0);
1020         prov->error_strings[0].string = prov->name;
1021         /*
1022          * Copy reasonstrings item 0..cnt-1 to prov->error_trings positions
1023          * 1..cnt.
1024          */
1025         for (cnt2 = 1; cnt2 <= cnt; cnt2++) {
1026             prov->error_strings[cnt2].error = (int)reasonstrings[cnt2-1].id;
1027             prov->error_strings[cnt2].string = reasonstrings[cnt2-1].ptr;
1028         }
1029 
1030         ERR_load_strings(prov->error_lib, prov->error_strings);
1031     }
1032 # endif
1033 #endif
1034 
1035     /* With this flag set, this provider has become fully "loaded". */
1036     prov->flag_initialized = 1;
1037     ok = 1;
1038 
1039  end:
1040     return ok;
1041 }
1042 
1043 /*
1044  * Deactivate a provider. If upcalls is 0 then we suppress any upcalls to a
1045  * parent provider. If removechildren is 0 then we suppress any calls to remove
1046  * child providers.
1047  * Return -1 on failure and the activation count on success
1048  */
1049 static int provider_deactivate(OSSL_PROVIDER *prov, int upcalls,
1050                                int removechildren)
1051 {
1052     int count;
1053     struct provider_store_st *store;
1054 #ifndef FIPS_MODULE
1055     int freeparent = 0;
1056 #endif
1057     int lock = 1;
1058 
1059     if (!ossl_assert(prov != NULL))
1060         return -1;
1061 
1062     /*
1063      * No need to lock if we've got no store because we've not been shared with
1064      * other threads.
1065      */
1066     store = get_provider_store(prov->libctx);
1067     if (store == NULL)
1068         lock = 0;
1069 
1070     if (lock && !CRYPTO_THREAD_read_lock(store->lock))
1071         return -1;
1072     if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) {
1073         CRYPTO_THREAD_unlock(store->lock);
1074         return -1;
1075     }
1076 
1077 #ifndef FIPS_MODULE
1078     if (prov->activatecnt >= 2 && prov->ischild && upcalls) {
1079         /*
1080          * We have had a direct activation in this child libctx so we need to
1081          * now down the ref count in the parent provider. We do the actual down
1082          * ref outside of the flag_lock, since it could involve getting other
1083          * locks.
1084          */
1085         freeparent = 1;
1086     }
1087 #endif
1088 
1089     if ((count = --prov->activatecnt) < 1)
1090         prov->flag_activated = 0;
1091 #ifndef FIPS_MODULE
1092     else
1093         removechildren = 0;
1094 #endif
1095 
1096 #ifndef FIPS_MODULE
1097     if (removechildren && store != NULL) {
1098         int i, max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
1099         OSSL_PROVIDER_CHILD_CB *child_cb;
1100 
1101         for (i = 0; i < max; i++) {
1102             child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
1103             child_cb->remove_cb((OSSL_CORE_HANDLE *)prov, child_cb->cbdata);
1104         }
1105     }
1106 #endif
1107     if (lock) {
1108         CRYPTO_THREAD_unlock(prov->flag_lock);
1109         CRYPTO_THREAD_unlock(store->lock);
1110     }
1111 #ifndef FIPS_MODULE
1112     if (freeparent)
1113         ossl_provider_free_parent(prov, 1);
1114 #endif
1115 
1116     /* We don't deinit here, that's done in ossl_provider_free() */
1117     return count;
1118 }
1119 
1120 /*
1121  * Activate a provider.
1122  * Return -1 on failure and the activation count on success
1123  */
1124 static int provider_activate(OSSL_PROVIDER *prov, int lock, int upcalls)
1125 {
1126     int count = -1;
1127     struct provider_store_st *store;
1128     int ret = 1;
1129 
1130     store = prov->store;
1131     /*
1132     * If the provider hasn't been added to the store, then we don't need
1133     * any locks because we've not shared it with other threads.
1134     */
1135     if (store == NULL) {
1136         lock = 0;
1137         if (!provider_init(prov))
1138             return -1;
1139     }
1140 
1141 #ifndef FIPS_MODULE
1142     if (prov->ischild && upcalls && !ossl_provider_up_ref_parent(prov, 1))
1143         return -1;
1144 #endif
1145 
1146     if (lock && !CRYPTO_THREAD_read_lock(store->lock)) {
1147 #ifndef FIPS_MODULE
1148         if (prov->ischild && upcalls)
1149             ossl_provider_free_parent(prov, 1);
1150 #endif
1151         return -1;
1152     }
1153 
1154     if (lock && !CRYPTO_THREAD_write_lock(prov->flag_lock)) {
1155         CRYPTO_THREAD_unlock(store->lock);
1156 #ifndef FIPS_MODULE
1157         if (prov->ischild && upcalls)
1158             ossl_provider_free_parent(prov, 1);
1159 #endif
1160         return -1;
1161     }
1162 
1163     count = ++prov->activatecnt;
1164     prov->flag_activated = 1;
1165 
1166     if (prov->activatecnt == 1 && store != NULL) {
1167         ret = create_provider_children(prov);
1168     }
1169     if (lock) {
1170         CRYPTO_THREAD_unlock(prov->flag_lock);
1171         CRYPTO_THREAD_unlock(store->lock);
1172     }
1173 
1174     if (!ret)
1175         return -1;
1176 
1177     return count;
1178 }
1179 
1180 static int provider_flush_store_cache(const OSSL_PROVIDER *prov)
1181 {
1182     struct provider_store_st *store;
1183     int freeing;
1184 
1185     if ((store = get_provider_store(prov->libctx)) == NULL)
1186         return 0;
1187 
1188     if (!CRYPTO_THREAD_read_lock(store->lock))
1189         return 0;
1190     freeing = store->freeing;
1191     CRYPTO_THREAD_unlock(store->lock);
1192 
1193     if (!freeing) {
1194         int acc
1195             = evp_method_store_cache_flush(prov->libctx)
1196 #ifndef FIPS_MODULE
1197             + ossl_encoder_store_cache_flush(prov->libctx)
1198             + ossl_decoder_store_cache_flush(prov->libctx)
1199             + ossl_store_loader_store_cache_flush(prov->libctx)
1200 #endif
1201             ;
1202 
1203 #ifndef FIPS_MODULE
1204         return acc == 4;
1205 #else
1206         return acc == 1;
1207 #endif
1208     }
1209     return 1;
1210 }
1211 
1212 static int provider_remove_store_methods(OSSL_PROVIDER *prov)
1213 {
1214     struct provider_store_st *store;
1215     int freeing;
1216 
1217     if ((store = get_provider_store(prov->libctx)) == NULL)
1218         return 0;
1219 
1220     if (!CRYPTO_THREAD_read_lock(store->lock))
1221         return 0;
1222     freeing = store->freeing;
1223     CRYPTO_THREAD_unlock(store->lock);
1224 
1225     if (!freeing) {
1226         int acc;
1227 
1228         if (!CRYPTO_THREAD_write_lock(prov->opbits_lock))
1229             return 0;
1230         OPENSSL_free(prov->operation_bits);
1231         prov->operation_bits = NULL;
1232         prov->operation_bits_sz = 0;
1233         CRYPTO_THREAD_unlock(prov->opbits_lock);
1234 
1235         acc = evp_method_store_remove_all_provided(prov)
1236 #ifndef FIPS_MODULE
1237             + ossl_encoder_store_remove_all_provided(prov)
1238             + ossl_decoder_store_remove_all_provided(prov)
1239             + ossl_store_loader_store_remove_all_provided(prov)
1240 #endif
1241             ;
1242 
1243 #ifndef FIPS_MODULE
1244         return acc == 4;
1245 #else
1246         return acc == 1;
1247 #endif
1248     }
1249     return 1;
1250 }
1251 
1252 int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild)
1253 {
1254     int count;
1255 
1256     if (prov == NULL)
1257         return 0;
1258 #ifndef FIPS_MODULE
1259     /*
1260      * If aschild is true, then we only actually do the activation if the
1261      * provider is a child. If its not, this is still success.
1262      */
1263     if (aschild && !prov->ischild)
1264         return 1;
1265 #endif
1266     if ((count = provider_activate(prov, 1, upcalls)) > 0)
1267         return count == 1 ? provider_flush_store_cache(prov) : 1;
1268 
1269     return 0;
1270 }
1271 
1272 int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren)
1273 {
1274     int count;
1275 
1276     if (prov == NULL
1277             || (count = provider_deactivate(prov, 1, removechildren)) < 0)
1278         return 0;
1279     return count == 0 ? provider_remove_store_methods(prov) : 1;
1280 }
1281 
1282 void *ossl_provider_ctx(const OSSL_PROVIDER *prov)
1283 {
1284     return prov != NULL ? prov->provctx : NULL;
1285 }
1286 
1287 /*
1288  * This function only does something once when store->use_fallbacks == 1,
1289  * and then sets store->use_fallbacks = 0, so the second call and so on is
1290  * effectively a no-op.
1291  */
1292 static int provider_activate_fallbacks(struct provider_store_st *store)
1293 {
1294     int use_fallbacks;
1295     int activated_fallback_count = 0;
1296     int ret = 0;
1297     const OSSL_PROVIDER_INFO *p;
1298 
1299     if (!CRYPTO_THREAD_read_lock(store->lock))
1300         return 0;
1301     use_fallbacks = store->use_fallbacks;
1302     CRYPTO_THREAD_unlock(store->lock);
1303     if (!use_fallbacks)
1304         return 1;
1305 
1306     if (!CRYPTO_THREAD_write_lock(store->lock))
1307         return 0;
1308     /* Check again, just in case another thread changed it */
1309     use_fallbacks = store->use_fallbacks;
1310     if (!use_fallbacks) {
1311         CRYPTO_THREAD_unlock(store->lock);
1312         return 1;
1313     }
1314 
1315     for (p = ossl_predefined_providers; p->name != NULL; p++) {
1316         OSSL_PROVIDER *prov = NULL;
1317 
1318         if (!p->is_fallback)
1319             continue;
1320         /*
1321          * We use the internal constructor directly here,
1322          * otherwise we get a call loop
1323          */
1324         prov = provider_new(p->name, p->init, NULL);
1325         if (prov == NULL)
1326             goto err;
1327         prov->libctx = store->libctx;
1328 #ifndef FIPS_MODULE
1329         prov->error_lib = ERR_get_next_error_library();
1330 #endif
1331 
1332         /*
1333          * We are calling provider_activate while holding the store lock. This
1334          * means the init function will be called while holding a lock. Normally
1335          * we try to avoid calling a user callback while holding a lock.
1336          * However, fallbacks are never third party providers so we accept this.
1337          */
1338         if (provider_activate(prov, 0, 0) < 0) {
1339             ossl_provider_free(prov);
1340             goto err;
1341         }
1342         prov->store = store;
1343         if (sk_OSSL_PROVIDER_push(store->providers, prov) == 0) {
1344             ossl_provider_free(prov);
1345             goto err;
1346         }
1347         activated_fallback_count++;
1348     }
1349 
1350     if (activated_fallback_count > 0) {
1351         store->use_fallbacks = 0;
1352         ret = 1;
1353     }
1354  err:
1355     CRYPTO_THREAD_unlock(store->lock);
1356     return ret;
1357 }
1358 
1359 int ossl_provider_doall_activated(OSSL_LIB_CTX *ctx,
1360                                   int (*cb)(OSSL_PROVIDER *provider,
1361                                             void *cbdata),
1362                                   void *cbdata)
1363 {
1364     int ret = 0, curr, max, ref = 0;
1365     struct provider_store_st *store = get_provider_store(ctx);
1366     STACK_OF(OSSL_PROVIDER) *provs = NULL;
1367 
1368 #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_AUTOLOAD_CONFIG)
1369     /*
1370      * Make sure any providers are loaded from config before we try to use
1371      * them.
1372      */
1373     if (ossl_lib_ctx_is_default(ctx))
1374         OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
1375 #endif
1376 
1377     if (store == NULL)
1378         return 1;
1379     if (!provider_activate_fallbacks(store))
1380         return 0;
1381 
1382     /*
1383      * Under lock, grab a copy of the provider list and up_ref each
1384      * provider so that they don't disappear underneath us.
1385      */
1386     if (!CRYPTO_THREAD_read_lock(store->lock))
1387         return 0;
1388     provs = sk_OSSL_PROVIDER_dup(store->providers);
1389     if (provs == NULL) {
1390         CRYPTO_THREAD_unlock(store->lock);
1391         return 0;
1392     }
1393     max = sk_OSSL_PROVIDER_num(provs);
1394     /*
1395      * We work backwards through the stack so that we can safely delete items
1396      * as we go.
1397      */
1398     for (curr = max - 1; curr >= 0; curr--) {
1399         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1400 
1401         if (!CRYPTO_THREAD_write_lock(prov->flag_lock))
1402             goto err_unlock;
1403         if (prov->flag_activated) {
1404             /*
1405              * We call CRYPTO_UP_REF directly rather than ossl_provider_up_ref
1406              * to avoid upping the ref count on the parent provider, which we
1407              * must not do while holding locks.
1408              */
1409             if (CRYPTO_UP_REF(&prov->refcnt, &ref, prov->refcnt_lock) <= 0) {
1410                 CRYPTO_THREAD_unlock(prov->flag_lock);
1411                 goto err_unlock;
1412             }
1413             /*
1414              * It's already activated, but we up the activated count to ensure
1415              * it remains activated until after we've called the user callback.
1416              * We do this with no locking (because we already hold the locks)
1417              * and no upcalls (which must not be called when locks are held). In
1418              * theory this could mean the parent provider goes inactive, whilst
1419              * still activated in the child for a short period. That's ok.
1420              */
1421             if (provider_activate(prov, 0, 0) < 0) {
1422                 CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
1423                 CRYPTO_THREAD_unlock(prov->flag_lock);
1424                 goto err_unlock;
1425             }
1426         } else {
1427             sk_OSSL_PROVIDER_delete(provs, curr);
1428             max--;
1429         }
1430         CRYPTO_THREAD_unlock(prov->flag_lock);
1431     }
1432     CRYPTO_THREAD_unlock(store->lock);
1433 
1434     /*
1435      * Now, we sweep through all providers not under lock
1436      */
1437     for (curr = 0; curr < max; curr++) {
1438         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1439 
1440         if (!cb(prov, cbdata)) {
1441             curr = -1;
1442             goto finish;
1443         }
1444     }
1445     curr = -1;
1446 
1447     ret = 1;
1448     goto finish;
1449 
1450  err_unlock:
1451     CRYPTO_THREAD_unlock(store->lock);
1452  finish:
1453     /*
1454      * The pop_free call doesn't do what we want on an error condition. We
1455      * either start from the first item in the stack, or part way through if
1456      * we only processed some of the items.
1457      */
1458     for (curr++; curr < max; curr++) {
1459         OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(provs, curr);
1460 
1461         provider_deactivate(prov, 0, 1);
1462         /*
1463          * As above where we did the up-ref, we don't call ossl_provider_free
1464          * to avoid making upcalls. There should always be at least one ref
1465          * to the provider in the store, so this should never drop to 0.
1466          */
1467         CRYPTO_DOWN_REF(&prov->refcnt, &ref, prov->refcnt_lock);
1468         /*
1469          * Not much we can do if this assert ever fails. So we don't use
1470          * ossl_assert here.
1471          */
1472         assert(ref > 0);
1473     }
1474     sk_OSSL_PROVIDER_free(provs);
1475     return ret;
1476 }
1477 
1478 int OSSL_PROVIDER_available(OSSL_LIB_CTX *libctx, const char *name)
1479 {
1480     OSSL_PROVIDER *prov = NULL;
1481     int available = 0;
1482     struct provider_store_st *store = get_provider_store(libctx);
1483 
1484     if (store == NULL || !provider_activate_fallbacks(store))
1485         return 0;
1486 
1487     prov = ossl_provider_find(libctx, name, 0);
1488     if (prov != NULL) {
1489         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
1490             return 0;
1491         available = prov->flag_activated;
1492         CRYPTO_THREAD_unlock(prov->flag_lock);
1493         ossl_provider_free(prov);
1494     }
1495     return available;
1496 }
1497 
1498 /* Setters of Provider Object data */
1499 int ossl_provider_set_fallback(OSSL_PROVIDER *prov)
1500 {
1501     if (prov == NULL)
1502         return 0;
1503 
1504     prov->flag_fallback = 1;
1505     return 1;
1506 }
1507 
1508 /* Getters of Provider Object data */
1509 const char *ossl_provider_name(const OSSL_PROVIDER *prov)
1510 {
1511     return prov->name;
1512 }
1513 
1514 const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov)
1515 {
1516     return prov->module;
1517 }
1518 
1519 const char *ossl_provider_module_name(const OSSL_PROVIDER *prov)
1520 {
1521 #ifdef FIPS_MODULE
1522     return NULL;
1523 #else
1524     return DSO_get_filename(prov->module);
1525 #endif
1526 }
1527 
1528 const char *ossl_provider_module_path(const OSSL_PROVIDER *prov)
1529 {
1530 #ifdef FIPS_MODULE
1531     return NULL;
1532 #else
1533     /* FIXME: Ensure it's a full path */
1534     return DSO_get_filename(prov->module);
1535 #endif
1536 }
1537 
1538 void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov)
1539 {
1540     if (prov != NULL)
1541         return prov->provctx;
1542 
1543     return NULL;
1544 }
1545 
1546 const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov)
1547 {
1548     if (prov != NULL)
1549         return prov->dispatch;
1550 
1551     return NULL;
1552 }
1553 
1554 OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov)
1555 {
1556     return prov != NULL ? prov->libctx : NULL;
1557 }
1558 
1559 /* Wrappers around calls to the provider */
1560 void ossl_provider_teardown(const OSSL_PROVIDER *prov)
1561 {
1562     if (prov->teardown != NULL
1563 #ifndef FIPS_MODULE
1564             && !prov->ischild
1565 #endif
1566        )
1567         prov->teardown(prov->provctx);
1568 }
1569 
1570 const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov)
1571 {
1572     return prov->gettable_params == NULL
1573         ? NULL : prov->gettable_params(prov->provctx);
1574 }
1575 
1576 int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[])
1577 {
1578     return prov->get_params == NULL
1579         ? 0 : prov->get_params(prov->provctx, params);
1580 }
1581 
1582 int ossl_provider_self_test(const OSSL_PROVIDER *prov)
1583 {
1584     int ret;
1585 
1586     if (prov->self_test == NULL)
1587         return 1;
1588     ret = prov->self_test(prov->provctx);
1589     if (ret == 0)
1590         (void)provider_remove_store_methods((OSSL_PROVIDER *)prov);
1591     return ret;
1592 }
1593 
1594 int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
1595                                    const char *capability,
1596                                    OSSL_CALLBACK *cb,
1597                                    void *arg)
1598 {
1599     return prov->get_capabilities == NULL
1600         ? 1 : prov->get_capabilities(prov->provctx, capability, cb, arg);
1601 }
1602 
1603 const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
1604                                                     int operation_id,
1605                                                     int *no_cache)
1606 {
1607     const OSSL_ALGORITHM *res;
1608 
1609     if (prov->query_operation == NULL)
1610         return NULL;
1611     res = prov->query_operation(prov->provctx, operation_id, no_cache);
1612 #if defined(OPENSSL_NO_CACHED_FETCH)
1613     /* Forcing the non-caching of queries */
1614     if (no_cache != NULL)
1615         *no_cache = 1;
1616 #endif
1617     return res;
1618 }
1619 
1620 void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov,
1621                                      int operation_id,
1622                                      const OSSL_ALGORITHM *algs)
1623 {
1624     if (prov->unquery_operation != NULL)
1625         prov->unquery_operation(prov->provctx, operation_id, algs);
1626 }
1627 
1628 int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum)
1629 {
1630     size_t byte = bitnum / 8;
1631     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
1632 
1633     if (!CRYPTO_THREAD_write_lock(provider->opbits_lock))
1634         return 0;
1635     if (provider->operation_bits_sz <= byte) {
1636         unsigned char *tmp = OPENSSL_realloc(provider->operation_bits,
1637                                              byte + 1);
1638 
1639         if (tmp == NULL) {
1640             CRYPTO_THREAD_unlock(provider->opbits_lock);
1641             ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
1642             return 0;
1643         }
1644         provider->operation_bits = tmp;
1645         memset(provider->operation_bits + provider->operation_bits_sz,
1646                '\0', byte + 1 - provider->operation_bits_sz);
1647         provider->operation_bits_sz = byte + 1;
1648     }
1649     provider->operation_bits[byte] |= bit;
1650     CRYPTO_THREAD_unlock(provider->opbits_lock);
1651     return 1;
1652 }
1653 
1654 int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
1655                                      int *result)
1656 {
1657     size_t byte = bitnum / 8;
1658     unsigned char bit = (1 << (bitnum % 8)) & 0xFF;
1659 
1660     if (!ossl_assert(result != NULL)) {
1661         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
1662         return 0;
1663     }
1664 
1665     *result = 0;
1666     if (!CRYPTO_THREAD_read_lock(provider->opbits_lock))
1667         return 0;
1668     if (provider->operation_bits_sz > byte)
1669         *result = ((provider->operation_bits[byte] & bit) != 0);
1670     CRYPTO_THREAD_unlock(provider->opbits_lock);
1671     return 1;
1672 }
1673 
1674 #ifndef FIPS_MODULE
1675 const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov)
1676 {
1677     return prov->handle;
1678 }
1679 
1680 int ossl_provider_is_child(const OSSL_PROVIDER *prov)
1681 {
1682     return prov->ischild;
1683 }
1684 
1685 int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle)
1686 {
1687     prov->handle = handle;
1688     prov->ischild = 1;
1689 
1690     return 1;
1691 }
1692 
1693 int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props)
1694 {
1695 #ifndef FIPS_MODULE
1696     struct provider_store_st *store = NULL;
1697     int i, max;
1698     OSSL_PROVIDER_CHILD_CB *child_cb;
1699 
1700     if ((store = get_provider_store(libctx)) == NULL)
1701         return 0;
1702 
1703     if (!CRYPTO_THREAD_read_lock(store->lock))
1704         return 0;
1705 
1706     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
1707     for (i = 0; i < max; i++) {
1708         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
1709         child_cb->global_props_cb(props, child_cb->cbdata);
1710     }
1711 
1712     CRYPTO_THREAD_unlock(store->lock);
1713 #endif
1714     return 1;
1715 }
1716 
1717 static int ossl_provider_register_child_cb(const OSSL_CORE_HANDLE *handle,
1718                                            int (*create_cb)(
1719                                                const OSSL_CORE_HANDLE *provider,
1720                                                void *cbdata),
1721                                            int (*remove_cb)(
1722                                                const OSSL_CORE_HANDLE *provider,
1723                                                void *cbdata),
1724                                            int (*global_props_cb)(
1725                                                const char *props,
1726                                                void *cbdata),
1727                                            void *cbdata)
1728 {
1729     /*
1730      * This is really an OSSL_PROVIDER that we created and cast to
1731      * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
1732      */
1733     OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
1734     OSSL_PROVIDER *prov;
1735     OSSL_LIB_CTX *libctx = thisprov->libctx;
1736     struct provider_store_st *store = NULL;
1737     int ret = 0, i, max;
1738     OSSL_PROVIDER_CHILD_CB *child_cb;
1739     char *propsstr = NULL;
1740 
1741     if ((store = get_provider_store(libctx)) == NULL)
1742         return 0;
1743 
1744     child_cb = OPENSSL_malloc(sizeof(*child_cb));
1745     if (child_cb == NULL)
1746         return 0;
1747     child_cb->prov = thisprov;
1748     child_cb->create_cb = create_cb;
1749     child_cb->remove_cb = remove_cb;
1750     child_cb->global_props_cb = global_props_cb;
1751     child_cb->cbdata = cbdata;
1752 
1753     if (!CRYPTO_THREAD_write_lock(store->lock)) {
1754         OPENSSL_free(child_cb);
1755         return 0;
1756     }
1757     propsstr = evp_get_global_properties_str(libctx, 0);
1758 
1759     if (propsstr != NULL) {
1760         global_props_cb(propsstr, cbdata);
1761         OPENSSL_free(propsstr);
1762     }
1763     max = sk_OSSL_PROVIDER_num(store->providers);
1764     for (i = 0; i < max; i++) {
1765         int activated;
1766 
1767         prov = sk_OSSL_PROVIDER_value(store->providers, i);
1768 
1769         if (!CRYPTO_THREAD_read_lock(prov->flag_lock))
1770             break;
1771         activated = prov->flag_activated;
1772         CRYPTO_THREAD_unlock(prov->flag_lock);
1773         /*
1774          * We hold the store lock while calling the user callback. This means
1775          * that the user callback must be short and simple and not do anything
1776          * likely to cause a deadlock. We don't hold the flag_lock during this
1777          * call. In theory this means that another thread could deactivate it
1778          * while we are calling create. This is ok because the other thread
1779          * will also call remove_cb, but won't be able to do so until we release
1780          * the store lock.
1781          */
1782         if (activated && !create_cb((OSSL_CORE_HANDLE *)prov, cbdata))
1783             break;
1784     }
1785     if (i == max) {
1786         /* Success */
1787         ret = sk_OSSL_PROVIDER_CHILD_CB_push(store->child_cbs, child_cb);
1788     }
1789     if (i != max || ret <= 0) {
1790         /* Failed during creation. Remove everything we just added */
1791         for (; i >= 0; i--) {
1792             prov = sk_OSSL_PROVIDER_value(store->providers, i);
1793             remove_cb((OSSL_CORE_HANDLE *)prov, cbdata);
1794         }
1795         OPENSSL_free(child_cb);
1796         ret = 0;
1797     }
1798     CRYPTO_THREAD_unlock(store->lock);
1799 
1800     return ret;
1801 }
1802 
1803 static void ossl_provider_deregister_child_cb(const OSSL_CORE_HANDLE *handle)
1804 {
1805     /*
1806      * This is really an OSSL_PROVIDER that we created and cast to
1807      * OSSL_CORE_HANDLE originally. Therefore it is safe to cast it back.
1808      */
1809     OSSL_PROVIDER *thisprov = (OSSL_PROVIDER *)handle;
1810     OSSL_LIB_CTX *libctx = thisprov->libctx;
1811     struct provider_store_st *store = NULL;
1812     int i, max;
1813     OSSL_PROVIDER_CHILD_CB *child_cb;
1814 
1815     if ((store = get_provider_store(libctx)) == NULL)
1816         return;
1817 
1818     if (!CRYPTO_THREAD_write_lock(store->lock))
1819         return;
1820     max = sk_OSSL_PROVIDER_CHILD_CB_num(store->child_cbs);
1821     for (i = 0; i < max; i++) {
1822         child_cb = sk_OSSL_PROVIDER_CHILD_CB_value(store->child_cbs, i);
1823         if (child_cb->prov == thisprov) {
1824             /* Found an entry */
1825             sk_OSSL_PROVIDER_CHILD_CB_delete(store->child_cbs, i);
1826             OPENSSL_free(child_cb);
1827             break;
1828         }
1829     }
1830     CRYPTO_THREAD_unlock(store->lock);
1831 }
1832 #endif
1833 
1834 /*-
1835  * Core functions for the provider
1836  * ===============================
1837  *
1838  * This is the set of functions that the core makes available to the provider
1839  */
1840 
1841 /*
1842  * This returns a list of Provider Object parameters with their types, for
1843  * discovery.  We do not expect that many providers will use this, but one
1844  * never knows.
1845  */
1846 static const OSSL_PARAM param_types[] = {
1847     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_VERSION, OSSL_PARAM_UTF8_PTR, NULL, 0),
1848     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_PROV_NAME, OSSL_PARAM_UTF8_PTR,
1849                     NULL, 0),
1850 #ifndef FIPS_MODULE
1851     OSSL_PARAM_DEFN(OSSL_PROV_PARAM_CORE_MODULE_FILENAME, OSSL_PARAM_UTF8_PTR,
1852                     NULL, 0),
1853 #endif
1854     OSSL_PARAM_END
1855 };
1856 
1857 /*
1858  * Forward declare all the functions that are provided aa dispatch.
1859  * This ensures that the compiler will complain if they aren't defined
1860  * with the correct signature.
1861  */
1862 static OSSL_FUNC_core_gettable_params_fn core_gettable_params;
1863 static OSSL_FUNC_core_get_params_fn core_get_params;
1864 static OSSL_FUNC_core_get_libctx_fn core_get_libctx;
1865 static OSSL_FUNC_core_thread_start_fn core_thread_start;
1866 #ifndef FIPS_MODULE
1867 static OSSL_FUNC_core_new_error_fn core_new_error;
1868 static OSSL_FUNC_core_set_error_debug_fn core_set_error_debug;
1869 static OSSL_FUNC_core_vset_error_fn core_vset_error;
1870 static OSSL_FUNC_core_set_error_mark_fn core_set_error_mark;
1871 static OSSL_FUNC_core_clear_last_error_mark_fn core_clear_last_error_mark;
1872 static OSSL_FUNC_core_pop_error_to_mark_fn core_pop_error_to_mark;
1873 OSSL_FUNC_BIO_new_file_fn ossl_core_bio_new_file;
1874 OSSL_FUNC_BIO_new_membuf_fn ossl_core_bio_new_mem_buf;
1875 OSSL_FUNC_BIO_read_ex_fn ossl_core_bio_read_ex;
1876 OSSL_FUNC_BIO_write_ex_fn ossl_core_bio_write_ex;
1877 OSSL_FUNC_BIO_gets_fn ossl_core_bio_gets;
1878 OSSL_FUNC_BIO_puts_fn ossl_core_bio_puts;
1879 OSSL_FUNC_BIO_up_ref_fn ossl_core_bio_up_ref;
1880 OSSL_FUNC_BIO_free_fn ossl_core_bio_free;
1881 OSSL_FUNC_BIO_vprintf_fn ossl_core_bio_vprintf;
1882 OSSL_FUNC_BIO_vsnprintf_fn BIO_vsnprintf;
1883 static OSSL_FUNC_self_test_cb_fn core_self_test_get_callback;
1884 OSSL_FUNC_get_entropy_fn ossl_rand_get_entropy;
1885 OSSL_FUNC_cleanup_entropy_fn ossl_rand_cleanup_entropy;
1886 OSSL_FUNC_get_nonce_fn ossl_rand_get_nonce;
1887 OSSL_FUNC_cleanup_nonce_fn ossl_rand_cleanup_nonce;
1888 #endif
1889 OSSL_FUNC_CRYPTO_malloc_fn CRYPTO_malloc;
1890 OSSL_FUNC_CRYPTO_zalloc_fn CRYPTO_zalloc;
1891 OSSL_FUNC_CRYPTO_free_fn CRYPTO_free;
1892 OSSL_FUNC_CRYPTO_clear_free_fn CRYPTO_clear_free;
1893 OSSL_FUNC_CRYPTO_realloc_fn CRYPTO_realloc;
1894 OSSL_FUNC_CRYPTO_clear_realloc_fn CRYPTO_clear_realloc;
1895 OSSL_FUNC_CRYPTO_secure_malloc_fn CRYPTO_secure_malloc;
1896 OSSL_FUNC_CRYPTO_secure_zalloc_fn CRYPTO_secure_zalloc;
1897 OSSL_FUNC_CRYPTO_secure_free_fn CRYPTO_secure_free;
1898 OSSL_FUNC_CRYPTO_secure_clear_free_fn CRYPTO_secure_clear_free;
1899 OSSL_FUNC_CRYPTO_secure_allocated_fn CRYPTO_secure_allocated;
1900 OSSL_FUNC_OPENSSL_cleanse_fn OPENSSL_cleanse;
1901 #ifndef FIPS_MODULE
1902 OSSL_FUNC_provider_register_child_cb_fn ossl_provider_register_child_cb;
1903 OSSL_FUNC_provider_deregister_child_cb_fn ossl_provider_deregister_child_cb;
1904 static OSSL_FUNC_provider_name_fn core_provider_get0_name;
1905 static OSSL_FUNC_provider_get0_provider_ctx_fn core_provider_get0_provider_ctx;
1906 static OSSL_FUNC_provider_get0_dispatch_fn core_provider_get0_dispatch;
1907 static OSSL_FUNC_provider_up_ref_fn core_provider_up_ref_intern;
1908 static OSSL_FUNC_provider_free_fn core_provider_free_intern;
1909 static OSSL_FUNC_core_obj_add_sigid_fn core_obj_add_sigid;
1910 static OSSL_FUNC_core_obj_create_fn core_obj_create;
1911 #endif
1912 
1913 static const OSSL_PARAM *core_gettable_params(const OSSL_CORE_HANDLE *handle)
1914 {
1915     return param_types;
1916 }
1917 
1918 static int core_get_params(const OSSL_CORE_HANDLE *handle, OSSL_PARAM params[])
1919 {
1920     int i;
1921     OSSL_PARAM *p;
1922     /*
1923      * We created this object originally and we know it is actually an
1924      * OSSL_PROVIDER *, so the cast is safe
1925      */
1926     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1927 
1928     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_VERSION)) != NULL)
1929         OSSL_PARAM_set_utf8_ptr(p, OPENSSL_VERSION_STR);
1930     if ((p = OSSL_PARAM_locate(params, OSSL_PROV_PARAM_CORE_PROV_NAME)) != NULL)
1931         OSSL_PARAM_set_utf8_ptr(p, prov->name);
1932 
1933 #ifndef FIPS_MODULE
1934     if ((p = OSSL_PARAM_locate(params,
1935                                OSSL_PROV_PARAM_CORE_MODULE_FILENAME)) != NULL)
1936         OSSL_PARAM_set_utf8_ptr(p, ossl_provider_module_path(prov));
1937 #endif
1938 
1939     if (prov->parameters == NULL)
1940         return 1;
1941 
1942     for (i = 0; i < sk_INFOPAIR_num(prov->parameters); i++) {
1943         INFOPAIR *pair = sk_INFOPAIR_value(prov->parameters, i);
1944 
1945         if ((p = OSSL_PARAM_locate(params, pair->name)) != NULL)
1946             OSSL_PARAM_set_utf8_ptr(p, pair->value);
1947     }
1948     return 1;
1949 }
1950 
1951 static OPENSSL_CORE_CTX *core_get_libctx(const OSSL_CORE_HANDLE *handle)
1952 {
1953     /*
1954      * We created this object originally and we know it is actually an
1955      * OSSL_PROVIDER *, so the cast is safe
1956      */
1957     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1958 
1959     /*
1960      * Using ossl_provider_libctx would be wrong as that returns
1961      * NULL for |prov| == NULL and NULL libctx has a special meaning
1962      * that does not apply here. Here |prov| == NULL can happen only in
1963      * case of a coding error.
1964      */
1965     assert(prov != NULL);
1966     return (OPENSSL_CORE_CTX *)prov->libctx;
1967 }
1968 
1969 static int core_thread_start(const OSSL_CORE_HANDLE *handle,
1970                              OSSL_thread_stop_handler_fn handfn,
1971                              void *arg)
1972 {
1973     /*
1974      * We created this object originally and we know it is actually an
1975      * OSSL_PROVIDER *, so the cast is safe
1976      */
1977     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
1978 
1979     return ossl_init_thread_start(prov, arg, handfn);
1980 }
1981 
1982 /*
1983  * The FIPS module inner provider doesn't implement these.  They aren't
1984  * needed there, since the FIPS module upcalls are always the outer provider
1985  * ones.
1986  */
1987 #ifndef FIPS_MODULE
1988 /*
1989  * These error functions should use |handle| to select the proper
1990  * library context to report in the correct error stack if error
1991  * stacks become tied to the library context.
1992  * We cannot currently do that since there's no support for it in the
1993  * ERR subsystem.
1994  */
1995 static void core_new_error(const OSSL_CORE_HANDLE *handle)
1996 {
1997     ERR_new();
1998 }
1999 
2000 static void core_set_error_debug(const OSSL_CORE_HANDLE *handle,
2001                                  const char *file, int line, const char *func)
2002 {
2003     ERR_set_debug(file, line, func);
2004 }
2005 
2006 static void core_vset_error(const OSSL_CORE_HANDLE *handle,
2007                             uint32_t reason, const char *fmt, va_list args)
2008 {
2009     /*
2010      * We created this object originally and we know it is actually an
2011      * OSSL_PROVIDER *, so the cast is safe
2012      */
2013     OSSL_PROVIDER *prov = (OSSL_PROVIDER *)handle;
2014 
2015     /*
2016      * If the uppermost 8 bits are non-zero, it's an OpenSSL library
2017      * error and will be treated as such.  Otherwise, it's a new style
2018      * provider error and will be treated as such.
2019      */
2020     if (ERR_GET_LIB(reason) != 0) {
2021         ERR_vset_error(ERR_GET_LIB(reason), ERR_GET_REASON(reason), fmt, args);
2022     } else {
2023         ERR_vset_error(prov->error_lib, (int)reason, fmt, args);
2024     }
2025 }
2026 
2027 static int core_set_error_mark(const OSSL_CORE_HANDLE *handle)
2028 {
2029     return ERR_set_mark();
2030 }
2031 
2032 static int core_clear_last_error_mark(const OSSL_CORE_HANDLE *handle)
2033 {
2034     return ERR_clear_last_mark();
2035 }
2036 
2037 static int core_pop_error_to_mark(const OSSL_CORE_HANDLE *handle)
2038 {
2039     return ERR_pop_to_mark();
2040 }
2041 
2042 static void core_self_test_get_callback(OPENSSL_CORE_CTX *libctx,
2043                                         OSSL_CALLBACK **cb, void **cbarg)
2044 {
2045     OSSL_SELF_TEST_get_callback((OSSL_LIB_CTX *)libctx, cb, cbarg);
2046 }
2047 
2048 static const char *core_provider_get0_name(const OSSL_CORE_HANDLE *prov)
2049 {
2050     return OSSL_PROVIDER_get0_name((const OSSL_PROVIDER *)prov);
2051 }
2052 
2053 static void *core_provider_get0_provider_ctx(const OSSL_CORE_HANDLE *prov)
2054 {
2055     return OSSL_PROVIDER_get0_provider_ctx((const OSSL_PROVIDER *)prov);
2056 }
2057 
2058 static const OSSL_DISPATCH *
2059 core_provider_get0_dispatch(const OSSL_CORE_HANDLE *prov)
2060 {
2061     return OSSL_PROVIDER_get0_dispatch((const OSSL_PROVIDER *)prov);
2062 }
2063 
2064 static int core_provider_up_ref_intern(const OSSL_CORE_HANDLE *prov,
2065                                        int activate)
2066 {
2067     return provider_up_ref_intern((OSSL_PROVIDER *)prov, activate);
2068 }
2069 
2070 static int core_provider_free_intern(const OSSL_CORE_HANDLE *prov,
2071                                      int deactivate)
2072 {
2073     return provider_free_intern((OSSL_PROVIDER *)prov, deactivate);
2074 }
2075 
2076 static int core_obj_add_sigid(const OSSL_CORE_HANDLE *prov,
2077                               const char *sign_name, const char *digest_name,
2078                               const char *pkey_name)
2079 {
2080     int sign_nid = OBJ_txt2nid(sign_name);
2081     int digest_nid = NID_undef;
2082     int pkey_nid = OBJ_txt2nid(pkey_name);
2083 
2084     if (digest_name != NULL && digest_name[0] != '\0'
2085         && (digest_nid = OBJ_txt2nid(digest_name)) == NID_undef)
2086             return 0;
2087 
2088     if (sign_nid == NID_undef)
2089         return 0;
2090 
2091     /*
2092      * Check if it already exists. This is a success if so (even if we don't
2093      * have nids for the digest/pkey)
2094      */
2095     if (OBJ_find_sigid_algs(sign_nid, NULL, NULL))
2096         return 1;
2097 
2098     if (pkey_nid == NID_undef)
2099         return 0;
2100 
2101     return OBJ_add_sigid(sign_nid, digest_nid, pkey_nid);
2102 }
2103 
2104 static int core_obj_create(const OSSL_CORE_HANDLE *prov, const char *oid,
2105                            const char *sn, const char *ln)
2106 {
2107     /* Check if it already exists and create it if not */
2108     return OBJ_txt2nid(oid) != NID_undef
2109            || OBJ_create(oid, sn, ln) != NID_undef;
2110 }
2111 #endif /* FIPS_MODULE */
2112 
2113 /*
2114  * Functions provided by the core.
2115  */
2116 static const OSSL_DISPATCH core_dispatch_[] = {
2117     { OSSL_FUNC_CORE_GETTABLE_PARAMS, (void (*)(void))core_gettable_params },
2118     { OSSL_FUNC_CORE_GET_PARAMS, (void (*)(void))core_get_params },
2119     { OSSL_FUNC_CORE_GET_LIBCTX, (void (*)(void))core_get_libctx },
2120     { OSSL_FUNC_CORE_THREAD_START, (void (*)(void))core_thread_start },
2121 #ifndef FIPS_MODULE
2122     { OSSL_FUNC_CORE_NEW_ERROR, (void (*)(void))core_new_error },
2123     { OSSL_FUNC_CORE_SET_ERROR_DEBUG, (void (*)(void))core_set_error_debug },
2124     { OSSL_FUNC_CORE_VSET_ERROR, (void (*)(void))core_vset_error },
2125     { OSSL_FUNC_CORE_SET_ERROR_MARK, (void (*)(void))core_set_error_mark },
2126     { OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK,
2127       (void (*)(void))core_clear_last_error_mark },
2128     { OSSL_FUNC_CORE_POP_ERROR_TO_MARK, (void (*)(void))core_pop_error_to_mark },
2129     { OSSL_FUNC_BIO_NEW_FILE, (void (*)(void))ossl_core_bio_new_file },
2130     { OSSL_FUNC_BIO_NEW_MEMBUF, (void (*)(void))ossl_core_bio_new_mem_buf },
2131     { OSSL_FUNC_BIO_READ_EX, (void (*)(void))ossl_core_bio_read_ex },
2132     { OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))ossl_core_bio_write_ex },
2133     { OSSL_FUNC_BIO_GETS, (void (*)(void))ossl_core_bio_gets },
2134     { OSSL_FUNC_BIO_PUTS, (void (*)(void))ossl_core_bio_puts },
2135     { OSSL_FUNC_BIO_CTRL, (void (*)(void))ossl_core_bio_ctrl },
2136     { OSSL_FUNC_BIO_UP_REF, (void (*)(void))ossl_core_bio_up_ref },
2137     { OSSL_FUNC_BIO_FREE, (void (*)(void))ossl_core_bio_free },
2138     { OSSL_FUNC_BIO_VPRINTF, (void (*)(void))ossl_core_bio_vprintf },
2139     { OSSL_FUNC_BIO_VSNPRINTF, (void (*)(void))BIO_vsnprintf },
2140     { OSSL_FUNC_SELF_TEST_CB, (void (*)(void))core_self_test_get_callback },
2141     { OSSL_FUNC_GET_ENTROPY, (void (*)(void))ossl_rand_get_entropy },
2142     { OSSL_FUNC_CLEANUP_ENTROPY, (void (*)(void))ossl_rand_cleanup_entropy },
2143     { OSSL_FUNC_GET_NONCE, (void (*)(void))ossl_rand_get_nonce },
2144     { OSSL_FUNC_CLEANUP_NONCE, (void (*)(void))ossl_rand_cleanup_nonce },
2145 #endif
2146     { OSSL_FUNC_CRYPTO_MALLOC, (void (*)(void))CRYPTO_malloc },
2147     { OSSL_FUNC_CRYPTO_ZALLOC, (void (*)(void))CRYPTO_zalloc },
2148     { OSSL_FUNC_CRYPTO_FREE, (void (*)(void))CRYPTO_free },
2149     { OSSL_FUNC_CRYPTO_CLEAR_FREE, (void (*)(void))CRYPTO_clear_free },
2150     { OSSL_FUNC_CRYPTO_REALLOC, (void (*)(void))CRYPTO_realloc },
2151     { OSSL_FUNC_CRYPTO_CLEAR_REALLOC, (void (*)(void))CRYPTO_clear_realloc },
2152     { OSSL_FUNC_CRYPTO_SECURE_MALLOC, (void (*)(void))CRYPTO_secure_malloc },
2153     { OSSL_FUNC_CRYPTO_SECURE_ZALLOC, (void (*)(void))CRYPTO_secure_zalloc },
2154     { OSSL_FUNC_CRYPTO_SECURE_FREE, (void (*)(void))CRYPTO_secure_free },
2155     { OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE,
2156         (void (*)(void))CRYPTO_secure_clear_free },
2157     { OSSL_FUNC_CRYPTO_SECURE_ALLOCATED,
2158         (void (*)(void))CRYPTO_secure_allocated },
2159     { OSSL_FUNC_OPENSSL_CLEANSE, (void (*)(void))OPENSSL_cleanse },
2160 #ifndef FIPS_MODULE
2161     { OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB,
2162         (void (*)(void))ossl_provider_register_child_cb },
2163     { OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB,
2164         (void (*)(void))ossl_provider_deregister_child_cb },
2165     { OSSL_FUNC_PROVIDER_NAME,
2166         (void (*)(void))core_provider_get0_name },
2167     { OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX,
2168         (void (*)(void))core_provider_get0_provider_ctx },
2169     { OSSL_FUNC_PROVIDER_GET0_DISPATCH,
2170         (void (*)(void))core_provider_get0_dispatch },
2171     { OSSL_FUNC_PROVIDER_UP_REF,
2172         (void (*)(void))core_provider_up_ref_intern },
2173     { OSSL_FUNC_PROVIDER_FREE,
2174         (void (*)(void))core_provider_free_intern },
2175     { OSSL_FUNC_CORE_OBJ_ADD_SIGID, (void (*)(void))core_obj_add_sigid },
2176     { OSSL_FUNC_CORE_OBJ_CREATE, (void (*)(void))core_obj_create },
2177 #endif
2178     { 0, NULL }
2179 };
2180 static const OSSL_DISPATCH *core_dispatch = core_dispatch_;
2181