e813989624707f6c715dd5d47379f62bd1bd21b6
[openssl.git] / crypto / stack / stack.c
1 /*
2  * Copyright 1995-2024 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 <stdio.h>
11 #include "internal/cryptlib.h"
12 #include "internal/numbers.h"
13 #include "internal/safe_math.h"
14 #include <openssl/stack.h>
15 #include <errno.h>
16 #include <openssl/e_os2.h>      /* For ossl_inline */
17
18 OSSL_SAFE_MATH_SIGNED(int, int)
19
20 /*
21  * The initial number of nodes in the array.
22  */
23 static const int min_nodes = 4;
24 static const int max_nodes = SIZE_MAX / sizeof(void *) < INT_MAX
25     ? (int)(SIZE_MAX / sizeof(void *)) : INT_MAX;
26
27 struct stack_st {
28     int num;
29     const void **data;
30     int sorted;
31     int num_alloc;
32     OPENSSL_sk_compfunc comp;
33 };
34
35 OPENSSL_sk_compfunc OPENSSL_sk_set_cmp_func(OPENSSL_STACK *sk,
36                                             OPENSSL_sk_compfunc c)
37 {
38     OPENSSL_sk_compfunc old = sk->comp;
39
40     if (sk->comp != c)
41         sk->sorted = 0;
42     sk->comp = c;
43
44     return old;
45 }
46
47 OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *sk)
48 {
49     OPENSSL_STACK *ret;
50
51     if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL)
52         goto err;
53
54     if (sk == NULL) {
55         ret->num = 0;
56         ret->sorted = 0;
57         ret->comp = NULL;
58     } else {
59         /* direct structure assignment */
60         *ret = *sk;
61     }
62
63     if (sk == NULL || sk->num == 0) {
64         /* postpone |ret->data| allocation */
65         ret->data = NULL;
66         ret->num_alloc = 0;
67         return ret;
68     }
69
70     /* duplicate |sk->data| content */
71     ret->data = OPENSSL_malloc(sizeof(*ret->data) * sk->num_alloc);
72     if (ret->data == NULL)
73         goto err;
74     memcpy(ret->data, sk->data, sizeof(void *) * sk->num);
75     return ret;
76
77  err:
78     OPENSSL_sk_free(ret);
79     return NULL;
80 }
81
82 OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *sk,
83                                     OPENSSL_sk_copyfunc copy_func,
84                                     OPENSSL_sk_freefunc free_func)
85 {
86     OPENSSL_STACK *ret;
87     int i;
88
89     if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL)
90         goto err;
91
92     if (sk == NULL) {
93         ret->num = 0;
94         ret->sorted = 0;
95         ret->comp = NULL;
96     } else {
97         /* direct structure assignment */
98         *ret = *sk;
99     }
100
101     if (sk == NULL || sk->num == 0) {
102         /* postpone |ret| data allocation */
103         ret->data = NULL;
104         ret->num_alloc = 0;
105         return ret;
106     }
107
108     ret->num_alloc = sk->num > min_nodes ? sk->num : min_nodes;
109     ret->data = OPENSSL_zalloc(sizeof(*ret->data) * ret->num_alloc);
110     if (ret->data == NULL)
111         goto err;
112
113     for (i = 0; i < ret->num; ++i) {
114         if (sk->data[i] == NULL)
115             continue;
116         if ((ret->data[i] = copy_func(sk->data[i])) == NULL) {
117             while (--i >= 0)
118                 if (ret->data[i] != NULL)
119                     free_func((void *)ret->data[i]);
120             goto err;
121         }
122     }
123     return ret;
124
125  err:
126     OPENSSL_sk_free(ret);
127     return NULL;
128 }
129
130 OPENSSL_STACK *OPENSSL_sk_new_null(void)
131 {
132     return OPENSSL_sk_new_reserve(NULL, 0);
133 }
134
135 OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc c)
136 {
137     return OPENSSL_sk_new_reserve(c, 0);
138 }
139
140 /*
141  * Calculate the array growth based on the target size.
142  *
143  * The growth factor is a rational number and is defined by a numerator
144  * and a denominator.  According to Andrew Koenig in his paper "Why Are
145  * Vectors Efficient?" from JOOP 11(5) 1998, this factor should be less
146  * than the golden ratio (1.618...).
147  *
148  * Considering only the Fibonacci ratios less than the golden ratio, the
149  * number of steps from the minimum allocation to integer overflow is:
150  *      factor  decimal    growths
151  *       3/2     1.5          51
152  *       8/5     1.6          45
153  *      21/13    1.615...     44
154  *
155  * All larger factors have the same number of growths.
156  *
157  * 3/2 and 8/5 have nice power of two shifts, so seem like a good choice.
158  */
159 static ossl_inline int compute_growth(int target, int current)
160 {
161     int err = 0;
162
163     while (current < target) {
164         if (current >= max_nodes)
165             return 0;
166
167         current = safe_muldiv_int(current, 8, 5, &err);
168         if (err != 0)
169             return 0;
170         if (current >= max_nodes)
171             current = max_nodes;
172     }
173     return current;
174 }
175
176 /* internal STACK storage allocation */
177 static int sk_reserve(OPENSSL_STACK *st, int n, int exact)
178 {
179     const void **tmpdata;
180     int num_alloc;
181
182     /* Check to see the reservation isn't exceeding the hard limit */
183     if (n > max_nodes - st->num) {
184         ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_RECORDS);
185         return 0;
186     }
187
188     /* Figure out the new size */
189     num_alloc = st->num + n;
190     if (num_alloc < min_nodes)
191         num_alloc = min_nodes;
192
193     /* If |st->data| allocation was postponed */
194     if (st->data == NULL) {
195         /*
196          * At this point, |st->num_alloc| and |st->num| are 0;
197          * so |num_alloc| value is |n| or |min_nodes| if greater than |n|.
198          */
199         if ((st->data = OPENSSL_zalloc(sizeof(void *) * num_alloc)) == NULL)
200             return 0;
201         st->num_alloc = num_alloc;
202         return 1;
203     }
204
205     if (!exact) {
206         if (num_alloc <= st->num_alloc)
207             return 1;
208         num_alloc = compute_growth(num_alloc, st->num_alloc);
209         if (num_alloc == 0) {
210             ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_RECORDS);
211             return 0;
212         }
213     } else if (num_alloc == st->num_alloc) {
214         return 1;
215     }
216
217     tmpdata = OPENSSL_realloc((void *)st->data, sizeof(void *) * num_alloc);
218     if (tmpdata == NULL)
219         return 0;
220
221     st->data = tmpdata;
222     st->num_alloc = num_alloc;
223     return 1;
224 }
225
226 OPENSSL_STACK *OPENSSL_sk_new_reserve(OPENSSL_sk_compfunc c, int n)
227 {
228     OPENSSL_STACK *st = OPENSSL_zalloc(sizeof(OPENSSL_STACK));
229
230     if (st == NULL)
231         return NULL;
232
233     st->comp = c;
234
235     if (n <= 0)
236         return st;
237
238     if (!sk_reserve(st, n, 1)) {
239         OPENSSL_sk_free(st);
240         return NULL;
241     }
242
243     return st;
244 }
245
246 int OPENSSL_sk_reserve(OPENSSL_STACK *st, int n)
247 {
248     if (st == NULL) {
249         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
250         return 0;
251     }
252
253     if (n < 0)
254         return 1;
255     return sk_reserve(st, n, 1);
256 }
257
258 int OPENSSL_sk_insert(OPENSSL_STACK *st, const void *data, int loc)
259 {
260     if (st == NULL) {
261         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
262         return 0;
263     }
264     if (st->num == max_nodes) {
265         ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_RECORDS);
266         return 0;
267     }
268
269     if (!sk_reserve(st, 1, 0))
270         return 0;
271
272     if ((loc >= st->num) || (loc < 0)) {
273         st->data[st->num] = data;
274     } else {
275         memmove(&st->data[loc + 1], &st->data[loc],
276                 sizeof(st->data[0]) * (st->num - loc));
277         st->data[loc] = data;
278     }
279     st->num++;
280     st->sorted = 0;
281     return st->num;
282 }
283
284 static ossl_inline void *internal_delete(OPENSSL_STACK *st, int loc)
285 {
286     const void *ret = st->data[loc];
287
288     if (loc != st->num - 1)
289         memmove(&st->data[loc], &st->data[loc + 1],
290                 sizeof(st->data[0]) * (st->num - loc - 1));
291     st->num--;
292
293     return (void *)ret;
294 }
295
296 void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *st, const void *p)
297 {
298     int i;
299
300     if (st == NULL)
301         return NULL;
302
303     for (i = 0; i < st->num; i++)
304         if (st->data[i] == p)
305             return internal_delete(st, i);
306     return NULL;
307 }
308
309 void *OPENSSL_sk_delete(OPENSSL_STACK *st, int loc)
310 {
311     if (st == NULL || loc < 0 || loc >= st->num)
312         return NULL;
313
314     return internal_delete(st, loc);
315 }
316
317 static int internal_find(OPENSSL_STACK *st, const void *data,
318                          int ret_val_options, int *pnum_matched)
319 {
320     const void *r;
321     int i, count = 0;
322     int *pnum = pnum_matched;
323
324     if (st == NULL || st->num == 0)
325         return -1;
326
327     if (pnum == NULL)
328         pnum = &count;
329
330     if (st->comp == NULL) {
331         for (i = 0; i < st->num; i++)
332             if (st->data[i] == data) {
333                 *pnum = 1;
334                 return i;
335             }
336         *pnum = 0;
337         return -1;
338     }
339
340     if (data == NULL)
341         return -1;
342
343     if (!st->sorted) {
344         int res = -1;
345
346         for (i = 0; i < st->num; i++)
347             if (st->comp(&data, st->data + i) == 0) {
348                 if (res == -1)
349                     res = i;
350                 ++*pnum;
351                 /* Check if only one result is wanted and exit if so */
352                 if (pnum_matched == NULL)
353                     return i;
354             }
355         if (res == -1)
356             *pnum = 0;
357         return res;
358     }
359
360     if (pnum_matched != NULL)
361         ret_val_options |= OSSL_BSEARCH_FIRST_VALUE_ON_MATCH;
362     r = ossl_bsearch(&data, st->data, st->num, sizeof(void *), st->comp,
363                      ret_val_options);
364
365     if (pnum_matched != NULL) {
366         *pnum = 0;
367         if (r != NULL) {
368             const void **p = (const void **)r;
369
370             while (p < st->data + st->num) {
371                 if (st->comp(&data, p) != 0)
372                     break;
373                 ++*pnum;
374                 ++p;
375             }
376         }
377     }
378
379     return r == NULL ? -1 : (int)((const void **)r - st->data);
380 }
381
382 int OPENSSL_sk_find(OPENSSL_STACK *st, const void *data)
383 {
384     return internal_find(st, data, OSSL_BSEARCH_FIRST_VALUE_ON_MATCH, NULL);
385 }
386
387 int OPENSSL_sk_find_ex(OPENSSL_STACK *st, const void *data)
388 {
389     return internal_find(st, data, OSSL_BSEARCH_VALUE_ON_NOMATCH, NULL);
390 }
391
392 int OPENSSL_sk_find_all(OPENSSL_STACK *st, const void *data, int *pnum)
393 {
394     return internal_find(st, data, OSSL_BSEARCH_FIRST_VALUE_ON_MATCH, pnum);
395 }
396
397 int OPENSSL_sk_push(OPENSSL_STACK *st, const void *data)
398 {
399     if (st == NULL)
400         return 0;
401     return OPENSSL_sk_insert(st, data, st->num);
402 }
403
404 int OPENSSL_sk_unshift(OPENSSL_STACK *st, const void *data)
405 {
406     return OPENSSL_sk_insert(st, data, 0);
407 }
408
409 void *OPENSSL_sk_shift(OPENSSL_STACK *st)
410 {
411     if (st == NULL || st->num == 0)
412         return NULL;
413     return internal_delete(st, 0);
414 }
415
416 void *OPENSSL_sk_pop(OPENSSL_STACK *st)
417 {
418     if (st == NULL || st->num == 0)
419         return NULL;
420     return internal_delete(st, st->num - 1);
421 }
422
423 void OPENSSL_sk_zero(OPENSSL_STACK *st)
424 {
425     if (st == NULL || st->num == 0)
426         return;
427     memset(st->data, 0, sizeof(*st->data) * st->num);
428     st->num = 0;
429 }
430
431 void OPENSSL_sk_pop_free(OPENSSL_STACK *st, OPENSSL_sk_freefunc func)
432 {
433     int i;
434
435     if (st == NULL)
436         return;
437     for (i = 0; i < st->num; i++)
438         if (st->data[i] != NULL)
439             func((char *)st->data[i]);
440     OPENSSL_sk_free(st);
441 }
442
443 void OPENSSL_sk_free(OPENSSL_STACK *st)
444 {
445     if (st == NULL)
446         return;
447     OPENSSL_free(st->data);
448     OPENSSL_free(st);
449 }
450
451 int OPENSSL_sk_num(const OPENSSL_STACK *st)
452 {
453     return st == NULL ? -1 : st->num;
454 }
455
456 void *OPENSSL_sk_value(const OPENSSL_STACK *st, int i)
457 {
458     if (st == NULL || i < 0 || i >= st->num)
459         return NULL;
460     return (void *)st->data[i];
461 }
462
463 void *OPENSSL_sk_set(OPENSSL_STACK *st, int i, const void *data)
464 {
465     if (st == NULL) {
466         ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
467         return NULL;
468     }
469     if (i < 0 || i >= st->num) {
470         ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT,
471                        "i=%d", i);
472         return NULL;
473     }
474     st->data[i] = data;
475     st->sorted = 0;
476     return (void *)st->data[i];
477 }
478
479 void OPENSSL_sk_sort(OPENSSL_STACK *st)
480 {
481     if (st != NULL && !st->sorted && st->comp != NULL) {
482         if (st->num > 1)
483             qsort(st->data, st->num, sizeof(void *), st->comp);
484         st->sorted = 1; /* empty or single-element stack is considered sorted */
485     }
486 }
487
488 int OPENSSL_sk_is_sorted(const OPENSSL_STACK *st)
489 {
490     return st == NULL ? 1 : st->sorted;
491 }