111 if (
auto error = open_folder(name, folder)) {
115 if (
auto error = open_file(folder, name, file)) {
118 if (file.get() < 0) {
119 return std::optional<TradingCalendar>();
123 while (text.size() <= MAXIMUM_FILE) {
124 const auto count = ::read(file.get(), buffer,
sizeof(buffer));
128 if (count < 0 && errno != EINTR) {
132 text.append(buffer,
static_cast<std::size_t
>(count));
135 return std::optional<TradingCalendar>();
145 const auto latest = std::chrono::duration_cast<std::chrono::system_clock::duration>(LATEST_RECEIPT);
146 const auto received = calendar.
received_at_.time_since_epoch();
147 if (received < -latest || latest < received) {
148 return calendar_cache_error(
"calendar cache: the receipt time is outside the range the file holds");
151 if (
auto error = open_folder(name, folder)) {
155 if (
auto error = open_file(folder, name, existing)) {
158 auto temporary = write_temporary(folder, name, serialize(calendar));
160 return std::move(temporary.error());
162 return rename_temporary(folder, name, temporary.value());
166 friend struct FileCalendarCacheTestAccess;
169 static constexpr int FILE_FLAGS = O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK;
171 static constexpr std::size_t MAXIMUM_FILE = 256 * 1024;
173 static constexpr auto LATEST_RECEIPT = std::chrono::nanoseconds::max() - std::chrono::hours(24);
178 explicit Descriptor(
int descriptor = -1) noexcept : descriptor_(descriptor) {}
181 if (descriptor_ >= 0) {
182 ::close(descriptor_);
186 Descriptor(
const Descriptor&) =
delete;
187 Descriptor& operator=(
const Descriptor&) =
delete;
189 int get() const noexcept {
193 void reset(
int descriptor)
noexcept {
194 if (descriptor_ >= 0) {
195 ::close(descriptor_);
197 descriptor_ = descriptor;
205 static bool owned_privately(
int descriptor, mode_t type)
noexcept {
206 struct stat status{};
207 return ::fstat(descriptor, &status) == 0 && (status.st_mode & S_IFMT) == type && status.st_uid == ::geteuid() &&
208 (status.st_mode & 077) == 0;
212 std::optional<BrokerError> open_folder(
const std::string& name, Descriptor& folder)
const {
213 bool safe = !name.empty() && name.size() <= 200;
214 for (
const char ch : name) {
216 ((ch >=
'a' && ch <=
'z') || (ch >=
'A' && ch <=
'Z') || (ch >=
'0' && ch <=
'9') || ch ==
'-' || ch ==
'_');
221 if (::mkdir(folder_.c_str(), 0700) != 0 && errno != EEXIST) {
224 folder.reset(::open(folder_.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
225 if (folder.get() < 0) {
226 struct stat status{};
227 const bool link = ::lstat(folder_.c_str(), &status) == 0 && S_ISLNK(status.st_mode);
229 link ?
"calendar cache: the folder is a symbolic link" :
"calendar cache: the folder could not be opened"
232 if (!owned_privately(folder.get(), S_IFDIR)) {
233 return calendar_cache_error(
"calendar cache: the folder is not private (owner or permissions)");
239 static std::optional<BrokerError> open_file(
const Descriptor& folder,
const std::string& name, Descriptor& file) {
240 file.reset(::openat(folder.get(), (name +
".calendar").c_str(), FILE_FLAGS | O_RDONLY));
241 if (file.get() < 0 && errno == ENOENT) {
244 if (file.get() < 0) {
246 errno == ELOOP ?
"calendar cache: the file is a symbolic link" :
"calendar cache: the file could not be opened"
249 if (!owned_privately(file.get(), S_IFREG)) {
250 return calendar_cache_error(
"calendar cache: the file is not private (owner, permissions or type)");
256 static const char* country_code(
Country country)
noexcept {
267 static std::string serialize(
const TradingCalendar& calendar) {
268 boost::json::array days;
269 days.reserve(calendar.days_.size());
270 for (
const auto& day : calendar.days_) {
271 const std::int64_t date =
272 std::int64_t{day.date_.year_} * 10000 + std::int64_t{day.date_.month_} * 100 + std::int64_t{day.date_.day_};
273 days.push_back(boost::json::array{date, day.open_});
275 boost::json::object document;
276 document[
"format"] = 1;
277 document[
"country"] = country_code(calendar.country_);
278 document[
"received_at_ns"] =
279 std::chrono::duration_cast<std::chrono::nanoseconds>(calendar.received_at_.time_since_epoch()).count();
280 document[
"unreadable_days"] = calendar.unreadable_days_;
281 document[
"days"] = std::move(days);
282 return boost::json::serialize(document);
286 static std::optional<TradingCalendar> parse(
const std::string& text) {
287 boost::system::error_code ec;
288 const auto document = boost::json::parse(text, ec);
289 if (ec || !document.is_object()) {
292 const auto&
object = document.as_object();
293 const auto* format =
object.if_contains(
"format");
294 const auto* country =
object.if_contains(
"country");
295 const auto* received =
object.if_contains(
"received_at_ns");
296 const auto* unreadable =
object.if_contains(
"unreadable_days");
297 const auto* days =
object.if_contains(
"days");
299 !format || !format->is_int64() || format->as_int64() != 1 || !country || !country->is_string() || !received ||
300 !received->is_int64() || !unreadable || !unreadable->is_int64() || !days || !days->is_array()
304 TradingCalendar calendar;
306 return country->as_string() == country_code(candidate);
311 calendar.country_ = *named;
312 const auto since_epoch = std::chrono::nanoseconds(received->as_int64());
313 if (since_epoch < -LATEST_RECEIPT || LATEST_RECEIPT < since_epoch) {
316 calendar.received_at_ = std::chrono::system_clock::time_point(
317 std::chrono::duration_cast<std::chrono::system_clock::duration>(since_epoch)
319 if (unreadable->as_int64() < 0 ||
static_cast<std::uint64_t
>(unreadable->as_int64()) > SIZE_MAX) {
322 calendar.unreadable_days_ =
static_cast<std::size_t
>(unreadable->as_int64());
323 calendar.days_.reserve(days->as_array().size());
324 for (
const auto& row : days->as_array()) {
326 !row.is_array() || row.as_array().size() != 2 || !row.as_array()[0].is_int64() || !row.as_array()[1].is_bool()
330 const auto number = row.as_array()[0].as_int64();
331 if (number < 10101 || number > 99991231) {
335 static_cast<int>(number / 10000),
336 static_cast<unsigned>(number / 100 % 100),
337 static_cast<unsigned>(number % 100),
342 calendar.days_.push_back(TradingDay{date, row.as_array()[1].as_bool()});
348 static Result<std::string> write_temporary(
349 const Descriptor& folder,
const std::string& name,
const std::string& text
351 static std::atomic<unsigned long> counter{0};
352 std::string temporary;
354 for (
int attempt = 0; attempt < 100 && file.get() < 0; ++attempt) {
355 temporary = name +
".calendar." + std::to_string(::getpid()) +
'-' + std::to_string(counter++) +
".tmp";
356 file.reset(::openat(folder.get(), temporary.c_str(), FILE_FLAGS | O_WRONLY | O_CREAT | O_EXCL, 0600));
357 if (file.get() < 0 && errno != EEXIST) {
361 if (file.get() < 0) {
365 for (std::size_t offset = 0; written && offset < text.size();) {
366 const auto count = ::write(file.get(), text.data() + offset, text.size() - offset);
368 offset +=
static_cast<std::size_t
>(count);
369 }
else if (count == 0 || errno != EINTR) {
373 if (!written || ::fsync(file.get()) != 0) {
374 ::unlinkat(folder.get(), temporary.c_str(), 0);
381 static std::optional<BrokerError> rename_temporary(
382 const Descriptor& folder,
const std::string& name,
const std::string& temporary
384 if (::renameat(folder.get(), temporary.c_str(), folder.get(), (name +
".calendar").c_str()) != 0) {
385 ::unlinkat(folder.get(), temporary.c_str(), 0);