DECODER: use property definitions instead of getting implementation parameters
[openssl.git] / crypto / encode_decode / decoder_lib.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 <openssl/core_names.h>
11 #include <openssl/bio.h>
12 #include <openssl/params.h>
13 #include <openssl/provider.h>
14 #include <openssl/evperr.h>
15 #include <openssl/ecerr.h>
16 #include <openssl/pkcs12err.h>
17 #include <openssl/x509err.h>
18 #include <openssl/trace.h>
19 #include "internal/bio.h"
20 #include "internal/provider.h"
21 #include "crypto/decoder.h"
22 #include "encoder_local.h"
23 #include "e_os.h"
24
25 struct decoder_process_data_st {
26     OSSL_DECODER_CTX *ctx;
27
28     /* Current BIO */
29     BIO *bio;
30
31     /* Index of the current decoder instance to be processed */
32     size_t current_decoder_inst_index;
33     /* For tracing, count recursion level */
34     size_t recursion;
35
36     /*-
37      * Flags
38      */
39     unsigned int flag_next_level_called : 1;
40     unsigned int flag_construct_called : 1;
41 };
42
43 static int decoder_process(const OSSL_PARAM params[], void *arg);
44
45 int OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in)
46 {
47     struct decoder_process_data_st data;
48     int ok = 0;
49     BIO *new_bio = NULL;
50
51     if (OSSL_DECODER_CTX_get_num_decoders(ctx) == 0) {
52         ERR_raise_data(ERR_LIB_OSSL_DECODER, OSSL_DECODER_R_DECODER_NOT_FOUND,
53                        "No decoders were found. For standard decoders you need "
54                        "at least one of the default or base providers "
55                        "available. Did you forget to load them?");
56         return 0;
57     }
58
59     if (BIO_tell(in) < 0) {
60         new_bio = BIO_new(BIO_f_readbuffer());
61         if (new_bio == NULL)
62             return 0;
63         in = BIO_push(new_bio, in);
64     }
65     memset(&data, 0, sizeof(data));
66     data.ctx = ctx;
67     data.bio = in;
68
69     /* Enable passphrase caching */
70     (void)ossl_pw_enable_passphrase_caching(&ctx->pwdata);
71
72     ok = decoder_process(NULL, &data);
73
74     if (!data.flag_construct_called) {
75         const char *spaces
76             = ctx->start_input_type != NULL && ctx->input_structure != NULL
77             ? " " : "";
78         const char *input_type_label
79             = ctx->start_input_type != NULL ? "Input type: " : "";
80         const char *input_structure_label
81             = ctx->input_structure != NULL ? "Input structure: " : "";
82         const char *comma
83             = ctx->start_input_type != NULL && ctx->input_structure != NULL
84             ? ", " : "";
85         const char *input_type
86             = ctx->start_input_type != NULL ? ctx->start_input_type : "";
87         const char *input_structure
88             = ctx->input_structure != NULL ? ctx->input_structure : "";
89
90         if (BIO_eof(in) == 0 || ERR_peek_error() == 0)
91             /* Prevent spurious decoding error */
92             ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_UNSUPPORTED,
93                            "No supported data to decode. %s%s%s%s%s%s",
94                            spaces, input_type_label, input_type, comma,
95                            input_structure_label, input_structure);
96         ok = 0;
97     }
98
99     /* Clear any internally cached passphrase */
100     (void)ossl_pw_clear_passphrase_cache(&ctx->pwdata);
101
102     if (new_bio != NULL) {
103         BIO_pop(new_bio);
104         BIO_free(new_bio);
105     }
106     return ok;
107 }
108
109 #ifndef OPENSSL_NO_STDIO
110 static BIO *bio_from_file(FILE *fp)
111 {
112     BIO *b;
113
114     if ((b = BIO_new(BIO_s_file())) == NULL) {
115         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB);
116         return NULL;
117     }
118     BIO_set_fp(b, fp, BIO_NOCLOSE);
119     return b;
120 }
121
122 int OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *fp)
123 {
124     BIO *b = bio_from_file(fp);
125     int ret = 0;
126
127     if (b != NULL)
128         ret = OSSL_DECODER_from_bio(ctx, b);
129
130     BIO_free(b);
131     return ret;
132 }
133 #endif
134
135 int OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata,
136                            size_t *pdata_len)
137 {
138     BIO *membio;
139     int ret = 0;
140
141     if (pdata == NULL || *pdata == NULL || pdata_len == NULL) {
142         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
143         return 0;
144     }
145
146     membio = BIO_new_mem_buf(*pdata, (int)*pdata_len);
147     if (OSSL_DECODER_from_bio(ctx, membio)) {
148         *pdata_len = (size_t)BIO_get_mem_data(membio, pdata);
149         ret = 1;
150     }
151     BIO_free(membio);
152
153     return ret;
154 }
155
156 int OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection)
157 {
158     if (!ossl_assert(ctx != NULL)) {
159         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
160         return 0;
161     }
162
163     /*
164      * 0 is a valid selection, and means that the caller leaves
165      * it to code to discover what the selection is.
166      */
167     ctx->selection = selection;
168     return 1;
169 }
170
171 int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx,
172                                     const char *input_type)
173 {
174     if (!ossl_assert(ctx != NULL)) {
175         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
176         return 0;
177     }
178
179     /*
180      * NULL is a valid starting input type, and means that the caller leaves
181      * it to code to discover what the starting input type is.
182      */
183     ctx->start_input_type = input_type;
184     return 1;
185 }
186
187 int OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx,
188                                          const char *input_structure)
189 {
190     if (!ossl_assert(ctx != NULL)) {
191         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
192         return 0;
193     }
194
195     /*
196      * NULL is a valid starting input structure, and means that the caller
197      * leaves it to code to discover what the starting input structure is.
198      */
199     ctx->input_structure = input_structure;
200     return 1;
201 }
202
203 OSSL_DECODER_INSTANCE *ossl_decoder_instance_new(OSSL_DECODER *decoder,
204                                                  void *decoderctx)
205 {
206     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
207     const OSSL_PROVIDER *prov;
208     OSSL_LIB_CTX *libctx;
209     const OSSL_PROPERTY_LIST *props;
210     const OSSL_PROPERTY_DEFINITION *prop;
211
212     if (!ossl_assert(decoder != NULL)) {
213         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
214         return 0;
215     }
216
217     if ((decoder_inst = OPENSSL_zalloc(sizeof(*decoder_inst))) == NULL) {
218         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
219         return 0;
220     }
221     if (!OSSL_DECODER_up_ref(decoder)) {
222         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_INTERNAL_ERROR);
223         goto err;
224     }
225
226     prov = OSSL_DECODER_get0_provider(decoder);
227     libctx = ossl_provider_libctx(prov);
228     props = ossl_decoder_parsed_properties(decoder);
229     if (props == NULL) {
230         ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION,
231                        "there are no property definitions with decoder %s",
232                        OSSL_DECODER_get0_name(decoder));
233         goto err;
234     }
235
236     /* The "input" property is mandatory */
237     prop = ossl_property_find_property(props, libctx, "input");
238     decoder_inst->input_type = ossl_property_get_string_value(libctx, prop);
239     if (decoder_inst->input_type == NULL) {
240         ERR_raise_data(ERR_LIB_OSSL_DECODER, ERR_R_INVALID_PROPERTY_DEFINITION,
241                        "the mandatory 'input' property is missing "
242                        "for decoder %s (properties: %s)",
243                        OSSL_DECODER_get0_name(decoder),
244                        OSSL_DECODER_get0_properties(decoder));
245         goto err;
246     }
247
248     /* The "structure" property is optional */
249     prop = ossl_property_find_property(props, libctx, "structure");
250     if (prop != NULL) {
251         decoder_inst->input_structure
252             = ossl_property_get_string_value(libctx, prop);
253     }
254
255     decoder_inst->decoder = decoder;
256     decoder_inst->decoderctx = decoderctx;
257     return decoder_inst;
258  err:
259     ossl_decoder_instance_free(decoder_inst);
260     return NULL;
261 }
262
263 void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst)
264 {
265     if (decoder_inst != NULL) {
266         if (decoder_inst->decoder != NULL)
267             decoder_inst->decoder->freectx(decoder_inst->decoderctx);
268         decoder_inst->decoderctx = NULL;
269         OSSL_DECODER_free(decoder_inst->decoder);
270         decoder_inst->decoder = NULL;
271         OPENSSL_free(decoder_inst);
272     }
273 }
274
275 int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx,
276                                       OSSL_DECODER_INSTANCE *di)
277 {
278     int ok;
279
280     if (ctx->decoder_insts == NULL
281         && (ctx->decoder_insts =
282             sk_OSSL_DECODER_INSTANCE_new_null()) == NULL) {
283         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
284         return 0;
285     }
286
287     ok = (sk_OSSL_DECODER_INSTANCE_push(ctx->decoder_insts, di) > 0);
288     if (ok) {
289         OSSL_TRACE_BEGIN(DECODER) {
290             BIO_printf(trc_out,
291                        "(ctx %p) Added decoder instance %p (decoder %p) with:\n",
292                        (void *)ctx, (void *)di, (void *)di->decoder);
293             BIO_printf(trc_out,
294                        "    input type: %s, input structure: %s\n",
295                        di->input_type, di->input_structure);
296         } OSSL_TRACE_END(DECODER);
297     }
298     return ok;
299 }
300
301 int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder)
302 {
303     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
304     const OSSL_PROVIDER *prov = NULL;
305     void *decoderctx = NULL;
306     void *provctx = NULL;
307
308     if (!ossl_assert(ctx != NULL) || !ossl_assert(decoder != NULL)) {
309         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
310         return 0;
311     }
312
313     prov = OSSL_DECODER_get0_provider(decoder);
314     provctx = OSSL_PROVIDER_get0_provider_ctx(prov);
315
316     if ((decoderctx = decoder->newctx(provctx)) == NULL
317         || (decoder_inst =
318             ossl_decoder_instance_new(decoder, decoderctx)) == NULL)
319         goto err;
320     /* Avoid double free of decoderctx on further errors */
321     decoderctx = NULL;
322
323     if (!ossl_decoder_ctx_add_decoder_inst(ctx, decoder_inst))
324         goto err;
325
326     return 1;
327  err:
328     ossl_decoder_instance_free(decoder_inst);
329     if (decoderctx != NULL)
330         decoder->freectx(decoderctx);
331     return 0;
332 }
333
334 int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx,
335                                OSSL_LIB_CTX *libctx, const char *propq)
336 {
337     /*
338      * This function goes through existing decoder methods in
339      * |ctx->decoder_insts|, and tries to fetch new decoders that produce
340      * what the existing ones want as input, and push those newly fetched
341      * decoders on top of the same stack.
342      * Then it does the same again, but looping over the newly fetched
343      * decoders, until there are no more decoders to be fetched, or
344      * when we have done this 10 times.
345      *
346      * we do this with sliding windows on the stack by keeping track of indexes
347      * and of the end.
348      *
349      * +----------------+
350      * |   DER to RSA   | <--- w_prev_start
351      * +----------------+
352      * |   DER to DSA   |
353      * +----------------+
354      * |   DER to DH    |
355      * +----------------+
356      * |   PEM to DER   | <--- w_prev_end, w_new_start
357      * +----------------+
358      *                    <--- w_new_end
359      */
360     size_t w_prev_start, w_prev_end; /* "previous" decoders */
361     size_t w_new_start, w_new_end;   /* "new" decoders */
362     size_t count = 0; /* Calculates how many were added in each iteration */
363     size_t depth = 0; /* Counts the number of iterations */
364
365     if (!ossl_assert(ctx != NULL)) {
366         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
367         return 0;
368     }
369
370     /*
371      * If there is no stack of OSSL_DECODER_INSTANCE, we have nothing
372      * more to add.  That's fine.
373      */
374     if (ctx->decoder_insts == NULL)
375         return 1;
376
377     w_prev_start = 0;
378     w_prev_end = sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts);
379     do {
380         size_t i;
381
382         w_new_start = w_new_end = w_prev_end;
383
384         for (i = w_prev_start; i < w_prev_end; i++) {
385             OSSL_DECODER_INSTANCE *decoder_inst =
386                 sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i);
387             const char *input_type =
388                 OSSL_DECODER_INSTANCE_get_input_type(decoder_inst);
389             OSSL_DECODER *decoder = NULL;
390
391             /*
392              * If the caller has specified what the initial input should be,
393              * and the decoder implementation we're looking at has that
394              * input type, there's no point adding on more implementations
395              * on top of this one, so we don't.
396              */
397             if (ctx->start_input_type != NULL
398                 && strcasecmp(ctx->start_input_type, input_type) == 0)
399                 continue;
400
401             ERR_set_mark();
402             decoder = OSSL_DECODER_fetch(libctx, input_type, propq);
403             ERR_pop_to_mark();
404
405             if (decoder != NULL) {
406                 size_t j;
407
408                 /*
409                  * Check that we don't already have this decoder in our
410                  * stack We only need to check among the newly added ones.
411                  */
412                 for (j = w_new_start; j < w_new_end; j++) {
413                     OSSL_DECODER_INSTANCE *check_inst =
414                         sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, j);
415
416                     if (decoder == check_inst->decoder) {
417                         /* We found it, so drop the new fetch */
418                         OSSL_DECODER_free(decoder);
419                         decoder = NULL;
420                         break;
421                     }
422                 }
423             }
424
425             if (decoder == NULL)
426                 continue;
427
428             /*
429              * Apart from keeping w_new_end up to date, We don't care about
430              * errors here.  If it doesn't collect, then it doesn't...
431              */
432             if (OSSL_DECODER_CTX_add_decoder(ctx, decoder)) /* ref++ */
433                 w_new_end++;
434             OSSL_DECODER_free(decoder); /* ref-- */
435         }
436         /* How many were added in this iteration */
437         count = w_new_end - w_new_start;
438
439         /* Slide the "previous decoder" windows */
440         w_prev_start = w_new_start;
441         w_prev_end = w_new_end;
442
443         depth++;
444     } while (count != 0 && depth <= 10);
445
446     return 1;
447 }
448
449 int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx)
450 {
451     if (ctx == NULL || ctx->decoder_insts == NULL)
452         return 0;
453     return sk_OSSL_DECODER_INSTANCE_num(ctx->decoder_insts);
454 }
455
456 int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx,
457                                    OSSL_DECODER_CONSTRUCT *construct)
458 {
459     if (!ossl_assert(ctx != NULL)) {
460         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
461         return 0;
462     }
463     ctx->construct = construct;
464     return 1;
465 }
466
467 int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx,
468                                         void *construct_data)
469 {
470     if (!ossl_assert(ctx != NULL)) {
471         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
472         return 0;
473     }
474     ctx->construct_data = construct_data;
475     return 1;
476 }
477
478 int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx,
479                                  OSSL_DECODER_CLEANUP *cleanup)
480 {
481     if (!ossl_assert(ctx != NULL)) {
482         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
483         return 0;
484     }
485     ctx->cleanup = cleanup;
486     return 1;
487 }
488
489 OSSL_DECODER_CONSTRUCT *
490 OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx)
491 {
492     if (ctx == NULL)
493         return NULL;
494     return ctx->construct;
495 }
496
497 void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx)
498 {
499     if (ctx == NULL)
500         return NULL;
501     return ctx->construct_data;
502 }
503
504 OSSL_DECODER_CLEANUP *
505 OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx)
506 {
507     if (ctx == NULL)
508         return NULL;
509     return ctx->cleanup;
510 }
511
512 int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst,
513                         void *reference, size_t reference_sz,
514                         OSSL_CALLBACK *export_cb, void *export_cbarg)
515 {
516     OSSL_DECODER *decoder = NULL;
517     void *decoderctx = NULL;
518
519     if (!(ossl_assert(decoder_inst != NULL)
520           && ossl_assert(reference != NULL)
521           && ossl_assert(export_cb != NULL)
522           && ossl_assert(export_cbarg != NULL))) {
523         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_PASSED_NULL_PARAMETER);
524         return 0;
525     }
526
527     decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
528     decoderctx = OSSL_DECODER_INSTANCE_get_decoder_ctx(decoder_inst);
529     return decoder->export_object(decoderctx, reference, reference_sz,
530                                   export_cb, export_cbarg);
531 }
532
533 OSSL_DECODER *
534 OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst)
535 {
536     if (decoder_inst == NULL)
537         return NULL;
538     return decoder_inst->decoder;
539 }
540
541 void *
542 OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst)
543 {
544     if (decoder_inst == NULL)
545         return NULL;
546     return decoder_inst->decoderctx;
547 }
548
549 const char *
550 OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst)
551 {
552     if (decoder_inst == NULL)
553         return NULL;
554     return decoder_inst->input_type;
555 }
556
557 const char *
558 OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst,
559                                           int *was_set)
560 {
561     if (decoder_inst == NULL)
562         return NULL;
563     *was_set = decoder_inst->flag_input_structure_was_set;
564     return decoder_inst->input_structure;
565 }
566
567 static int decoder_process(const OSSL_PARAM params[], void *arg)
568 {
569     struct decoder_process_data_st *data = arg;
570     OSSL_DECODER_CTX *ctx = data->ctx;
571     OSSL_DECODER_INSTANCE *decoder_inst = NULL;
572     OSSL_DECODER *decoder = NULL;
573     OSSL_CORE_BIO *cbio = NULL;
574     BIO *bio = data->bio;
575     long loc;
576     size_t i;
577     int ok = 0;
578     /* For recursions */
579     struct decoder_process_data_st new_data;
580     const char *data_type = NULL;
581     const char *data_structure = NULL;
582
583     /*
584      * This is an indicator up the call stack that something was indeed
585      * decoded, leading to a recursive call of this function.
586      */
587     data->flag_next_level_called = 1;
588
589     memset(&new_data, 0, sizeof(new_data));
590     new_data.ctx = data->ctx;
591     new_data.recursion = data->recursion + 1;
592
593 #define LEVEL_STR ">>>>>>>>>>>>>>>>"
594 #define LEVEL (new_data.recursion < sizeof(LEVEL_STR)                   \
595                ? &LEVEL_STR[sizeof(LEVEL_STR) - new_data.recursion - 1] \
596                : LEVEL_STR "...")
597
598     if (params == NULL) {
599         /* First iteration, where we prepare for what is to come */
600
601         OSSL_TRACE_BEGIN(DECODER) {
602             BIO_printf(trc_out,
603                        "(ctx %p) starting to walk the decoder chain\n",
604                        (void *)new_data.ctx);
605         } OSSL_TRACE_END(DECODER);
606
607         data->current_decoder_inst_index =
608             OSSL_DECODER_CTX_get_num_decoders(ctx);
609
610         bio = data->bio;
611     } else {
612         const OSSL_PARAM *p;
613         const char *trace_data_structure;
614
615         decoder_inst =
616             sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts,
617                                            data->current_decoder_inst_index);
618         decoder = OSSL_DECODER_INSTANCE_get_decoder(decoder_inst);
619
620         data->flag_construct_called = 0;
621         if (ctx->construct != NULL) {
622             int rv = ctx->construct(decoder_inst, params, ctx->construct_data);
623
624             data->flag_construct_called = 1;
625             ok = (rv > 0);
626             if (ok)
627                 goto end;
628         }
629
630         /* The constructor didn't return success */
631
632         /*
633          * so we try to use the object we got and feed it to any next
634          * decoder that will take it.  Object references are not
635          * allowed for this.
636          * If this data isn't present, decoding has failed.
637          */
638
639         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA);
640         if (p == NULL || p->data_type != OSSL_PARAM_OCTET_STRING)
641             goto end;
642         new_data.bio = BIO_new_mem_buf(p->data, (int)p->data_size);
643         if (new_data.bio == NULL)
644             goto end;
645         bio = new_data.bio;
646
647         /* Get the data type if there is one */
648         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
649         if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_type))
650             goto end;
651
652         /* Get the data structure if there is one */
653         p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_STRUCTURE);
654         if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &data_structure))
655             goto end;
656
657         /*
658          * If the data structure is "type-specific" and the data type is
659          * given, we drop the data structure.  The reasoning is that the
660          * data type is already enough to find the applicable next decoder,
661          * so an additional "type-specific" data structure is extraneous.
662          *
663          * Furthermore, if the OSSL_DECODER caller asked for a type specific
664          * structure under another name, such as "DH", we get a mismatch
665          * if the data structure we just received is "type-specific".
666          * There's only so much you can do without infusing this code with
667          * too special knowledge.
668          */
669         trace_data_structure = data_structure;
670         if (data_type != NULL && data_structure != NULL
671             && strcasecmp(data_structure, "type-specific") == 0)
672             data_structure = NULL;
673
674         OSSL_TRACE_BEGIN(DECODER) {
675             BIO_printf(trc_out,
676                        "(ctx %p) %s incoming from previous decoder (%p):\n"
677                        "    data type: %s, data structure: %s%s\n",
678                        (void *)new_data.ctx, LEVEL, (void *)decoder,
679                        data_type, trace_data_structure,
680                        (trace_data_structure == data_structure
681                         ? "" : " (dropped)"));
682         } OSSL_TRACE_END(DECODER);
683     }
684
685     /*
686      * If we have no more decoders to look through at this point,
687      * we failed
688      */
689     if (data->current_decoder_inst_index == 0)
690         goto end;
691
692     if ((loc = BIO_tell(bio)) < 0) {
693         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_BIO_LIB);
694         goto end;
695     }
696
697     if ((cbio = ossl_core_bio_new_from_bio(bio)) == NULL) {
698         ERR_raise(ERR_LIB_OSSL_DECODER, ERR_R_MALLOC_FAILURE);
699         goto end;
700     }
701
702     for (i = data->current_decoder_inst_index; i-- > 0;) {
703         OSSL_DECODER_INSTANCE *new_decoder_inst =
704             sk_OSSL_DECODER_INSTANCE_value(ctx->decoder_insts, i);
705         OSSL_DECODER *new_decoder =
706             OSSL_DECODER_INSTANCE_get_decoder(new_decoder_inst);
707         void *new_decoderctx =
708             OSSL_DECODER_INSTANCE_get_decoder_ctx(new_decoder_inst);
709         const char *new_input_type =
710             OSSL_DECODER_INSTANCE_get_input_type(new_decoder_inst);
711         int n_i_s_was_set = 0;   /* We don't care here */
712         const char *new_input_structure =
713             OSSL_DECODER_INSTANCE_get_input_structure(new_decoder_inst,
714                                                       &n_i_s_was_set);
715
716         OSSL_TRACE_BEGIN(DECODER) {
717             BIO_printf(trc_out,
718                        "(ctx %p) %s [%u] Considering decoder instance %p, which has:\n"
719                        "    input type: %s, input structure: %s, decoder: %p\n",
720                        (void *)new_data.ctx, LEVEL, (unsigned int)i,
721                        (void *)new_decoder_inst, new_input_type,
722                        new_input_structure, (void *)new_decoder);
723         } OSSL_TRACE_END(DECODER);
724
725         /*
726          * If |decoder| is NULL, it means we've just started, and the caller
727          * may have specified what it expects the initial input to be.  If
728          * that's the case, we do this extra check.
729          */
730         if (decoder == NULL && ctx->start_input_type != NULL
731             && strcasecmp(ctx->start_input_type, new_input_type) != 0) {
732             OSSL_TRACE_BEGIN(DECODER) {
733                 BIO_printf(trc_out,
734                            "(ctx %p) %s [%u] the start input type '%s' doesn't match the input type of the considered decoder, skipping...\n",
735                            (void *)new_data.ctx, LEVEL, (unsigned int)i,
736                            ctx->start_input_type);
737             } OSSL_TRACE_END(DECODER);
738             continue;
739         }
740
741         /*
742          * If we have a previous decoder, we check that the input type
743          * of the next to be used matches the type of this previous one.
744          * |new_input_type| holds the value of the "input-type" parameter
745          * for the decoder we're currently considering.
746          */
747         if (decoder != NULL && !OSSL_DECODER_is_a(decoder, new_input_type)) {
748             OSSL_TRACE_BEGIN(DECODER) {
749                 BIO_printf(trc_out,
750                            "(ctx %p) %s [%u] the input type doesn't match the name of the previous decoder (%p), skipping...\n",
751                            (void *)new_data.ctx, LEVEL, (unsigned int)i,
752                            (void *)decoder);
753             } OSSL_TRACE_END(DECODER);
754             continue;
755         }
756
757         /*
758          * If the previous decoder gave us a data type, we check to see
759          * if that matches the decoder we're currently considering.
760          */
761         if (data_type != NULL && !OSSL_DECODER_is_a(new_decoder, data_type)) {
762             OSSL_TRACE_BEGIN(DECODER) {
763                 BIO_printf(trc_out,
764                            "(ctx %p) %s [%u] the previous decoder's data type doesn't match the name of the considered decoder, skipping...\n",
765                            (void *)new_data.ctx, LEVEL, (unsigned int)i);
766             } OSSL_TRACE_END(DECODER);
767             continue;
768         }
769
770         /*
771          * If the previous decoder gave us a data structure name, we check
772          * to see that it matches the input data structure of the decoder
773          * we're currently considering.
774          */
775         if (data_structure != NULL
776             && (new_input_structure == NULL
777                 || strcasecmp(data_structure, new_input_structure) != 0)) {
778             OSSL_TRACE_BEGIN(DECODER) {
779                 BIO_printf(trc_out,
780                            "(ctx %p) %s [%u] the previous decoder's data structure doesn't match the input structure of the considered decoder, skipping...\n",
781                            (void *)new_data.ctx, LEVEL, (unsigned int)i);
782             } OSSL_TRACE_END(DECODER);
783             continue;
784         }
785
786         /*
787          * Checking the return value of BIO_reset() or BIO_seek() is unsafe.
788          * Furthermore, BIO_reset() is unsafe to use if the source BIO happens
789          * to be a BIO_s_mem(), because the earlier BIO_tell() gives us zero
790          * no matter where we are in the underlying buffer we're reading from.
791          *
792          * So, we simply do a BIO_seek(), and use BIO_tell() that we're back
793          * at the same position.  This is a best effort attempt, but BIO_seek()
794          * and BIO_tell() should come as a pair...
795          */
796         (void)BIO_seek(bio, loc);
797         if (BIO_tell(bio) != loc)
798             goto end;
799
800         /* Recurse */
801         OSSL_TRACE_BEGIN(DECODER) {
802             BIO_printf(trc_out,
803                        "(ctx %p) %s [%u] Running decoder instance %p\n",
804                        (void *)new_data.ctx, LEVEL, (unsigned int)i,
805                        (void *)new_decoder_inst);
806         } OSSL_TRACE_END(DECODER);
807
808         /*
809          * We only care about errors reported from decoder implementations
810          * if it returns false (i.e. there was a fatal error).
811          */
812         ERR_set_mark();
813
814         new_data.current_decoder_inst_index = i;
815         ok = new_decoder->decode(new_decoderctx, cbio,
816                                  new_data.ctx->selection,
817                                  decoder_process, &new_data,
818                                  ossl_pw_passphrase_callback_dec,
819                                  &new_data.ctx->pwdata);
820
821         OSSL_TRACE_BEGIN(DECODER) {
822             BIO_printf(trc_out,
823                        "(ctx %p) %s [%u] Running decoder instance %p => %d"
824                        " (recursed further: %s, construct called: %s)\n",
825                        (void *)new_data.ctx, LEVEL, (unsigned int)i,
826                        (void *)new_decoder_inst, ok,
827                        new_data.flag_next_level_called ? "yes" : "no",
828                        new_data.flag_construct_called ? "yes" : "no");
829         } OSSL_TRACE_END(DECODER);
830
831         data->flag_construct_called = new_data.flag_construct_called;
832
833         /* Break on error or if we tried to construct an object already */
834         if (!ok || data->flag_construct_called) {
835             ERR_clear_last_mark();
836             break;
837         }
838         ERR_pop_to_mark();
839
840         /*
841          * Break if the decoder implementation that we called recursed, since
842          * that indicates that it successfully decoded something.
843          */
844         if (new_data.flag_next_level_called)
845             break;
846     }
847
848  end:
849     ossl_core_bio_free(cbio);
850     BIO_free(new_data.bio);
851     return ok;
852 }