2021-07-18 22:15:13 +00:00
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
//
|
|
|
|
// SCSI Target Emulator RaSCSI (*^..^*)
|
|
|
|
// for Raspberry Pi
|
|
|
|
//
|
|
|
|
// Powered by XM6 TypeG Technology.
|
|
|
|
// Copyright (C) 2016-2020 GIMONS
|
|
|
|
// Copyright (C) 2020 akuker
|
|
|
|
//
|
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
#include <cstring>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include "exceptions.h"
|
|
|
|
#include "rasutil.h"
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
//
|
|
|
|
// Serialize/Deserialize protobuf data: Length followed by the actual data
|
|
|
|
//
|
|
|
|
//---------------------------------------------------------------------------
|
|
|
|
|
2021-07-19 23:41:00 +00:00
|
|
|
void SerializeProtobufData(int fd, const string& data)
|
2021-07-18 22:15:13 +00:00
|
|
|
{
|
|
|
|
// Write the size of the protobuf data as a header
|
2021-07-19 23:41:00 +00:00
|
|
|
int32_t size = data.length();
|
|
|
|
if (write(fd, &size, sizeof(size)) != sizeof(size)) {
|
|
|
|
throw ioexception("Cannot write protobuf header");
|
|
|
|
}
|
2021-07-18 22:15:13 +00:00
|
|
|
|
|
|
|
// Write the actual protobuf data
|
|
|
|
void *buf = malloc(size);
|
|
|
|
memcpy(buf, data.data(), size);
|
2021-07-19 23:41:00 +00:00
|
|
|
if (write(fd, buf, size) != size) {
|
|
|
|
free(buf);
|
|
|
|
|
|
|
|
throw ioexception("Cannot write protobuf data");
|
|
|
|
}
|
2021-07-18 22:15:13 +00:00
|
|
|
|
|
|
|
free(buf);
|
|
|
|
}
|
|
|
|
|
|
|
|
string DeserializeProtobufData(int fd)
|
|
|
|
{
|
|
|
|
// First read the header with the size of the protobuf data
|
2021-07-19 23:41:00 +00:00
|
|
|
int32_t size;
|
|
|
|
if (read(fd, &size, sizeof(size)) != sizeof(size)) {
|
2021-07-18 22:15:13 +00:00
|
|
|
// No more data
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read the actual protobuf data
|
|
|
|
void *buf = malloc(size);
|
2021-07-19 23:41:00 +00:00
|
|
|
if (read(fd, buf, size) != (ssize_t)size) {
|
2021-07-18 22:15:13 +00:00
|
|
|
free(buf);
|
|
|
|
|
|
|
|
throw ioexception("Missing protobuf data");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read protobuf data into a string, to be converted into a protobuf data structure by the caller
|
|
|
|
string data((const char *)buf, size);
|
|
|
|
free(buf);
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|