stack: Do not add error if pop/shift/value accesses outside of the stack
[openssl.git] / crypto / conf / conf_def.c
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* Part of the code in here was originally in conf.c, which is now removed */
11
12 #include <stdio.h>
13 #include <string.h>
14 #include "internal/e_os.h" /* struct stat */
15 #ifdef __TANDEM
16 # include <sys/types.h> /* needed for stat.h */
17 # include <sys/stat.h> /* struct stat */
18 #endif
19 #include "internal/cryptlib.h"
20 #include "internal/o_dir.h"
21 #include <openssl/lhash.h>
22 #include <openssl/conf.h>
23 #include <openssl/conf_api.h>
24 #include "conf_local.h"
25 #include "conf_def.h"
26 #include <openssl/buffer.h>
27 #include <openssl/err.h>
28 #ifndef OPENSSL_NO_POSIX_IO
29 # include <sys/stat.h>
30 # ifdef _WIN32
31 #  define stat    _stat
32 # endif
33 #endif
34
35 #ifndef S_ISDIR
36 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
37 #endif
38
39 /*
40  * The maximum length we can grow a value to after variable expansion. 64k
41  * should be more than enough for all reasonable uses.
42  */
43 #define MAX_CONF_VALUE_LENGTH       65536
44
45 static int is_keytype(const CONF *conf, char c, unsigned short type);
46 static char *eat_ws(CONF *conf, char *p);
47 static void trim_ws(CONF *conf, char *start);
48 static char *eat_alpha_numeric(CONF *conf, char *p);
49 static void clear_comments(CONF *conf, char *p);
50 static int str_copy(CONF *conf, char *section, char **to, char *from);
51 static char *scan_quote(CONF *conf, char *p);
52 static char *scan_dquote(CONF *conf, char *p);
53 #define scan_esc(conf,p)        (((IS_EOF((conf),(p)[1]))?((p)+1):((p)+2)))
54 #ifndef OPENSSL_NO_POSIX_IO
55 static BIO *process_include(char *include, OPENSSL_DIR_CTX **dirctx,
56                             char **dirpath);
57 static BIO *get_next_file(const char *path, OPENSSL_DIR_CTX **dirctx);
58 #endif
59
60 static CONF *def_create(CONF_METHOD *meth);
61 static int def_init_default(CONF *conf);
62 #ifndef OPENSSL_NO_DEPRECATED_3_0
63 static int def_init_WIN32(CONF *conf);
64 #endif
65 static int def_destroy(CONF *conf);
66 static int def_destroy_data(CONF *conf);
67 static int def_load(CONF *conf, const char *name, long *eline);
68 static int def_load_bio(CONF *conf, BIO *bp, long *eline);
69 static int def_dump(const CONF *conf, BIO *bp);
70 static int def_is_number(const CONF *conf, char c);
71 static int def_to_int(const CONF *conf, char c);
72
73 static CONF_METHOD default_method = {
74     "OpenSSL default",
75     def_create,
76     def_init_default,
77     def_destroy,
78     def_destroy_data,
79     def_load_bio,
80     def_dump,
81     def_is_number,
82     def_to_int,
83     def_load
84 };
85
86 CONF_METHOD *NCONF_default(void)
87 {
88     return &default_method;
89 }
90
91 #ifndef OPENSSL_NO_DEPRECATED_3_0
92 static CONF_METHOD WIN32_method = {
93     "WIN32",
94     def_create,
95     def_init_WIN32,
96     def_destroy,
97     def_destroy_data,
98     def_load_bio,
99     def_dump,
100     def_is_number,
101     def_to_int,
102     def_load
103 };
104
105 CONF_METHOD *NCONF_WIN32(void)
106 {
107     return &WIN32_method;
108 }
109 #endif
110
111 static CONF *def_create(CONF_METHOD *meth)
112 {
113     CONF *ret;
114
115     ret = OPENSSL_malloc(sizeof(*ret));
116     if (ret != NULL)
117         if (meth->init(ret) == 0) {
118             OPENSSL_free(ret);
119             ret = NULL;
120         }
121     return ret;
122 }
123
124 static int def_init_default(CONF *conf)
125 {
126     if (conf == NULL)
127         return 0;
128
129     memset(conf, 0, sizeof(*conf));
130     conf->meth = &default_method;
131     conf->meth_data = (void *)CONF_type_default;
132
133     return 1;
134 }
135
136 #ifndef OPENSSL_NO_DEPRECATED_3_0
137 static int def_init_WIN32(CONF *conf)
138 {
139     if (conf == NULL)
140         return 0;
141
142     memset(conf, 0, sizeof(*conf));
143     conf->meth = &WIN32_method;
144     conf->meth_data = (void *)CONF_type_win32;
145
146     return 1;
147 }
148 #endif
149
150 static int def_destroy(CONF *conf)
151 {
152     if (def_destroy_data(conf)) {
153         OPENSSL_free(conf);
154         return 1;
155     }
156     return 0;
157 }
158
159 static int def_destroy_data(CONF *conf)
160 {
161     if (conf == NULL)
162         return 0;
163     _CONF_free_data(conf);
164     return 1;
165 }
166
167 static int def_load(CONF *conf, const char *name, long *line)
168 {
169     int ret;
170     BIO *in = NULL;
171
172 #ifdef OPENSSL_SYS_VMS
173     in = BIO_new_file(name, "r");
174 #else
175     in = BIO_new_file(name, "rb");
176 #endif
177     if (in == NULL) {
178         if (ERR_GET_REASON(ERR_peek_last_error()) == BIO_R_NO_SUCH_FILE)
179             ERR_raise(ERR_LIB_CONF, CONF_R_NO_SUCH_FILE);
180         else
181             ERR_raise(ERR_LIB_CONF, ERR_R_SYS_LIB);
182         return 0;
183     }
184
185     ret = def_load_bio(conf, in, line);
186     BIO_free(in);
187
188     return ret;
189 }
190
191
192 /* Parse a boolean value and fill in *flag. Return 0 on error. */
193 static int parsebool(const char *pval, int *flag)
194 {
195     if (OPENSSL_strcasecmp(pval, "on") == 0
196         || OPENSSL_strcasecmp(pval, "true") == 0) {
197         *flag = 1;
198     } else if (OPENSSL_strcasecmp(pval, "off") == 0
199                || OPENSSL_strcasecmp(pval, "false") == 0) {
200         *flag = 0;
201     } else {
202         ERR_raise(ERR_LIB_CONF, CONF_R_INVALID_PRAGMA);
203         return 0;
204     }
205     return 1;
206 }
207
208 static int def_load_bio(CONF *conf, BIO *in, long *line)
209 {
210 /* The macro BUFSIZE conflicts with a system macro in VxWorks */
211 #define CONFBUFSIZE     512
212     int bufnum = 0, i, ii;
213     BUF_MEM *buff = NULL;
214     char *s, *p, *end;
215     int again;
216     int first_call = 1;
217     long eline = 0;
218     char btmp[DECIMAL_SIZE(eline) + 1];
219     CONF_VALUE *v = NULL, *tv;
220     CONF_VALUE *sv = NULL;
221     char *section = NULL, *buf;
222     char *start, *psection, *pname;
223     void *h = (void *)(conf->data);
224     STACK_OF(BIO) *biosk = NULL;
225 #ifndef OPENSSL_NO_POSIX_IO
226     char *dirpath = NULL;
227     OPENSSL_DIR_CTX *dirctx = NULL;
228 #endif
229
230     if ((buff = BUF_MEM_new()) == NULL) {
231         ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
232         goto err;
233     }
234
235     section = OPENSSL_strdup("default");
236     if (section == NULL)
237         goto err;
238
239     if (_CONF_new_data(conf) == 0) {
240         ERR_raise(ERR_LIB_CONF, ERR_R_CONF_LIB);
241         goto err;
242     }
243
244     sv = _CONF_new_section(conf, section);
245     if (sv == NULL) {
246         ERR_raise(ERR_LIB_CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
247         goto err;
248     }
249
250     bufnum = 0;
251     again = 0;
252     for (;;) {
253         if (!BUF_MEM_grow(buff, bufnum + CONFBUFSIZE)) {
254             ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
255             goto err;
256         }
257         p = &(buff->data[bufnum]);
258         *p = '\0';
259  read_retry:
260         if (in != NULL && BIO_gets(in, p, CONFBUFSIZE - 1) < 0)
261             goto err;
262         p[CONFBUFSIZE - 1] = '\0';
263         ii = i = strlen(p);
264         if (first_call) {
265             /* Other BOMs imply unsupported multibyte encoding,
266              * so don't strip them and let the error raise */
267             const unsigned char utf8_bom[3] = {0xEF, 0xBB, 0xBF};
268
269             if (i >= 3 && memcmp(p, utf8_bom, 3) == 0) {
270                 memmove(p, p + 3, i - 3);
271                 p[i - 3] = 0;
272                 i -= 3;
273                 ii -= 3;
274             }
275             first_call = 0;
276         }
277         if (i == 0 && !again) {
278             /* the currently processed BIO is NULL or at EOF */
279             BIO *parent;
280
281 #ifndef OPENSSL_NO_POSIX_IO
282             /* continue processing with the next file from directory */
283             if (dirctx != NULL) {
284                 BIO *next;
285
286                 if ((next = get_next_file(dirpath, &dirctx)) != NULL) {
287                     BIO_vfree(in);
288                     in = next;
289                     goto read_retry;
290                 } else {
291                     OPENSSL_free(dirpath);
292                     dirpath = NULL;
293                 }
294             }
295 #endif
296             /* no more files in directory, continue with processing parent */
297             if ((parent = sk_BIO_pop(biosk)) == NULL) {
298                 /* everything processed get out of the loop */
299                 break;
300             } else {
301                 BIO_vfree(in);
302                 in = parent;
303                 goto read_retry;
304             }
305         }
306         again = 0;
307         while (i > 0) {
308             if ((p[i - 1] != '\r') && (p[i - 1] != '\n'))
309                 break;
310             else
311                 i--;
312         }
313         /*
314          * we removed some trailing stuff so there is a new line on the end.
315          */
316         if (ii && i == ii)
317             again = 1;          /* long line */
318         else {
319             p[i] = '\0';
320             eline++;            /* another input line */
321         }
322
323         /* we now have a line with trailing \r\n removed */
324
325         /* i is the number of bytes */
326         bufnum += i;
327
328         v = NULL;
329         /* check for line continuation */
330         if (bufnum >= 1) {
331             /*
332              * If we have bytes and the last char '\\' and second last char
333              * is not '\\'
334              */
335             p = &(buff->data[bufnum - 1]);
336             if (IS_ESC(conf, p[0]) && ((bufnum <= 1) || !IS_ESC(conf, p[-1]))) {
337                 bufnum--;
338                 again = 1;
339             }
340         }
341         if (again)
342             continue;
343         bufnum = 0;
344         buf = buff->data;
345
346         clear_comments(conf, buf);
347         s = eat_ws(conf, buf);
348         if (IS_EOF(conf, *s))
349             continue;           /* blank line */
350         if (*s == '[') {
351             char *ss;
352
353             s++;
354             start = eat_ws(conf, s);
355             ss = start;
356  again:
357             end = eat_alpha_numeric(conf, ss);
358             p = eat_ws(conf, end);
359             if (*p != ']') {
360                 if (*p != '\0' && ss != p) {
361                     ss = p;
362                     goto again;
363                 }
364                 ERR_raise(ERR_LIB_CONF, CONF_R_MISSING_CLOSE_SQUARE_BRACKET);
365                 goto err;
366             }
367             *end = '\0';
368             if (!str_copy(conf, NULL, &section, start))
369                 goto err;
370             if ((sv = _CONF_get_section(conf, section)) == NULL)
371                 sv = _CONF_new_section(conf, section);
372             if (sv == NULL) {
373                 ERR_raise(ERR_LIB_CONF, CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
374                 goto err;
375             }
376             continue;
377         } else {
378             pname = s;
379             end = eat_alpha_numeric(conf, s);
380             if ((end[0] == ':') && (end[1] == ':')) {
381                 *end = '\0';
382                 end += 2;
383                 psection = pname;
384                 pname = end;
385                 end = eat_alpha_numeric(conf, end);
386             } else {
387                 psection = section;
388             }
389             p = eat_ws(conf, end);
390             if (CHECK_AND_SKIP_PREFIX(pname, ".pragma")
391                 && (p != pname || *p == '=')) {
392                 char *pval;
393
394                 if (*p == '=') {
395                     p++;
396                     p = eat_ws(conf, p);
397                 }
398                 trim_ws(conf, p);
399
400                 /* Pragma values take the form keyword:value */
401                 pval = strchr(p, ':');
402                 if (pval == NULL || pval == p || pval[1] == '\0') {
403                     ERR_raise(ERR_LIB_CONF, CONF_R_INVALID_PRAGMA);
404                     goto err;
405                 }
406
407                 *pval++ = '\0';
408                 trim_ws(conf, p);
409                 pval = eat_ws(conf, pval);
410
411                 /*
412                  * Known pragmas:
413                  *
414                  * dollarid     takes "on", "true or "off", "false"
415                  * abspath      takes "on", "true or "off", "false"
416                  * includedir   directory prefix
417                  */
418                 if (strcmp(p, "dollarid") == 0) {
419                     if (!parsebool(pval, &conf->flag_dollarid))
420                         goto err;
421                 } else if (strcmp(p, "abspath") == 0) {
422                     if (!parsebool(pval, &conf->flag_abspath))
423                         goto err;
424                 } else if (strcmp(p, "includedir") == 0) {
425                     OPENSSL_free(conf->includedir);
426                     if ((conf->includedir = OPENSSL_strdup(pval)) == NULL)
427                         goto err;
428                 }
429
430                 /*
431                  * We *ignore* any unknown pragma.
432                  */
433                 continue;
434             } else if (CHECK_AND_SKIP_PREFIX(pname, ".include")
435                 && (p != pname || *p == '=')) {
436                 char *include = NULL;
437                 BIO *next;
438                 const char *include_dir = ossl_safe_getenv("OPENSSL_CONF_INCLUDE");
439                 char *include_path = NULL;
440
441                 if (include_dir == NULL)
442                     include_dir = conf->includedir;
443
444                 if (*p == '=') {
445                     p++;
446                     p = eat_ws(conf, p);
447                 }
448                 trim_ws(conf, p);
449                 if (!str_copy(conf, psection, &include, p))
450                     goto err;
451
452                 if (include_dir != NULL && !ossl_is_absolute_path(include)) {
453                     size_t newlen = strlen(include_dir) + strlen(include) + 2;
454
455                     include_path = OPENSSL_malloc(newlen);
456                     if (include_path == NULL) {
457                         OPENSSL_free(include);
458                         goto err;
459                     }
460
461                     OPENSSL_strlcpy(include_path, include_dir, newlen);
462                     if (!ossl_ends_with_dirsep(include_path))
463                         OPENSSL_strlcat(include_path, "/", newlen);
464                     OPENSSL_strlcat(include_path, include, newlen);
465                     OPENSSL_free(include);
466                 } else {
467                     include_path = include;
468                 }
469
470                 if (conf->flag_abspath
471                         && !ossl_is_absolute_path(include_path)) {
472                     ERR_raise(ERR_LIB_CONF, CONF_R_RELATIVE_PATH);
473                     OPENSSL_free(include_path);
474                     goto err;
475                 }
476
477                 /* get the BIO of the included file */
478 #ifndef OPENSSL_NO_POSIX_IO
479                 next = process_include(include_path, &dirctx, &dirpath);
480                 if (include_path != dirpath) {
481                     /* dirpath will contain include in case of a directory */
482                     OPENSSL_free(include_path);
483                 }
484 #else
485                 next = BIO_new_file(include_path, "r");
486                 OPENSSL_free(include_path);
487 #endif
488
489                 if (next != NULL) {
490                     /* push the currently processing BIO onto stack */
491                     if (biosk == NULL) {
492                         if ((biosk = sk_BIO_new_null()) == NULL) {
493                             ERR_raise(ERR_LIB_CONF, ERR_R_CRYPTO_LIB);
494                             BIO_free(next);
495                             goto err;
496                         }
497                     }
498                     if (!sk_BIO_push(biosk, in)) {
499                         ERR_raise(ERR_LIB_CONF, ERR_R_CRYPTO_LIB);
500                         BIO_free(next);
501                         goto err;
502                     }
503                     /* continue with reading from the included BIO */
504                     in = next;
505                 }
506                 continue;
507             } else if (*p != '=') {
508                 ERR_raise_data(ERR_LIB_CONF, CONF_R_MISSING_EQUAL_SIGN,
509                                "HERE-->%s", p);
510                 goto err;
511             }
512             *end = '\0';
513             p++;
514             start = eat_ws(conf, p);
515             trim_ws(conf, start);
516
517             if ((v = OPENSSL_malloc(sizeof(*v))) == NULL)
518                 goto err;
519             v->name = OPENSSL_strdup(pname);
520             v->value = NULL;
521             if (v->name == NULL)
522                 goto err;
523             if (!str_copy(conf, psection, &(v->value), start))
524                 goto err;
525
526             if (strcmp(psection, section) != 0) {
527                 if ((tv = _CONF_get_section(conf, psection))
528                     == NULL)
529                     tv = _CONF_new_section(conf, psection);
530                 if (tv == NULL) {
531                     ERR_raise(ERR_LIB_CONF,
532                               CONF_R_UNABLE_TO_CREATE_NEW_SECTION);
533                     goto err;
534                 }
535             } else
536                 tv = sv;
537             if (_CONF_add_string(conf, tv, v) == 0) {
538                 ERR_raise(ERR_LIB_CONF, ERR_R_CONF_LIB);
539                 goto err;
540             }
541             v = NULL;
542         }
543     }
544     BUF_MEM_free(buff);
545     OPENSSL_free(section);
546     /*
547      * No need to pop, since we only get here if the stack is empty.
548      * If this causes a BIO leak, THE ISSUE IS SOMEWHERE ELSE!
549      */
550     sk_BIO_free(biosk);
551     return 1;
552
553  err:
554     BUF_MEM_free(buff);
555     OPENSSL_free(section);
556     /*
557      * Since |in| is the first element of the stack and should NOT be freed
558      * here, we cannot use sk_BIO_pop_free().  Instead, we pop and free one
559      * BIO at a time, making sure that the last one popped isn't.
560      */
561     while (sk_BIO_num(biosk) > 0) {
562         BIO *popped = sk_BIO_pop(biosk);
563         BIO_vfree(in);
564         in = popped;
565     }
566     sk_BIO_free(biosk);
567 #ifndef OPENSSL_NO_POSIX_IO
568     OPENSSL_free(dirpath);
569     if (dirctx != NULL)
570         OPENSSL_DIR_end(&dirctx);
571 #endif
572     if (line != NULL)
573         *line = eline;
574     BIO_snprintf(btmp, sizeof(btmp), "%ld", eline);
575     ERR_add_error_data(2, "line ", btmp);
576     if (h != conf->data) {
577         CONF_free(conf->data);
578         conf->data = NULL;
579     }
580     if (v != NULL) {
581         OPENSSL_free(v->name);
582         OPENSSL_free(v->value);
583         OPENSSL_free(v);
584     }
585     return 0;
586 }
587
588 static void clear_comments(CONF *conf, char *p)
589 {
590     for (;;) {
591         if (IS_FCOMMENT(conf, *p)) {
592             *p = '\0';
593             return;
594         }
595         if (!IS_WS(conf, *p)) {
596             break;
597         }
598         p++;
599     }
600
601     for (;;) {
602         if (IS_COMMENT(conf, *p)) {
603             *p = '\0';
604             return;
605         }
606         if (IS_DQUOTE(conf, *p)) {
607             p = scan_dquote(conf, p);
608             continue;
609         }
610         if (IS_QUOTE(conf, *p)) {
611             p = scan_quote(conf, p);
612             continue;
613         }
614         if (IS_ESC(conf, *p)) {
615             p = scan_esc(conf, p);
616             continue;
617         }
618         if (IS_EOF(conf, *p))
619             return;
620         else
621             p++;
622     }
623 }
624
625 static int str_copy(CONF *conf, char *section, char **pto, char *from)
626 {
627     int q, r, rr = 0, to = 0, len = 0;
628     char *s, *e, *rp, *p, *rrp, *np, *cp, v;
629     BUF_MEM *buf;
630
631     if ((buf = BUF_MEM_new()) == NULL)
632         return 0;
633
634     len = strlen(from) + 1;
635     if (!BUF_MEM_grow(buf, len))
636         goto err;
637
638     for (;;) {
639         if (IS_QUOTE(conf, *from)) {
640             q = *from;
641             from++;
642             while (!IS_EOF(conf, *from) && (*from != q)) {
643                 if (IS_ESC(conf, *from)) {
644                     from++;
645                     if (IS_EOF(conf, *from))
646                         break;
647                 }
648                 buf->data[to++] = *(from++);
649             }
650             if (*from == q)
651                 from++;
652         } else if (IS_DQUOTE(conf, *from)) {
653             q = *from;
654             from++;
655             while (!IS_EOF(conf, *from)) {
656                 if (*from == q) {
657                     if (*(from + 1) == q) {
658                         from++;
659                     } else {
660                         break;
661                     }
662                 }
663                 buf->data[to++] = *(from++);
664             }
665             if (*from == q)
666                 from++;
667         } else if (IS_ESC(conf, *from)) {
668             from++;
669             v = *(from++);
670             if (IS_EOF(conf, v))
671                 break;
672             else if (v == 'r')
673                 v = '\r';
674             else if (v == 'n')
675                 v = '\n';
676             else if (v == 'b')
677                 v = '\b';
678             else if (v == 't')
679                 v = '\t';
680             buf->data[to++] = v;
681         } else if (IS_EOF(conf, *from))
682             break;
683         else if (*from == '$'
684                  && (!conf->flag_dollarid
685                      || from[1] == '{'
686                      || from[1] == '(')) {
687             size_t newsize;
688
689             /* try to expand it */
690             rrp = NULL;
691             s = &(from[1]);
692             if (*s == '{')
693                 q = '}';
694             else if (*s == '(')
695                 q = ')';
696             else
697                 q = 0;
698
699             if (q)
700                 s++;
701             cp = section;
702             e = np = s;
703             while (IS_ALNUM(conf, *e)
704                    || (conf->flag_dollarid && IS_DOLLAR(conf, *e)))
705                 e++;
706             if ((e[0] == ':') && (e[1] == ':')) {
707                 cp = np;
708                 rrp = e;
709                 rr = *e;
710                 *rrp = '\0';
711                 e += 2;
712                 np = e;
713                 while (IS_ALNUM(conf, *e)
714                        || (conf->flag_dollarid && IS_DOLLAR(conf, *e)))
715                     e++;
716             }
717             r = *e;
718             *e = '\0';
719             rp = e;
720             if (q) {
721                 if (r != q) {
722                     ERR_raise(ERR_LIB_CONF, CONF_R_NO_CLOSE_BRACE);
723                     goto err;
724                 }
725                 e++;
726             }
727             /*-
728              * So at this point we have
729              * np which is the start of the name string which is
730              *   '\0' terminated.
731              * cp which is the start of the section string which is
732              *   '\0' terminated.
733              * e is the 'next point after'.
734              * r and rr are the chars replaced by the '\0'
735              * rp and rrp is where 'r' and 'rr' came from.
736              */
737             p = _CONF_get_string(conf, cp, np);
738             if (rrp != NULL)
739                 *rrp = rr;
740             *rp = r;
741             if (p == NULL) {
742                 ERR_raise(ERR_LIB_CONF, CONF_R_VARIABLE_HAS_NO_VALUE);
743                 goto err;
744             }
745             newsize = strlen(p) + buf->length - (e - from);
746             if (newsize > MAX_CONF_VALUE_LENGTH) {
747                 ERR_raise(ERR_LIB_CONF, CONF_R_VARIABLE_EXPANSION_TOO_LONG);
748                 goto err;
749             }
750             if (!BUF_MEM_grow_clean(buf, newsize)) {
751                 ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB);
752                 goto err;
753             }
754             while (*p)
755                 buf->data[to++] = *(p++);
756
757             /*
758              * Since we change the pointer 'from', we also have to change the
759              * perceived length of the string it points at.  /RL
760              */
761             len -= e - from;
762             from = e;
763
764             /*
765              * In case there were no braces or parenthesis around the
766              * variable reference, we have to put back the character that was
767              * replaced with a '\0'.  /RL
768              */
769             *rp = r;
770         } else
771             buf->data[to++] = *(from++);
772     }
773     buf->data[to] = '\0';
774     OPENSSL_free(*pto);
775     *pto = buf->data;
776     OPENSSL_free(buf);
777     return 1;
778  err:
779     BUF_MEM_free(buf);
780     return 0;
781 }
782
783 #ifndef OPENSSL_NO_POSIX_IO
784 /*
785  * Check whether included path is a directory.
786  * Returns next BIO to process and in case of a directory
787  * also an opened directory context and the include path.
788  */
789 static BIO *process_include(char *include, OPENSSL_DIR_CTX **dirctx,
790                             char **dirpath)
791 {
792     struct stat st;
793     BIO *next;
794
795     if (stat(include, &st) < 0) {
796         ERR_raise_data(ERR_LIB_SYS, errno, "calling stat(%s)", include);
797         /* missing include file is not fatal error */
798         return NULL;
799     }
800
801     if (S_ISDIR(st.st_mode)) {
802         if (*dirctx != NULL) {
803             ERR_raise_data(ERR_LIB_CONF, CONF_R_RECURSIVE_DIRECTORY_INCLUDE,
804                            "%s", include);
805             return NULL;
806         }
807         /* a directory, load its contents */
808         if ((next = get_next_file(include, dirctx)) != NULL)
809             *dirpath = include;
810         return next;
811     }
812
813     next = BIO_new_file(include, "r");
814     return next;
815 }
816
817 /*
818  * Get next file from the directory path.
819  * Returns BIO of the next file to read and updates dirctx.
820  */
821 static BIO *get_next_file(const char *path, OPENSSL_DIR_CTX **dirctx)
822 {
823     const char *filename;
824     size_t pathlen;
825
826     pathlen = strlen(path);
827     while ((filename = OPENSSL_DIR_read(dirctx, path)) != NULL) {
828         size_t namelen;
829
830         namelen = strlen(filename);
831
832
833         if ((namelen > 5
834              && OPENSSL_strcasecmp(filename + namelen - 5, ".conf") == 0)
835             || (namelen > 4
836                 && OPENSSL_strcasecmp(filename + namelen - 4, ".cnf") == 0)) {
837             size_t newlen;
838             char *newpath;
839             BIO *bio;
840
841             newlen = pathlen + namelen + 2;
842             newpath = OPENSSL_zalloc(newlen);
843             if (newpath == NULL)
844                 break;
845 #ifdef OPENSSL_SYS_VMS
846             /*
847              * If the given path isn't clear VMS syntax,
848              * we treat it as on Unix.
849              */
850             if (path[pathlen - 1] == ']'
851                 || path[pathlen - 1] == '>'
852                 || path[pathlen - 1] == ':') {
853                 /* Clear VMS directory syntax, just copy as is */
854                 OPENSSL_strlcpy(newpath, path, newlen);
855             }
856 #endif
857             if (newpath[0] == '\0') {
858                 OPENSSL_strlcpy(newpath, path, newlen);
859                 OPENSSL_strlcat(newpath, "/", newlen);
860             }
861             OPENSSL_strlcat(newpath, filename, newlen);
862
863             bio = BIO_new_file(newpath, "r");
864             OPENSSL_free(newpath);
865             /* Errors when opening files are non-fatal. */
866             if (bio != NULL)
867                 return bio;
868         }
869     }
870     OPENSSL_DIR_end(dirctx);
871     *dirctx = NULL;
872     return NULL;
873 }
874 #endif
875
876 static int is_keytype(const CONF *conf, char c, unsigned short type)
877 {
878     const unsigned short * keytypes = (const unsigned short *) conf->meth_data;
879     unsigned char key = (unsigned char)c;
880
881 #ifdef CHARSET_EBCDIC
882 # if CHAR_BIT > 8
883     if (key > 255) {
884         /* key is out of range for os_toascii table */
885         return 0;
886     }
887 # endif
888     /* convert key from ebcdic to ascii */
889     key = os_toascii[key];
890 #endif
891
892     if (key > 127) {
893         /* key is not a seven bit ascii character */
894         return 0;
895     }
896
897     return (keytypes[key] & type) ? 1 : 0;
898 }
899
900 static char *eat_ws(CONF *conf, char *p)
901 {
902     while (IS_WS(conf, *p) && (!IS_EOF(conf, *p)))
903         p++;
904     return p;
905 }
906
907 static void trim_ws(CONF *conf, char *start)
908 {
909     char *p = start;
910
911     while (!IS_EOF(conf, *p))
912         p++;
913     p--;
914     while ((p >= start) && IS_WS(conf, *p))
915         p--;
916     p++;
917     *p = '\0';
918 }
919
920 static char *eat_alpha_numeric(CONF *conf, char *p)
921 {
922     for (;;) {
923         if (IS_ESC(conf, *p)) {
924             p = scan_esc(conf, p);
925             continue;
926         }
927         if (!(IS_ALNUM_PUNCT(conf, *p)
928               || (conf->flag_dollarid && IS_DOLLAR(conf, *p))))
929             return p;
930         p++;
931     }
932 }
933
934 static char *scan_quote(CONF *conf, char *p)
935 {
936     int q = *p;
937
938     p++;
939     while (!(IS_EOF(conf, *p)) && (*p != q)) {
940         if (IS_ESC(conf, *p)) {
941             p++;
942             if (IS_EOF(conf, *p))
943                 return p;
944         }
945         p++;
946     }
947     if (*p == q)
948         p++;
949     return p;
950 }
951
952 static char *scan_dquote(CONF *conf, char *p)
953 {
954     int q = *p;
955
956     p++;
957     while (!(IS_EOF(conf, *p))) {
958         if (*p == q) {
959             if (*(p + 1) == q) {
960                 p++;
961             } else {
962                 break;
963             }
964         }
965         p++;
966     }
967     if (*p == q)
968         p++;
969     return p;
970 }
971
972 static void dump_value_doall_arg(const CONF_VALUE *a, BIO *out)
973 {
974     if (a->name)
975         BIO_printf(out, "[%s] %s=%s\n", a->section, a->name, a->value);
976     else
977         BIO_printf(out, "[[%s]]\n", a->section);
978 }
979
980 IMPLEMENT_LHASH_DOALL_ARG_CONST(CONF_VALUE, BIO);
981
982 static int def_dump(const CONF *conf, BIO *out)
983 {
984     lh_CONF_VALUE_doall_BIO(conf->data, dump_value_doall_arg, out);
985     return 1;
986 }
987
988 static int def_is_number(const CONF *conf, char c)
989 {
990     return IS_NUMBER(conf, c);
991 }
992
993 static int def_to_int(const CONF *conf, char c)
994 {
995     return c - '0';
996 }