hop-2012/experiments/cmsg/util.c

114 lines
2.8 KiB
C

/* Copyright 2010, 2011, 2012 Tony Garnock-Jones <tonygarnockjones@gmail.com>.
*
* This file is part of Hop.
*
* Hop is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Hop is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Hop. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <stdarg.h>
/* OSSP UUID */
#include <uuid.h>
#include "cmsg_private.h"
#define UUID_CHECK(context) \
if (result != UUID_RC_OK) { \
warn("gen_uuid failed with %d at %s\n", result, context); \
return result; \
}
int gen_uuid(unsigned char *uuid_buf) {
uuid_rc_t result;
uuid_t *uuid;
unsigned char temp_buf[UUID_LEN_STR + 1];
unsigned char *temp_buf_ptr = &temp_buf[0]; /* odd API */
size_t uuid_buf_len = UUID_LEN_STR + 1;
assert(CMSG_UUID_BUF_SIZE == UUID_LEN_STR);
result = uuid_create(&uuid);
UUID_CHECK("uuid_create");
result = uuid_make(uuid, UUID_MAKE_V4);
UUID_CHECK("uuid_make");
result = uuid_export(uuid, UUID_FMT_STR, &temp_buf_ptr, &uuid_buf_len);
UUID_CHECK("uuid_export");
assert(uuid_buf_len == (UUID_LEN_STR + 1));
memcpy(uuid_buf, temp_buf, CMSG_UUID_BUF_SIZE);
result = uuid_destroy(uuid);
UUID_CHECK("uuid_destroy");
return UUID_RC_OK;
}
cmsg_bytes_t cmsg_bytes_malloc_dup(cmsg_bytes_t src) {
cmsg_bytes_t result;
result.len = src.len;
result.bytes = malloc(src.len);
if (result.bytes != NULL) {
memcpy(result.bytes, src.bytes, src.len);
}
return result;
}
cmsg_bytes_t cmsg_bytes_malloc(size_t amount) {
cmsg_bytes_t result;
result.len = amount;
result.bytes = malloc(amount);
return result;
}
void cmsg_bytes_free(cmsg_bytes_t bytes) {
free(bytes.bytes);
}
int cmsg_bytes_cmp(cmsg_bytes_t a, cmsg_bytes_t b) {
if (a.len < b.len) return -1;
if (a.len > b.len) return 1;
return memcmp(a.bytes, b.bytes, a.len);
}
void die(char const *format, ...) {
va_list vl;
va_start(vl, format);
fprintf(stderr, "ERROR: ");
vfprintf(stderr, format, vl);
va_end(vl);
exit(1);
}
void warn(char const *format, ...) {
va_list vl;
va_start(vl, format);
fprintf(stderr, "WARNING: ");
vfprintf(stderr, format, vl);
va_end(vl);
}
void info(char const *format, ...) {
va_list vl;
va_start(vl, format);
fprintf(stderr, "INFO: ");
vfprintf(stderr, format, vl);
va_end(vl);
}