1 /*
2 * Copyright 1995-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 <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/buffer.h>
13 #include <openssl/asn1.h>
14
15 #ifndef NO_OLD_ASN1
16
17 # ifndef OPENSSL_NO_STDIO
ASN1_i2d_fp(i2d_of_void * i2d,FILE * out,const void * x)18 int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, const void *x)
19 {
20 BIO *b;
21 int ret;
22
23 if ((b = BIO_new(BIO_s_file())) == NULL) {
24 ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
25 return 0;
26 }
27 BIO_set_fp(b, out, BIO_NOCLOSE);
28 ret = ASN1_i2d_bio(i2d, b, x);
29 BIO_free(b);
30 return ret;
31 }
32 # endif
33
ASN1_i2d_bio(i2d_of_void * i2d,BIO * out,const void * x)34 int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, const void *x)
35 {
36 char *b;
37 unsigned char *p;
38 int i, j = 0, n, ret = 1;
39
40 n = i2d(x, NULL);
41 if (n <= 0)
42 return 0;
43
44 b = OPENSSL_malloc(n);
45 if (b == NULL) {
46 ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
47 return 0;
48 }
49
50 p = (unsigned char *)b;
51 i2d(x, &p);
52
53 for (;;) {
54 i = BIO_write(out, &(b[j]), n);
55 if (i == n)
56 break;
57 if (i <= 0) {
58 ret = 0;
59 break;
60 }
61 j += i;
62 n -= i;
63 }
64 OPENSSL_free(b);
65 return ret;
66 }
67
68 #endif
69
70 #ifndef OPENSSL_NO_STDIO
ASN1_item_i2d_fp(const ASN1_ITEM * it,FILE * out,const void * x)71 int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x)
72 {
73 BIO *b;
74 int ret;
75
76 if ((b = BIO_new(BIO_s_file())) == NULL) {
77 ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
78 return 0;
79 }
80 BIO_set_fp(b, out, BIO_NOCLOSE);
81 ret = ASN1_item_i2d_bio(it, b, x);
82 BIO_free(b);
83 return ret;
84 }
85 #endif
86
ASN1_item_i2d_bio(const ASN1_ITEM * it,BIO * out,const void * x)87 int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x)
88 {
89 unsigned char *b = NULL;
90 int i, j = 0, n, ret = 1;
91
92 n = ASN1_item_i2d(x, &b, it);
93 if (b == NULL) {
94 ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
95 return 0;
96 }
97
98 for (;;) {
99 i = BIO_write(out, &(b[j]), n);
100 if (i == n)
101 break;
102 if (i <= 0) {
103 ret = 0;
104 break;
105 }
106 j += i;
107 n -= i;
108 }
109 OPENSSL_free(b);
110 return ret;
111 }
112
ASN1_item_i2d_mem_bio(const ASN1_ITEM * it,const ASN1_VALUE * val)113 BIO *ASN1_item_i2d_mem_bio(const ASN1_ITEM *it, const ASN1_VALUE *val)
114 {
115 BIO *res;
116
117 if (it == NULL || val == NULL) {
118 ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
119 return NULL;
120 }
121
122 if ((res = BIO_new(BIO_s_mem())) == NULL)
123 return NULL;
124 if (ASN1_item_i2d_bio(it, res, val) <= 0) {
125 BIO_free(res);
126 res = NULL;
127 }
128 return res;
129 }
130