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