in src/data_query.h [104:164]
int table_streams::init(int dbfd, bool is_read_only, const unsigned char *magic,
int record_offset, int record_size) {
int flags = is_read_only ? O_RDONLY : (O_RDWR | O_CREAT);
std::string index_name = name + ".index";
int datafd = openat(dbfd, name.c_str(), flags);
int indexfd = openat(dbfd, index_name.c_str(), flags);
int has_error = 0;
if (datafd == -1)
has_error |= is_read_only ? 1 : error("could not open <dbdir>/" + name);
if (indexfd == -1)
has_error |=
is_read_only ? 1 : error("could not open <dbdir>/" + index_name);
if (has_error) {
close(indexfd);
close(datafd);
return 1;
}
if (!is_read_only) {
fchmod(indexfd, 0644);
fchmod(datafd, 0644);
}
if (data.init(datafd, is_read_only))
return error("could not open <dbdir>/" + name);
if (index.init(indexfd, is_read_only))
return error("could not open <dbdir>/" + index_name);
// Check that file sizes make sense.
const unsigned char index_magic[] = {'s', 2, 'm', 0x1, 'n', 0xd, 0xe, 'x'};
assert(sizeof(index_magic) == magic_size);
if (data.get_num_bytes_on_open()) {
if (!index.get_num_bytes_on_open())
return error("unexpected data without index for " + name);
if (data.get_num_bytes_on_open() < magic_size ||
(data.get_num_bytes_on_open() - record_offset) % record_size)
return error("invalid data for " + name);
unsigned char file_magic[magic_size];
if (data.seek(0) || data.read(file_magic, magic_size) != magic_size ||
memcmp(file_magic, magic, magic_size))
return error("bad magic for " + name);
} else if (!is_read_only) {
if (data.seek(0) || data.write(magic, magic_size) != magic_size)
return error("could not write magic for " + name);
}
if (index.get_num_bytes_on_open()) {
if (!data.get_num_bytes_on_open())
return error("unexpected index without " + name);
if (index.get_num_bytes_on_open() < magic_size)
return error("invalid index for " + name);
unsigned char file_magic[magic_size];
if (index.seek(0) || index.read(file_magic, magic_size) != magic_size ||
memcmp(file_magic, index_magic, magic_size))
return error("bad index magic for " + name);
} else if (!is_read_only) {
if (index.seek(0) || index.write(index_magic, magic_size) != magic_size)
return error("could not write index magic for " + name);
}
return 0;
}