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