Fix CVE-2017-6891 in minitasn1 code
[platform/upstream/gnutls.git] / lib / gnutls_datum.c
1 /*
2  * Copyright (C) 2001-2012 Free Software Foundation, Inc.
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * The GnuTLS is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2.1 of
11  * the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>
20  *
21  */
22
23 /* contains functions that make it easier to
24  * write vectors of <size|data>. The destination size
25  * should be preallocated (datum.size+(bits/8))
26  */
27
28 #include <gnutls_int.h>
29 #include <gnutls_num.h>
30 #include <gnutls_datum.h>
31 #include <gnutls_errors.h>
32
33 int
34 _gnutls_set_datum(gnutls_datum_t * dat, const void *data, size_t data_size)
35 {
36         if (data_size == 0 || data == NULL) {
37                 dat->data = NULL;
38                 dat->size = 0;
39                 return 0;
40         }
41
42         dat->data = gnutls_malloc(data_size);
43         if (dat->data == NULL)
44                 return GNUTLS_E_MEMORY_ERROR;
45
46         dat->size = data_size;
47         memcpy(dat->data, data, data_size);
48
49         return 0;
50 }
51
52 /* ensures that the data set are null-terminated */
53 int
54 _gnutls_set_strdatum(gnutls_datum_t * dat, const void *data, size_t data_size)
55 {
56         if (data_size == 0 || data == NULL) {
57                 dat->data = NULL;
58                 dat->size = 0;
59                 return 0;
60         }
61
62         dat->data = gnutls_malloc(data_size+1);
63         if (dat->data == NULL)
64                 return GNUTLS_E_MEMORY_ERROR;
65
66         dat->size = data_size;
67         memcpy(dat->data, data, data_size);
68         dat->data[data_size] = 0;
69
70         return 0;
71 }
72
73 int
74 _gnutls_datum_append(gnutls_datum_t * dst, const void *data,
75                      size_t data_size)
76 {
77
78         dst->data = gnutls_realloc_fast(dst->data, data_size + dst->size);
79         if (dst->data == NULL)
80                 return GNUTLS_E_MEMORY_ERROR;
81
82         memcpy(&dst->data[dst->size], data, data_size);
83         dst->size += data_size;
84
85         return 0;
86 }
87