2 utils.c -- gathering of some stupid small functions
3 Copyright (C) 1999-2005 Ivo Timmermans
4 2000-2014 Guus Sliepen <guus@tinc-vpn.org>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "../src/logger.h"
26 static const char hexadecimals[] = "0123456789ABCDEF";
28 static int charhex2bin(char c) {
32 return toupper(c) - 'A' + 10;
35 bool hex2bin(char *src, char *dst, int length) {
36 for(int i = 0; i < length; i++) {
37 if(!isxdigit(src[i * 2]) || !isxdigit(src[i * 2 + 1]))
39 dst[i] = charhex2bin(src[i * 2]) * 16 + charhex2bin(src[i * 2 + 1]);
44 void bin2hex(char *src, char *dst, int length) {
46 for(i = length - 1; i >= 0; i--) {
47 dst[i * 2 + 1] = hexadecimals[(unsigned char) src[i] & 15];
48 dst[i * 2] = hexadecimals[(unsigned char) src[i] >> 4];
52 #if defined(HAVE_MINGW) || defined(HAVE_CYGWIN)
54 #include <w32api/windows.h>
57 const char *winerror(int err) {
58 static char buf[1024], *ptr;
60 ptr = buf + sprintf(buf, "(%d) ", err);
62 if (!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
63 NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), ptr, sizeof(buf) - (ptr - buf), NULL)) {
64 strcpy(ptr, "(unable to format errormessage)");
67 if((ptr = strchr(buf, '\r')))
74 unsigned int bitfield_to_int(const void *bitfield, size_t size) {
75 unsigned int value = 0;
76 if(size > sizeof value)
78 memcpy(&value, bitfield, size);
83 * As memcmp(), but constant-time.
84 * Returns 0 when data is equal, non-zero otherwise.
86 int memcmp_constant_time (const void *a, const void *b, size_t size) {
87 const uint8_t *a1 = a, *b1 = b;
91 for (i = 0; i < size; i++)