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