store: Avoid spurious error from decoding at EOF
[openssl.git] / providers / implementations / storemgmt / file_store.c
1 /*
2  * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "e_os.h"                /* To get strncasecmp() on Windows */
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         goto err;
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;
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 (strncasecmp(uri, "file:", 5) == 0) {
222         const char *p = &uri[5];
223
224         if (strncmp(&uri[5], "//", 2) == 0) {
225             path_data_n--;           /* Invalidate using the full URI */
226             if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
227                 p = &uri[16];
228             } else if (uri[7] == '/') {
229                 p = &uri[7];
230             } else {
231                 ERR_clear_last_mark();
232                 ERR_raise(ERR_LIB_PROV, PROV_R_URI_AUTHORITY_UNSUPPORTED);
233                 return NULL;
234             }
235         }
236
237         path_data[path_data_n].check_absolute = 1;
238 #ifdef _WIN32
239         /* Windows file: URIs with a drive letter start with a / */
240         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
241             char c = tolower(p[1]);
242
243             if (c >= 'a' && c <= 'z') {
244                 p++;
245                 /* We know it's absolute, so no need to check */
246                 path_data[path_data_n].check_absolute = 0;
247             }
248         }
249 #endif
250         path_data[path_data_n++].path = p;
251     }
252
253
254     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
255         /*
256          * If the scheme "file" was an explicit part of the URI, the path must
257          * be absolute.  So says RFC 8089
258          */
259         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
260             ERR_clear_last_mark();
261             ERR_raise_data(ERR_LIB_PROV, PROV_R_PATH_MUST_BE_ABSOLUTE,
262                            "Given path=%s", path_data[i].path);
263             return NULL;
264         }
265
266         if (stat(path_data[i].path, &st) < 0) {
267             ERR_raise_data(ERR_LIB_SYS, errno,
268                            "calling stat(%s)",
269                            path_data[i].path);
270         } else {
271             path = path_data[i].path;
272         }
273     }
274     if (path == NULL) {
275         ERR_clear_last_mark();
276         return NULL;
277     }
278
279     /* Successfully found a working path, clear possible collected errors */
280     ERR_pop_to_mark();
281
282     if (S_ISDIR(st.st_mode))
283         ctx = file_open_dir(path, uri, provctx);
284     else if ((bio = BIO_new_file(path, "rb")) == NULL
285              || (ctx = file_open_stream(bio, uri, provctx)) == NULL)
286         BIO_free_all(bio);
287
288     return ctx;
289 }
290
291 void *file_attach(void *provctx, OSSL_CORE_BIO *cin)
292 {
293     struct file_ctx_st *ctx;
294     BIO *new_bio = ossl_bio_new_from_core_bio(provctx, cin);
295
296     if (new_bio == NULL)
297         return NULL;
298
299     ctx = file_open_stream(new_bio, NULL, provctx);
300     if (ctx == NULL)
301         BIO_free(new_bio);
302     return ctx;
303 }
304
305 /*-
306  *  Setting parameters
307  *  ------------------
308  */
309
310 static const OSSL_PARAM *file_settable_ctx_params(void *provctx)
311 {
312     static const OSSL_PARAM known_settable_ctx_params[] = {
313         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_PROPERTIES, NULL, 0),
314         OSSL_PARAM_int(OSSL_STORE_PARAM_EXPECT, NULL),
315         OSSL_PARAM_octet_string(OSSL_STORE_PARAM_SUBJECT, NULL, 0),
316         OSSL_PARAM_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE, NULL, 0),
317         OSSL_PARAM_END
318     };
319     return known_settable_ctx_params;
320 }
321
322 static int file_set_ctx_params(void *loaderctx, const OSSL_PARAM params[])
323 {
324     struct file_ctx_st *ctx = loaderctx;
325     const OSSL_PARAM *p;
326
327     if (params == NULL)
328         return 1;
329
330     if (ctx->type != IS_DIR) {
331         /* these parameters are ignored for directories */
332         p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_PROPERTIES);
333         if (p != NULL) {
334             OPENSSL_free(ctx->_.file.propq);
335             ctx->_.file.propq = NULL;
336             if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.propq, 0))
337                 return 0;
338         }
339         p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_INPUT_TYPE);
340         if (p != NULL) {
341             OPENSSL_free(ctx->_.file.input_type);
342             ctx->_.file.input_type = NULL;
343             if (!OSSL_PARAM_get_utf8_string(p, &ctx->_.file.input_type, 0))
344                 return 0;
345         }
346     }
347     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_EXPECT);
348     if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->expected_type))
349         return 0;
350     p = OSSL_PARAM_locate_const(params, OSSL_STORE_PARAM_SUBJECT);
351     if (p != NULL) {
352         const unsigned char *der = NULL;
353         size_t der_len = 0;
354         X509_NAME *x509_name;
355         unsigned long hash;
356         int ok;
357
358         if (ctx->type != IS_DIR) {
359             ERR_raise(ERR_LIB_PROV,
360                       PROV_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
361             return 0;
362         }
363
364         if (!OSSL_PARAM_get_octet_string_ptr(p, (const void **)&der, &der_len)
365             || (x509_name = d2i_X509_NAME(NULL, &der, der_len)) == NULL)
366             return 0;
367         hash = X509_NAME_hash_ex(x509_name,
368                                  ossl_prov_ctx_get0_libctx(ctx->provctx), NULL,
369                                  &ok);
370         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
371                      "%08lx", hash);
372         X509_NAME_free(x509_name);
373         if (ok == 0)
374             return 0;
375     }
376     return 1;
377 }
378
379 /*-
380  *  Loading an object from a stream
381  *  -------------------------------
382  */
383
384 struct file_load_data_st {
385     OSSL_CALLBACK *object_cb;
386     void *object_cbarg;
387 };
388
389 static int file_load_construct(OSSL_DECODER_INSTANCE *decoder_inst,
390                                const OSSL_PARAM *params, void *construct_data)
391 {
392     struct file_load_data_st *data = construct_data;
393
394     /*
395      * At some point, we may find it justifiable to recognise PKCS#12 and
396      * handle it specially here, making |file_load()| return pass its
397      * contents one piece at ta time, like |e_loader_attic.c| does.
398      *
399      * However, that currently means parsing them out, which converts the
400      * DER encoded PKCS#12 into a bunch of EVP_PKEYs and X509s, just to
401      * have to re-encode them into DER to create an object abstraction for
402      * each of them.
403      * It's much simpler (less churn) to pass on the object abstraction we
404      * get to the load_result callback and leave it to that one to do the
405      * work.  If that's libcrypto code, we know that it has much better
406      * possibilities to handle the EVP_PKEYs and X509s without the extra
407      * churn.
408      */
409
410     return data->object_cb(params, data->object_cbarg);
411 }
412
413 void file_load_cleanup(void *construct_data)
414 {
415     /* Nothing to do */
416 }
417
418 static int file_setup_decoders(struct file_ctx_st *ctx)
419 {
420     EVP_PKEY *dummy; /* for ossl_decoder_ctx_setup_for_pkey() */
421     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
422     OSSL_DECODER *to_obj = NULL; /* Last resort decoder */
423     OSSL_DECODER_INSTANCE *to_obj_inst = NULL;
424     OSSL_DECODER_CLEANUP *old_cleanup = NULL;
425     void *old_construct_data = NULL;
426     int ok = 0, expect_evp_pkey = 0;
427
428     /* Setup for this session, so only if not already done */
429     if (ctx->_.file.decoderctx == NULL) {
430         if ((ctx->_.file.decoderctx = OSSL_DECODER_CTX_new()) == NULL) {
431             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
432             goto err;
433         }
434
435         expect_evp_pkey = (ctx->expected_type == 0
436                            || ctx->expected_type == OSSL_STORE_INFO_PARAMS
437                            || ctx->expected_type == OSSL_STORE_INFO_PUBKEY
438                            || ctx->expected_type == OSSL_STORE_INFO_PKEY);
439
440         /* Make sure the input type is set */
441         if (!OSSL_DECODER_CTX_set_input_type(ctx->_.file.decoderctx,
442                                              ctx->_.file.input_type)) {
443             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
444             goto err;
445         }
446
447         /*
448          * Create the internal last resort decoder implementation together
449          * with a "decoder instance".
450          * The decoder doesn't need any identification or to be attached to
451          * any provider, since it's only used locally.
452          */
453         to_obj = ossl_decoder_from_algorithm(0, &ossl_der_to_obj_algorithm,
454                                              NULL);
455         if (to_obj == NULL)
456             goto err;
457         to_obj_inst = ossl_decoder_instance_new(to_obj, ctx->provctx);
458         if (to_obj_inst == NULL)
459             goto err;
460
461         if (!ossl_decoder_ctx_add_decoder_inst(ctx->_.file.decoderctx,
462                                                to_obj_inst)) {
463             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
464             goto err;
465         }
466
467         /*
468          * OSSL_DECODER_INSTANCE shouldn't be freed from this point on.
469          * That's going to happen whenever the OSSL_DECODER_CTX is freed.
470          */
471         to_obj_inst = NULL;
472
473         /*
474          * Add on the usual decoder context for keys, with a dummy object.
475          * Since we're setting up our own constructor, we don't need to care
476          * more than that...
477          */
478         if ((expect_evp_pkey
479              && !ossl_decoder_ctx_setup_for_pkey(ctx->_.file.decoderctx,
480                                                  &dummy, NULL,
481                                                  libctx, ctx->_.file.propq))
482             || !OSSL_DECODER_CTX_add_extra(ctx->_.file.decoderctx,
483                                            libctx, ctx->_.file.propq)) {
484             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
485             goto err;
486         }
487
488         /*
489          * Then we throw away the installed finalizer data, and install our
490          * own instead.
491          */
492         old_cleanup = OSSL_DECODER_CTX_get_cleanup(ctx->_.file.decoderctx);
493         old_construct_data =
494             OSSL_DECODER_CTX_get_construct_data(ctx->_.file.decoderctx);
495         if (old_cleanup != NULL)
496             old_cleanup(old_construct_data);
497
498         /*
499          * Set the hooks.
500          */
501         if (!OSSL_DECODER_CTX_set_construct(ctx->_.file.decoderctx,
502                                             file_load_construct)
503             || !OSSL_DECODER_CTX_set_cleanup(ctx->_.file.decoderctx,
504                                              file_load_cleanup)) {
505             ERR_raise(ERR_LIB_PROV, ERR_R_OSSL_DECODER_LIB);
506             goto err;
507         }
508     }
509
510     ok = 1;
511  err:
512     OSSL_DECODER_free(to_obj);
513     return ok;
514 }
515
516 static int file_load_file(struct file_ctx_st *ctx,
517                           OSSL_CALLBACK *object_cb, void *object_cbarg,
518                           OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
519 {
520     struct file_load_data_st data;
521     int ret, err;
522
523     /* Setup the decoders (one time shot per session */
524
525     if (!file_setup_decoders(ctx))
526         return 0;
527
528     /* Setup for this object */
529
530     data.object_cb = object_cb;
531     data.object_cbarg = object_cbarg;
532     OSSL_DECODER_CTX_set_construct_data(ctx->_.file.decoderctx, &data);
533     OSSL_DECODER_CTX_set_passphrase_cb(ctx->_.file.decoderctx, pw_cb, pw_cbarg);
534
535     /* Launch */
536
537     ERR_set_mark();
538     ret = OSSL_DECODER_from_bio(ctx->_.file.decoderctx, ctx->_.file.file);
539     if (BIO_eof(ctx->_.file.file)
540         && ((err = ERR_peek_last_error()) != 0)
541         && ERR_GET_LIB(err) == ERR_LIB_OSSL_DECODER
542         && ERR_GET_REASON(err) == ERR_R_UNSUPPORTED)
543         ERR_pop_to_mark();
544     else
545         ERR_clear_last_mark();
546     return ret;
547 }
548
549 /*-
550  *  Loading a name object from a directory
551  *  --------------------------------------
552  */
553
554 static char *file_name_to_uri(struct file_ctx_st *ctx, const char *name)
555 {
556     char *data = NULL;
557
558     assert(name != NULL);
559     {
560         const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
561         long calculated_length = strlen(ctx->uri) + strlen(pathsep)
562             + strlen(name) + 1 /* \0 */;
563
564         data = OPENSSL_zalloc(calculated_length);
565         if (data == NULL) {
566             ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
567             return NULL;
568         }
569
570         OPENSSL_strlcat(data, ctx->uri, calculated_length);
571         OPENSSL_strlcat(data, pathsep, calculated_length);
572         OPENSSL_strlcat(data, name, calculated_length);
573     }
574     return data;
575 }
576
577 static int file_name_check(struct file_ctx_st *ctx, const char *name)
578 {
579     const char *p = NULL;
580
581     /* If there are no search criteria, all names are accepted */
582     if (ctx->_.dir.search_name[0] == '\0')
583         return 1;
584
585     /* If the expected type isn't supported, no name is accepted */
586     if (ctx->expected_type != 0
587         && ctx->expected_type != OSSL_STORE_INFO_CERT
588         && ctx->expected_type != OSSL_STORE_INFO_CRL)
589         return 0;
590
591     /*
592      * First, check the basename
593      */
594     if (strncasecmp(name, ctx->_.dir.search_name,
595                     sizeof(ctx->_.dir.search_name) - 1) != 0
596         || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
597         return 0;
598     p = &name[sizeof(ctx->_.dir.search_name)];
599
600     /*
601      * Then, if the expected type is a CRL, check that the extension starts
602      * with 'r'
603      */
604     if (*p == 'r') {
605         p++;
606         if (ctx->expected_type != 0
607             && ctx->expected_type != OSSL_STORE_INFO_CRL)
608             return 0;
609     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
610         return 0;
611     }
612
613     /*
614      * Last, check that the rest of the extension is a decimal number, at
615      * least one digit long.
616      */
617     if (!isdigit(*p))
618         return 0;
619     while (isdigit(*p))
620         p++;
621
622 #ifdef __VMS
623     /*
624      * One extra step here, check for a possible generation number.
625      */
626     if (*p == ';')
627         for (p++; *p != '\0'; p++)
628             if (!ossl_isdigit(*p))
629                 break;
630 #endif
631
632     /*
633      * If we've reached the end of the string at this point, we've successfully
634      * found a fitting file name.
635      */
636     return *p == '\0';
637 }
638
639 static int file_load_dir_entry(struct file_ctx_st *ctx,
640                                OSSL_CALLBACK *object_cb, void *object_cbarg,
641                                OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
642 {
643     /* Prepare as much as possible in advance */
644     static const int object_type = OSSL_OBJECT_NAME;
645     OSSL_PARAM object[] = {
646         OSSL_PARAM_int(OSSL_OBJECT_PARAM_TYPE, (int *)&object_type),
647         OSSL_PARAM_utf8_string(OSSL_OBJECT_PARAM_DATA, NULL, 0),
648         OSSL_PARAM_END
649     };
650     char *newname = NULL;
651     int ok;
652
653     /* Loop until we get an error or until we have a suitable name */
654     do {
655         if (ctx->_.dir.last_entry == NULL) {
656             if (!ctx->_.dir.end_reached) {
657                 assert(ctx->_.dir.last_errno != 0);
658                 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
659             }
660             /* file_eof() will tell if EOF was reached */
661             return 0;
662         }
663
664         /* flag acceptable names */
665         if (ctx->_.dir.last_entry[0] != '.'
666             && file_name_check(ctx, ctx->_.dir.last_entry)) {
667
668             /* If we can't allocate the new name, we fail */
669             if ((newname =
670                  file_name_to_uri(ctx, ctx->_.dir.last_entry)) == NULL)
671                 return 0;
672         }
673
674         /*
675          * On the first call (with a NULL context), OPENSSL_DIR_read()
676          * cares about the second argument.  On the following calls, it
677          * only cares that it isn't NULL.  Therefore, we can safely give
678          * it our URI here.
679          */
680         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
681         ctx->_.dir.last_errno = errno;
682         if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
683             ctx->_.dir.end_reached = 1;
684     } while (newname == NULL);
685
686     object[1].data = newname;
687     object[1].data_size = strlen(newname);
688     ok = object_cb(object, object_cbarg);
689     OPENSSL_free(newname);
690     return ok;
691 }
692
693 /*-
694  *  Loading, local dispatcher
695  *  -------------------------
696  */
697
698 static int file_load(void *loaderctx,
699                      OSSL_CALLBACK *object_cb, void *object_cbarg,
700                      OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
701 {
702     struct file_ctx_st *ctx = loaderctx;
703
704     switch (ctx->type) {
705     case IS_FILE:
706         return file_load_file(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
707     case IS_DIR:
708         return
709             file_load_dir_entry(ctx, object_cb, object_cbarg, pw_cb, pw_cbarg);
710     default:
711         break;
712     }
713
714     /* ctx->type has an unexpected value */
715     assert(0);
716     return 0;
717 }
718
719 /*-
720  *  Eof detection and closing
721  *  -------------------------
722  */
723
724 static int file_eof(void *loaderctx)
725 {
726     struct file_ctx_st *ctx = loaderctx;
727
728     switch (ctx->type) {
729     case IS_DIR:
730         return ctx->_.dir.end_reached;
731     case IS_FILE:
732         /*
733          * BIO_pending() checks any filter BIO.
734          * BIO_eof() checks the source BIO.
735          */
736         return !BIO_pending(ctx->_.file.file)
737             && BIO_eof(ctx->_.file.file);
738     }
739
740     /* ctx->type has an unexpected value */
741     assert(0);
742     return 1;
743 }
744
745 static int file_close_dir(struct file_ctx_st *ctx)
746 {
747     if (ctx->_.dir.ctx != NULL)
748         OPENSSL_DIR_end(&ctx->_.dir.ctx);
749     free_file_ctx(ctx);
750     return 1;
751 }
752
753 static int file_close_stream(struct file_ctx_st *ctx)
754 {
755     /*
756      * This frees either the provider BIO filter (for file_attach()) OR
757      * the allocated file BIO (for file_open()).
758      */
759     BIO_free(ctx->_.file.file);
760     ctx->_.file.file = NULL;
761
762     free_file_ctx(ctx);
763     return 1;
764 }
765
766 static int file_close(void *loaderctx)
767 {
768     struct file_ctx_st *ctx = loaderctx;
769
770     switch (ctx->type) {
771     case IS_DIR:
772         return file_close_dir(ctx);
773     case IS_FILE:
774         return file_close_stream(ctx);
775     }
776
777     /* ctx->type has an unexpected value */
778     assert(0);
779     return 1;
780 }
781
782 const OSSL_DISPATCH ossl_file_store_functions[] = {
783     { OSSL_FUNC_STORE_OPEN, (void (*)(void))file_open },
784     { OSSL_FUNC_STORE_ATTACH, (void (*)(void))file_attach },
785     { OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS,
786       (void (*)(void))file_settable_ctx_params },
787     { OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))file_set_ctx_params },
788     { OSSL_FUNC_STORE_LOAD, (void (*)(void))file_load },
789     { OSSL_FUNC_STORE_EOF, (void (*)(void))file_eof },
790     { OSSL_FUNC_STORE_CLOSE, (void (*)(void))file_close },
791     { 0, NULL },
792 };