/*1* Copyright (c) 2016 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#include "brssl.h"2526/* see brssl.h */27void *28xmalloc(size_t len)29{30void *buf;3132if (len == 0) {33return NULL;34}35buf = malloc(len);36if (buf == NULL) {37#ifndef _STANDALONE38fprintf(stderr, "ERROR: could not allocate %lu byte(s)\n",39(unsigned long)len);40exit(EXIT_FAILURE);41#else42;43#endif44}45return buf;46}4748/* see brssl.h */49void50xfree(void *buf)51{52if (buf != NULL) {53free(buf);54}55}5657/* see brssl.h */58void *59xblobdup(const void *src, size_t len)60{61void *buf;6263buf = xmalloc(len);64memcpy(buf, src, len);65return buf;66}6768/* see brssl.h */69char *70xstrdup(const void *src)71{72return xblobdup(src, strlen(src) + 1);73}7475/* see brssl.h */76br_x509_pkey *77xpkeydup(const br_x509_pkey *pk)78{79br_x509_pkey *pk2;8081pk2 = xmalloc(sizeof *pk2);82pk2->key_type = pk->key_type;83switch (pk->key_type) {84case BR_KEYTYPE_RSA:85pk2->key.rsa.n = xblobdup(pk->key.rsa.n, pk->key.rsa.nlen);86pk2->key.rsa.nlen = pk->key.rsa.nlen;87pk2->key.rsa.e = xblobdup(pk->key.rsa.e, pk->key.rsa.elen);88pk2->key.rsa.elen = pk->key.rsa.elen;89break;90case BR_KEYTYPE_EC:91pk2->key.ec.curve = pk->key.ec.curve;92pk2->key.ec.q = xblobdup(pk->key.ec.q, pk->key.ec.qlen);93pk2->key.ec.qlen = pk->key.ec.qlen;94break;95default:96#ifndef _STANDALONE97fprintf(stderr, "Unknown public key type: %u\n",98(unsigned)pk->key_type);99exit(EXIT_FAILURE);100#else101;102#endif103}104return pk2;105}106107/* see brssl.h */108void109xfreepkey(br_x509_pkey *pk)110{111if (pk != NULL) {112switch (pk->key_type) {113case BR_KEYTYPE_RSA:114xfree(pk->key.rsa.n);115xfree(pk->key.rsa.e);116break;117case BR_KEYTYPE_EC:118xfree(pk->key.ec.q);119break;120default:121#ifndef _STANDALONE122fprintf(stderr, "Unknown public key type: %u\n",123(unsigned)pk->key_type);124exit(EXIT_FAILURE);125#else126;127#endif128}129xfree(pk);130}131}132133134