hexagram/src/capture.c

133 lines
3.1 KiB
C
Raw Normal View History

2019-02-11 20:12:09 -06:00
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <net/if.h>
#include <hexagram/capture.h>
struct _hexagram_capture {
int fd;
uint32_t endian;
};
hexagram_capture *hexagram_capture_open_fd(int fd, int flags) {
hexagram_capture *capture;
hexagram_capture_header header;
if ((capture = malloc(sizeof(*capture))) == NULL) {
goto error_malloc;
}
if (flags & O_WRONLY && !(flags & O_APPEND)) {
memcpy(header.magic, HEXAGRAM_CAPTURE_MAGIC, strlen(HEXAGRAM_CAPTURE_MAGIC));
header.endian = HEXAGRAM_CAPTURE_ENDIAN;
if (write(fd, &header, sizeof(header)) < 0) {
goto error_io;
}
} else if (flags & O_RDONLY) {
ssize_t readlen;
if ((readlen = read(fd, &header, sizeof(header))) < 0) {
goto error_io;
}
if (memcmp(header.magic, HEXAGRAM_CAPTURE_MAGIC, sizeof(header.magic)) != 0) {
goto error_invalid_format;
}
switch (header.endian) {
case HEXAGRAM_CAPTURE_ENDIAN:
case HEXAGRAM_CAPTURE_ENDIAN_SWAPPED:
break;
default:
goto error_invalid_format;
}
}
capture->fd = fd;
capture->endian = header.endian;
return capture;
error_invalid_format:
error_io:
free(capture);
error_malloc:
return NULL;
}
hexagram_capture *hexagram_capture_open_file(const char *file, int flags) {
int fd = (flags & O_CREAT)?
open(file, flags, 0644):
open(file, flags);
if (fd < 0) {
return NULL;
}
return hexagram_capture_open_fd(fd, flags);
}
void hexagram_capture_destroy(hexagram_capture *capture) {
memset(capture, '\0', sizeof(*capture));
free(capture);
}
int hexagram_capture_read(hexagram_capture *capture,
uint32_t *timestamp_hi,
uint32_t *timestamp_lo,
struct can_frame *frame) {
ssize_t len;
hexagram_capture_frame data;
if ((len = read(capture->fd, &data, sizeof(data))) < 0) {
goto error_io;
} else if (len < sizeof(data)) {
goto error_io;
}
*timestamp_hi = data.timestamp_hi;
*timestamp_lo = data.timestamp_lo;
memcpy(frame, &data.frame, sizeof(data.frame));
return 0;
error_io:
return -1;
}
int hexagram_capture_write(hexagram_capture *capture,
struct can_frame *frame,
struct timeval *timestamp) {
hexagram_capture_frame data;
if (timestamp == NULL) {
struct timeval now;
if (gettimeofday(&now, NULL) < 0) {
goto error_gettimeofday;
}
data.timestamp_hi = now.tv_usec & 0xffffffff00000000 >> 32;
data.timestamp_lo = now.tv_usec & 0x00000000ffffffff;
} else {
data.timestamp_hi = timestamp->tv_usec & 0xffffffff00000000 >> 32;
data.timestamp_lo = timestamp->tv_usec & 0x00000000ffffffff;
}
memcpy(&data.frame, frame, sizeof(data.frame));
return write(capture->fd, &data, sizeof(data));
error_gettimeofday:
return -1;
}