Update copyright year
[openssl.git] / providers / implementations / storemgmt / file_store.c
1 /*
2  * Copyright 2020-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 /* This file has quite some overlap with engines/e_loader_attic.c */
11
12 #include <string.h>
13 #include <sys/stat.h>
14 #include <ctype.h>  /* isdigit */
15 #include <assert.h>
16
17 #include <openssl/core_dispatch.h>
18 #include <openssl/core_names.h>
19 #include <openssl/core_object.h>
20 #include <openssl/bio.h>
21 #include <openssl/err.h>
22 #include <openssl/params.h>
23 #include <openssl/decoder.h>
24 #include <openssl/proverr.h>
25 #include <openssl/store.h>       /* The OSSL_STORE_INFO type numbers */
26 #include "internal/cryptlib.h"
27 #include "internal/o_dir.h"
28 #include "crypto/decoder.h"
29 #include "crypto/ctype.h"        /* ossl_isdigit() */
30 #include "prov/implementations.h"
31 #include "prov/bio.h"
32 #include "file_store_local.h"
33
34 DEFINE_STACK_OF(OSSL_STORE_INFO)
35
36 #ifdef _WIN32
37 # define stat _stat
38 #endif
39
40 #ifndef S_ISDIR
41 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
42 #endif
43
44 static OSSL_FUNC_store_open_fn file_open;
45 static OSSL_FUNC_store_attach_fn file_attach;
46 static OSSL_FUNC_store_settable_ctx_params_fn file_settable_ctx_params;
47 static OSSL_FUNC_store_set_ctx_params_fn file_set_ctx_params;
48 static OSSL_FUNC_store_load_fn file_load;
49 static OSSL_FUNC_store_eof_fn file_eof;
50 static OSSL_FUNC_store_close_fn file_close;
51
52 /*
53  * This implementation makes full use of OSSL_DECODER, and then some.
54  * It uses its own internal decoder implementation that reads DER and
55  * passes that on to the data callback; this decoder is created with
56  * internal OpenSSL functions, thereby bypassing the need for a surrounding
57  * provider.  This is ok, since this is a local decoder, not meant for
58  * public consumption.  It also uses the libcrypto internal decoder
59  * setup function ossl_decoder_ctx_setup_for_pkey(), to allow the
60  * last resort decoder to be added first (and thereby be executed last).
61  * Finally, it sets up its own construct and cleanup functions.
62  *
63  * Essentially, that makes this implementation a kind of glorified decoder.
64  */
65
66 struct file_ctx_st {
67     void *provctx;
68     char *uri;                   /* The URI we currently try to load */
69     enum {
70         IS_FILE = 0,             /* Read file and pass results */
71         IS_DIR                   /* Pass directory entry names */
72     } type;
73
74     union {
75         /* Used with |IS_FILE| */
76         struct {
77             BIO *file;
78
79             OSSL_DECODER_CTX *decoderctx;
80             char *input_type;
81             char *propq;    /* The properties we got as a parameter */
82         } file;
83
84         /* Used with |IS_DIR| */
85         struct {
86             OPENSSL_DIR_CTX *ctx;
87             int end_reached;
88
89             /*
90              * When a search expression is given, these are filled in.
91              * |search_name| contains the file basename to look for.
92              * The string is exactly 8 characters long.
93              */
94             char search_name[9];
95
96             /*
97              * The directory reading utility we have combines opening with
98              * reading the first name.  To make sure we can detect the end
99              * at the right time, we read early and cache the name.
100              */
101             const char *last_entry;
102             int last_errno;
103         } dir;
104     } _;
105
106     /* Expected object type.  May be unspecified */
107     int expected_type;
108 };
109
110 static void free_file_ctx(struct file_ctx_st *ctx)
111 {
112     if (ctx == NULL)
113         return;
114
115     OPENSSL_free(ctx->uri);
116     if (ctx->type != IS_DIR) {
117         OSSL_DECODER_CTX_free(ctx->_.file.decoderctx);
118         OPENSSL_free(ctx->_.file.propq);
119         OPENSSL_free(ctx->_.file.input_type);
120     }
121     OPENSSL_free(ctx);
122 }
123
124 static struct file_ctx_st *new_file_ctx(int type, const char *uri,
125                                         void *provctx)
126 {
127     struct file_ctx_st *ctx = NULL;
128
129     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) != NULL
130         && (uri == NULL || (ctx->uri = OPENSSL_strdup(uri)) != NULL)) {
131         ctx->type = type;
132         ctx->provctx = provctx;
133         return ctx;
134     }
135     free_file_ctx(ctx);
136     return NULL;
137 }
138
139 static OSSL_DECODER_CONSTRUCT file_load_construct;
140 static OSSL_DECODER_CLEANUP file_load_cleanup;
141
142 /*-
143  *  Opening / attaching streams and directories
144  *  -------------------------------------------
145  */
146
147 /*
148  * Function to service both file_open() and file_attach()
149  *
150  *
151  */
152 static struct file_ctx_st *file_open_stream(BIO *source, const char *uri,
153                                             void *provctx)
154 {
155     struct file_ctx_st *ctx;
156
157     if ((ctx = new_file_ctx(IS_FILE, uri, provctx)) == NULL) {
158         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
159         goto err;
160     }
161
162     ctx->_.file.file = source;
163
164     return ctx;
165  err:
166     free_file_ctx(ctx);
167     return NULL;
168 }
169
170 static void *file_open_dir(const char *path, const char *uri, void *provctx)
171 {
172     struct file_ctx_st *ctx;
173
174     if ((ctx = new_file_ctx(IS_DIR, uri, provctx)) == NULL) {
175         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
176         return NULL;
177     }
178
179     ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
180     ctx->_.dir.last_errno = errno;
181     if (ctx->_.dir.last_entry == NULL) {
182         if (ctx->_.dir.last_errno != 0) {
183             ERR_raise_data(ERR_LIB_SYS, ctx->_.dir.last_errno,
184                            "Calling OPENSSL_DIR_read(\"%s\")", path);
185             goto err;
186         }
187         ctx->_.dir.end_reached = 1;
188     }
189     return ctx;
190  err:
191     file_close(ctx);
192     return NULL;
193 }
194
195 static void *file_open(void *provctx, const char *uri)
196 {
197     struct file_ctx_st *ctx = NULL;
198     struct stat st;
199     struct {
200         const char *path;
201         unsigned int check_absolute:1;
202     } path_data[2];
203     size_t path_data_n = 0, i;
204     const char *path, *p = uri, *q;
205     BIO *bio;
206
207     ERR_set_mark();
208
209     /*
210      * First step, just take the URI as is.
211      */
212     path_data[path_data_n].check_absolute = 0;
213     path_data[path_data_n++].path = uri;
214
215     /*
216      * Second step, if the URI appears to start with the "file" scheme,
217      * extract the path and make that the second path to check.
218      * There's a special case if the URI also contains an authority, then
219      * the full URI shouldn't be used as a path anywhere.
220      */
221     if (CHECK_AND_SKIP_CASE_PREFIX(p, "file:")) {
222         q = p;
223         if (CHECK_AND_SKIP_CASE_PREFIX(q, "//")) {
224             path_data_n--;           /* Invalidate using the full URI */
225             if (CHECK_AND_SKIP_CASE_PREFIX(q, "localhost/")
226                     || CHECK_AND_SKIP_CASE_PREFIX(q, "/")) {
227                 p = q - 1;
228             } else {
229                 ERR_clear_last_mark();
230                 ERR_raise(ERR_LIB_PROV, PROV_R_URI_AUTHORITY_UNSUPPORTED);
231                 return NULL;
232             }
233         }
234
235         path_data[path_data_n].check_absolute = 1;
236 #ifdef _WIN32
237         /* Windows "file:" URIs with a drive letter start with a '/' */
238         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
239             char c = tolower(p[1]);
240
241             if (c >= 'a' && c <= 'z') {
242                 p++;
243                 /* We know it's absolute, so no need to check */
244                 path_data[path_data_n].check_absolute = 0;
245             }
246         }
247 #endif
248         path_data[path_data_n++].path = p;
249     }
250
251
252     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
253         /*
254          * If the scheme "file" was an explicit part of the URI, the path must
255          * be absolute.  So says RFC 8089
256          */
257         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
258             ERR_clear_last_mark();
259             ERR_raise_data(ERR_LIB_PROV, PROV_R_PATH_MUST_BE_ABSOLUTE,
260                            "Given path=%s", path_data[i].path);
261             return NULL;
262         }
263
264         if (stat(path_data[i].path, &st) < 0) {
265             ERR_raise_data(ERR_LIB_SYS, errno,
266                            "calling stat(%s)",
267                            path_data[i].path);
268         } else {
269             path = path_data[i].path;
270         }
271     }
272     if (path == NULL) {
273         ERR_clear_last_mark();
274         return NULL;
275     }
276
277     /* Successfully found a working path, clear possible collected errors */
278     ERR_pop_to_mark();
279
280     if (S_ISDIR(st.st_mode))
281         ctx = file_open_dir(path, uri, provctx);
282     else if ((bio = BIO_new_file(path, "rb")) == NULL
283              || (ctx = file_open_stream(bio, uri, provctx)) == NULL)
284         BIO_free_all(bio);
285
286     return ctx;
287 }
288
289 void *file_attach(void *provctx, OSSL_CORE_BIO *cin)
290 {
291     struct file_ctx_st *ctx;
292     BIO *new_bio = ossl_bio_new_from_core_bio(provctx, cin);
293
294     if (new_bio == NULL)
295         return NULL;
296
297     ctx = file_open_stream(new_bio, NULL, provctx);
298     if (ctx == NULL)
299         BIO_free(new_bio);
300     return ctx;
301 }
302
303 /*-
304  *  Setting parameters
305  *  ------------------
306  */
307
308 static const OSSL_PARAM *file_settable_ctx_params(void *provctx)
309 {
310     static const OSSL_PARAM known_settable_ctx_params[] = {
311         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_PROPERTIES, NULL, 0),
312         OSSL_PARAM_int(OSSL_STORE_PARAM_EXPECT, NULL),
313         OSSL_PARAM_octet_string(OSSL_STORE_PARAM_SUBJECT, NULL, 0),
314         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE, NULL, 0),
315         OSSL_PARAM_END
316     };
317     return known_settable_ctx_params;
318 }
319
320 static int file_set_ctx_params(void *loaderctx, const OSSL_PARAM params[])
321 {
322     struct file_ctx_st *ctx = loaderctx;
323     const OSSL_PARAM *p;
324
325     if (params == NULL)
326         return 1;
327
328     if (ctx->type != IS_DIR) {
329         /* these parameters are ignored for directories */
330         p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES);
331         if (p != NULL) {
332             OPENSSL_free(ctx->_.file.propq);
333             ctx->_.file.propq = NULL;
334             if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.propq, 0))
335                 return 0;
336         }
337         p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_INPUT_TYPE);
338         if (p != NULL) {
339             OPENSSL_free(ctx->_.file.input_type);
340             ctx->_.file.input_type = NULL;
341             if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.input_type, 0))
342                 return 0;
343         }
344     }
345     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_EXPECT);
346     if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->expected_type))
347         return 0;
348     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT);
349     if (p != NULL) {
350         const unsigned char *der = NULL;
351         size_t der_len = 0;
352         X509_NAME *x509_name;
353         unsigned long hash;
354         int ok;
355
356         if (ctx->type != IS_DIR) {
357             ERR_raise(ERR_LIB_PROV,
358                       PROV_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
359             return 0;
360         }
361
362         if (!OSSL_PARAM_get_octet_string_ptr(p, (const void **)&der, &der_len)
363             || (x509_name = d2i_X509_NAME(NULL, &der, der_len)) == NULL)
364             return 0;
365         hash = X509_NAME_hash_ex(x509_name,
366                                  ossl_prov_ctx_get0_libctx(ctx->provctx), NULL,
367                                  &ok);
368         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
369                      "%08lx", hash);
370         X509_NAME_free(x509_name);
371         if (ok == 0)
372             return 0;
373     }
374     return 1;
375 }
376
377 /*-
378  *  Loading an object from a stream
379  *  -------------------------------
380  */
381
382 struct file_load_data_st {
383     OSSL_CALLBACK *object_cb;
384     void *object_cbarg;
385 };
386
387 static int file_load_construct(OSSL_DECODER_INSTANCE *decoder_inst,
388                                const OSSL_PARAM *params, void *construct_data)
389 {
390     struct file_load_data_st *data = construct_data;
391
392     /*
393      * At some point, we may find it justifiable to recognise PKCS#12 and
394      * handle it specially here, making |file_load()| return pass its
395      * contents one piece at ta time, like |e_loader_attic.c| does.
396      *
397      * However, that currently means parsing them out, which converts the
398      * DER encoded PKCS#12 into a bunch of EVP_PKEYs and X509s, just to
399      * have to re-encode them into DER to create an object abstraction for
400      * each of them.
401      * It's much simpler (less churn) to pass on the object abstraction we
402      * get to the load_result callback and leave it to that one to do the
403      * work.  If that's libcrypto code, we know that it has much better
404      * possibilities to handle the EVP_PKEYs and X509s without the extra
405      * churn.
406      */
407
408     return data->object_cb(params, data->object_cbarg);
409 }
410
411 void file_load_cleanup(void *construct_data)
412 {
413     /* Nothing to do */
414 }
415
416 static int file_setup_decoders(struct file_ctx_st *ctx)
417 {
418     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
419     const OSSL_ALGORITHM *to_algo = NULL;
420     int ok = 0;
421
422     /* Setup for this session, so only if not already done */
423     if (ctx->_.file.decoderctx == NULL) {
424         if ((ctx->_.file.decoderctx = OSSL_DECODER_CTX_new()) == NULL) {
425             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
426             goto err;
427         }
428
429         /* Make sure the input type is set */
430         if (!OSSL_DECODER_CTX_set_input_type(ctx->_.file.decoderctx,
431                                              ctx->_.file.input_type)) {
432             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
433             goto err;
434         }
435
436         /*
437          * Where applicable, set the outermost structure name.
438          * The goal is to avoid the STORE object types that are
439          * potentially password protected but aren't interesting
440          * for this load.
441          */
442         switch (ctx->expected_type) {
443         case OSSL_STORE_INFO_CERT:
444             if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
445                                                       "Certificate")) {
446                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
447                 goto err;
448             }
449             break;
450         case OSSL_STORE_INFO_CRL:
451             if (!OSSL_DECODER_CTX_set_input_structure(ctx->_.file.decoderctx,
452                                                       "CertificateList")) {
453                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
454                 goto err;
455             }
456             break;
457         default:
458             break;
459         }
460
461         for (to_algo = ossl_any_to_obj_algorithm;
462              to_algo->algorithm_names != NULL;
463              to_algo++) {
464             OSSL_DECODER *to_obj = NULL;
465             OSSL_DECODER_INSTANCE *to_obj_inst = NULL;
466
467             /*
468              * Create the internal last resort decoder implementation
469              * together with a "decoder instance".
470              * The decoder doesn't need any identification or to be
471              * attached to any provider, since it's only used locally.
472              */
473             to_obj = ossl_decoder_from_algorithm(0, to_algo, NULL);
474             if (to_obj != NULL)
475                 to_obj_inst = ossl_decoder_instance_new(to_obj, ctx->provctx);
476             OSSL_DECODER_free(to_obj);
477             if (to_obj_inst == NULL)
478                 goto err;
479
480             if (!ossl_decoder_ctx_add_decoder_inst(ctx->_.file.decoderctx,
481                                                    to_obj_inst)) {
482                 ossl_decoder_instance_free(to_obj_inst);
483                 ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
484                 goto err;
485             }
486         }
487         /* Add on the usual extra decoders */
488         if (!OSSL_DECODER_CTX_add_extra(ctx->_.file.decoderctx,
489                                         libctx, ctx->_.file.propq)) {
490             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
491             goto err;
492         }
493
494         /*
495          * Then install our constructor hooks, which just passes decoded
496          * data to the load callback
497          */
498         if (!OSSL_DECODER_CTX_set_construct(ctx->_.file.decoderctx,
499                                             file_load_construct)
500             || !OSSL_DECODER_CTX_set_cleanup(ctx->_.file.decoderctx,
501                                              file_load_cleanup)) {
502             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
503             goto err;
504         }
505     }
506
507     ok = 1;
508  err:
509     return ok;
510 }
511
512 static int file_load_file(struct file_ctx_st *ctx,
513                           OSSL_CALLBACK *object_cb, void *object_cbarg,
514                           OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
515 {
516     struct file_load_data_st data;
517     int ret, err;
518
519     /* Setup the decoders (one time shot per session */
520
521     if (!file_setup_decoders(ctx))
522         return 0;
523
524     /* Setup for this object */
525
526     data.object_cb = object_cb;
527     data.object_cbarg = object_cbarg;
528     OSSL_DECODER_CTX_set_construct_data(ctx->_.file.decoderctx, &data);
529     OSSL_DECODER_CTX_set_passphrase_cb(ctx->_.file.decoderctx, pw_cb, pw_cbarg);
530
531     /* Launch */
532
533     ERR_set_mark();
534     ret = OSSL_DECODER_from_bio(ctx->_.file.decoderctx, ctx->_.file.file);
535     if (BIO_eof(ctx->_.file.file)
536         && ((err = ERR_peek_last_error()) != 0)
537         && ERR_GET_LIB(err) == ERR_LIB_OSSL_DECODER
538         && ERR_GET_REASON(err) == ERR_R_UNSUPPORTED)
539         ERR_pop_to_mark();
540     else
541         ERR_clear_last_mark();
542     return ret;
543 }
544
545 /*-
546  *  Loading a name object from a directory
547  *  --------------------------------------
548  */
549
550 static char *file_name_to_uri(struct file_ctx_st *ctx, const char *name)
551 {
552     char *data = NULL;
553
554     assert(name != NULL);
555     {
556         const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
557         long calculated_length = strlen(ctx->uri) + strlen(pathsep)
558             + strlen(name) + 1 /* \0 */;
559
560         data = OPENSSL_zalloc(calculated_length);
561         if (data == NULL) {
562             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
563             return NULL;
564         }
565
566         OPENSSL_strlcat(data, ctx->uri, calculated_length);
567         OPENSSL_strlcat(data, pathsep, calculated_length);
568         OPENSSL_strlcat(data, name, calculated_length);
569     }
570     return data;
571 }
572
573 static int file_name_check(struct file_ctx_st *ctx, const char *name)
574 {
575     const char *p = NULL;
576     size_t len = strlen(ctx->_.dir.search_name);
577
578     /* If there are no search criteria, all names are accepted */
579     if (ctx->_.dir.search_name[0] == '\0')
580         return 1;
581
582     /* If the expected type isn't supported, no name is accepted */
583     if (ctx->expected_type != 0
584         && ctx->expected_type != OSSL_STORE_INFO_CERT
585         && ctx->expected_type != OSSL_STORE_INFO_CRL)
586         return 0;
587
588     /*
589      * First, check the basename
590      */
591     if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
592         || name[len] != '.')
593         return 0;
594     p = &name[len + 1];
595
596     /*
597      * Then, if the expected type is a CRL, check that the extension starts
598      * with 'r'
599      */
600     if (*p == 'r') {
601         p++;
602         if (ctx->expected_type != 0
603             && ctx->expected_type != OSSL_STORE_INFO_CRL)
604             return 0;
605     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
606         return 0;
607     }
608
609     /*
610      * Last, check that the rest of the extension is a decimal number, at
611      * least one digit long.
612      */
613     if (!isdigit(*p))
614         return 0;
615     while (isdigit(*p))
616         p++;
617
618 #ifdef __VMS
619     /*
620      * One extra step here, check for a possible generation number.
621      */
622     if (*p == ';')
623         for (p++; *p != '\0'; p++)
624             if (!ossl_isdigit(*p))
625                 break;
626 #endif
627
628     /*
629      * If we've reached the end of the string at this point, we've successfully
630      * found a fitting file name.
631      */
632     return *p == '\0';
633 }
634
635 static int file_load_dir_entry(struct file_ctx_st *ctx,
636                                OSSL_CALLBACK *object_cb, void *object_cbarg,
637                                OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
638 {
639     /* Prepare as much as possible in advance */
640     static const int object_type = OSSL_OBJECT_NAME;
641     OSSL_PARAM object[] = {
642         OSSL_PARAM_int(OSSL_OBJECT_PARAM_TYPE, (int *)&object_type),
643         OSSL_PARAM_utf8_string(OSSL_OBJECT_PARAM_DATA, NULL, 0),
644         OSSL_PARAM_END
645     };
646     char *newname = NULL;
647     int ok;
648
649     /* Loop until we get an error or until we have a suitable name */
650     do {
651         if (ctx->_.dir.last_entry == NULL) {
652             if (!ctx->_.dir.end_reached) {
653                 assert(ctx->_.dir.last_errno != 0);
654                 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
655             }
656             /* file_eof() will tell if EOF was reached */
657             return 0;
658         }
659
660         /* flag acceptable names */
661         if (ctx->_.dir.last_entry[0] != '.'
662             && file_name_check(ctx, ctx->_.dir.last_entry)) {
663
664             /* If we can't allocate the new name, we fail */
665             if ((newname =
666                  file_name_to_uri(ctx, ctx->_.dir.last_entry)) == NULL)
667                 return 0;
668         }
669
670         /*
671          * On the first call (with a NULL context), OPENSSL_DIR_read()
672          * cares about the second argument.  On the following calls, it
673          * only cares that it isn't NULL.  Therefore, we can safely give
674          * it our URI here.
675          */
676         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
677         ctx->_.dir.last_errno = errno;
678         if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
679             ctx->_.dir.end_reached = 1;
680     } while (newname == NULL);
681
682     object[1].data = newname;
683     object[1].data_size = strlen(newname);
684     ok = object_cb(object, object_cbarg);
685     OPENSSL_free(newname);
686     return ok;
687 }
688
689 /*-
690  *  Loading, local dispatcher
691  *  -------------------------
692  */
693
694 static int file_load(void *loaderctx,
695                      OSSL_CALLBACK *object_cb, void *object_cbarg,
696                      OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
697 {
698     struct file_ctx_st *ctx = loaderctx;
699
700     switch (ctx->type) {
701     case IS_FILE:
702         return file_load_file(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
703     case IS_DIR:
704         return
705             file_load_dir_entry(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
706     default:
707         break;
708     }
709
710     /* ctx->type has an unexpected value */
711     assert(0);
712     return 0;
713 }
714
715 /*-
716  *  Eof detection and closing
717  *  -------------------------
718  */
719
720 static int file_eof(void *loaderctx)
721 {
722     struct file_ctx_st *ctx = loaderctx;
723
724     switch (ctx->type) {
725     case IS_DIR:
726         return ctx->_.dir.end_reached;
727     case IS_FILE:
728         /*
729          * BIO_pending() checks any filter BIO.
730          * BIO_eof() checks the source BIO.
731          */
732         return !BIO_pending(ctx->_.file.file)
733             && BIO_eof(ctx->_.file.file);
734     }
735
736     /* ctx->type has an unexpected value */
737     assert(0);
738     return 1;
739 }
740
741 static int file_close_dir(struct file_ctx_st *ctx)
742 {
743     if (ctx->_.dir.ctx != NULL)
744         OPENSSL_DIR_end(&ctx->_.dir.ctx);
745     free_file_ctx(ctx);
746     return 1;
747 }
748
749 static int file_close_stream(struct file_ctx_st *ctx)
750 {
751     /*
752      * This frees either the provider BIO filter (for file_attach()) OR
753      * the allocated file BIO (for file_open()).
754      */
755     BIO_free(ctx->_.file.file);
756     ctx->_.file.file = NULL;
757
758     free_file_ctx(ctx);
759     return 1;
760 }
761
762 static int file_close(void *loaderctx)
763 {
764     struct file_ctx_st *ctx = loaderctx;
765
766     switch (ctx->type) {
767     case IS_DIR:
768         return file_close_dir(ctx);
769     case IS_FILE:
770         return file_close_stream(ctx);
771     }
772
773     /* ctx->type has an unexpected value */
774     assert(0);
775     return 1;
776 }
777
778 const OSSL_DISPATCH ossl_file_store_functions[] = {
779     { OSSL_FUNC_STORE_OPEN, (void (*)(void))file_open },
780     { OSSL_FUNC_STORE_ATTACH, (void (*)(void))file_attach },
781     { OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS,
782       (void (*)(void))file_settable_ctx_params },
783     { OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))file_set_ctx_params },
784     { OSSL_FUNC_STORE_LOAD, (void (*)(void))file_load },
785     { OSSL_FUNC_STORE_EOF, (void (*)(void))file_eof },
786     { OSSL_FUNC_STORE_CLOSE, (void (*)(void))file_close },
787     { 0, NULL },
788 };