eventstore-client-c/tcp_package.c

83 lines
2.9 KiB
C
Raw Normal View History

2018-03-19 06:08:57 +00:00
//
// Created by nicol on 2018-03-18.
//
#include <memory.h>
#include <stdlib.h>
#include <mem.h>
#include "tcp_package.h"
const uint32_t CommandOffset = 0;
const uint32_t FlagsOffset = 1;
const uint32_t CorrelationOffset = 2;
const uint32_t AuthOffset = 18;
const uint32_t MandatorySize = 18;
const tcp_package_t* tcp_package_create(uint8_t command, const esc_uuid_t* correlation_id, buffer_t data) {
tcp_package_t* pkg = malloc(sizeof(tcp_package_t));
pkg->command = command;
pkg->flags = 0;
pkg->correlation_id = *correlation_id;
pkg->login = 0;
pkg->password = 0;
pkg->data = data;
return pkg;
}
const tcp_package_t* tcp_package_create_authenticated(uint8_t command, const esc_uuid_t* correlation_id, buffer_t data, const char* username, const char* password) {
tcp_package_t* pkg = malloc(sizeof(tcp_package_t));
pkg->command = command;
pkg->flags = 1;
pkg->correlation_id = *correlation_id;
pkg->login = username;
pkg->password = password;
pkg->data = data;
return pkg;
}
void tcp_package_free(const tcp_package_t* pkg) {
buffer_free(pkg->data);
free((void*)pkg);
}
buffer_t tcp_package_to_buffer(const tcp_package_t* pkg) {
uint8_t* _dst = malloc(MandatorySize + pkg->data.size + (pkg->flags ? 257*2 : 0));
_dst[CommandOffset] = pkg->command;
_dst[FlagsOffset] = pkg->flags;
memcpy(&_dst[CorrelationOffset], &pkg->correlation_id, sizeof(esc_uuid_t));
size_t size = MandatorySize;
if (pkg->flags) {
size_t l_len = strlen(pkg->login);
_dst[AuthOffset] = l_len;
strcpy(&_dst[AuthOffset+1], pkg->login);
size_t p_len = strlen(pkg->password);
_dst[AuthOffset+1+l_len] = p_len;
strcpy(&_dst[AuthOffset+2+l_len], pkg->password);
memcpy(&_dst[AuthOffset+2+l_len+p_len], pkg->data.data, pkg->data.size);
size += 2 + l_len + p_len + pkg->data.size;
} else {
memcpy(&_dst[AuthOffset], pkg->data.data, pkg->data.size);
size += pkg->data.size;
}
return buffer_from(_dst, size);
}
const tcp_package_t* tcp_package_from_buffer(buffer_t buffer) {
tcp_package_t* pkg = malloc(sizeof(tcp_package_t));
pkg->command = buffer.data[CommandOffset];
pkg->flags = buffer.data[FlagsOffset];
memcpy(&pkg->correlation_id, &buffer.data[CorrelationOffset], sizeof(esc_uuid_t));
if (pkg->flags) {
size_t l_len = buffer.data[AuthOffset];
size_t p_len = buffer.data[AuthOffset+1+l_len];
pkg->data = buffer_create(buffer.size - MandatorySize - 2 - l_len - p_len);
memcpy(pkg->data.data, &buffer.data[MandatorySize + 2 + l_len + p_len], buffer.size - MandatorySize - 2 - l_len - p_len);
} else {
pkg->login = 0;
pkg->password = 0;
pkg->data = buffer_create(buffer.size - MandatorySize);
memcpy(pkg->data.data, &buffer.data[MandatorySize], buffer.size - MandatorySize);
}
return pkg;
}