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 <https://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 <num.h>
30 #include <datum.h>
31 #include "errors.h"
32
33 /* On error, @dat is not changed. */
34 int
_gnutls_set_datum(gnutls_datum_t * dat,const void * data,size_t data_size)35 _gnutls_set_datum(gnutls_datum_t * dat, const void *data, size_t data_size)
36 {
37 if (data_size == 0 || data == NULL) {
38 dat->data = NULL;
39 dat->size = 0;
40 return 0;
41 }
42
43 unsigned char *m = gnutls_malloc(data_size);
44 if (!m)
45 return GNUTLS_E_MEMORY_ERROR;
46
47 dat->data = m;
48 dat->size = data_size;
49 memcpy(dat->data, data, data_size);
50
51 return 0;
52 }
53
54 /* ensures that the data set are null-terminated
55 * The function always returns an allocated string in @dat on success.
56 * On error, @dat is not changed.
57 */
58 int
_gnutls_set_strdatum(gnutls_datum_t * dat,const void * data,size_t data_size)59 _gnutls_set_strdatum(gnutls_datum_t * dat, const void *data, size_t data_size)
60 {
61 if (data == NULL)
62 return gnutls_assert_val(GNUTLS_E_ILLEGAL_PARAMETER);
63
64 unsigned char *m = gnutls_malloc(data_size + 1);
65 if (!m)
66 return GNUTLS_E_MEMORY_ERROR;
67
68 dat->data = m;
69 dat->size = data_size;
70 if (data_size)
71 memcpy(dat->data, data, data_size);
72 dat->data[data_size] = 0;
73
74 return 0;
75 }
76
77