File: file_storage.cc

package info (click to toggle)
golang-github-google-certificate-transparency 0.0~git20160709.0.0f6e3d1~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 5,676 kB
  • sloc: cpp: 35,278; python: 11,838; java: 1,911; sh: 1,885; makefile: 950; xml: 520; ansic: 225
file content (213 lines) | stat: -rw-r--r-- 5,831 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/* -*- indent-tabs-mode: nil -*- */
#include "log/file_storage.h"

#include <dirent.h>
#include <errno.h>
#include <glog/logging.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdlib>
#include <set>
#include <string>

#include "log/filesystem_ops.h"
#include "util/util.h"

using cert_trans::BasicFilesystemOps;
using cert_trans::FilesystemOps;
using std::string;

namespace cert_trans {


FileStorage::FileStorage(const string& file_base, int storage_depth)
    : storage_dir_(file_base + "/storage"),
      tmp_dir_(file_base + "/tmp"),
      tmp_file_template_(tmp_dir_ + "/tmpXXXXXX"),
      storage_depth_(storage_depth),
      file_op_(new BasicFilesystemOps()) {
  CHECK_GE(storage_depth_, 0);
  CreateMissingDirectory(storage_dir_);
  CreateMissingDirectory(tmp_dir_);
}


FileStorage::FileStorage(const string& file_base, int storage_depth,
                         FilesystemOps* file_op)
    : storage_dir_(file_base + "/storage"),
      tmp_dir_(file_base + "/tmp"),
      tmp_file_template_(tmp_dir_ + "/tmpXXXXXX"),
      storage_depth_(storage_depth),
      file_op_(CHECK_NOTNULL(file_op)) {
  CHECK_GE(storage_depth_, 0);
  CreateMissingDirectory(storage_dir_);
  CreateMissingDirectory(tmp_dir_);
}


FileStorage::~FileStorage() {
  // Needs to be where FilesystemOps is visible.
}


std::set<string> FileStorage::Scan() const {
  std::set<string> storage_keys;
  ScanDir(storage_dir_, storage_depth_, &storage_keys);
  return storage_keys;
}


util::Status FileStorage::CreateEntry(const string& key, const string& data) {
  if (LookupEntry(key, NULL).ok()) {
    return util::Status(util::error::ALREADY_EXISTS,
                        "entry already exists: " + key);
  }
  WriteStorageEntry(key, data);
  return util::Status::OK;
}


util::Status FileStorage::UpdateEntry(const string& key, const string& data) {
  if (!LookupEntry(key, NULL).ok()) {
    return util::Status(util::error::NOT_FOUND,
                        "tried to update non-existent entry: " + key);
  }
  WriteStorageEntry(key, data);
  return util::Status::OK;
}


util::Status FileStorage::LookupEntry(const string& key,
                                      string* result) const {
  string data_file = StoragePath(key);
  if (!FileExists(data_file)) {
    return util::Status(util::error::NOT_FOUND, "entry not found: " + key);
  }
  if (result) {
    CHECK(util::ReadBinaryFile(data_file, result));
  }
  return util::Status::OK;
}


string FileStorage::StoragePathBasename(const string& hex) const {
  if (hex.length() <= static_cast<uint>(storage_depth_))
    return "-";
  return hex.substr(storage_depth_);
}


string FileStorage::StoragePathComponent(const string& hex, int n) const {
  CHECK_GE(n, 0);
  CHECK_LT(n, storage_depth_);
  if (static_cast<uint>(n) >= hex.length())
    return "-";
  return string(1, hex[n]);
}


string FileStorage::StoragePath(const string& key) const {
  string hex = util::HexString(key);
  string dirname = storage_dir_ + "/";
  for (int n = 0; n < storage_depth_; ++n)
    dirname += StoragePathComponent(hex, n) + "/";
  return dirname + StoragePathBasename(hex);
}


string FileStorage::StorageKey(const string& storage_path) const {
  CHECK_EQ(storage_path.substr(0, storage_dir_.size()), storage_dir_);
  string key_path = storage_path.substr(storage_dir_.size() + 1);
  string hex_key;
  for (int n = 0; n < storage_depth_; ++n) {
    char hex_char = key_path[2 * n];
    if (hex_char == '-')
      return util::BinaryString(hex_key);
    hex_key.push_back(hex_char);
  }
  string basename = key_path.substr(2 * storage_depth_);
  if (basename != "-")
    hex_key.append(basename);
  return util::BinaryString(hex_key);
}


void FileStorage::WriteStorageEntry(const string& key, const string& data) {
  string hex = util::HexString(key);

  // Make the intermediate directories, if needed.
  // TODO(ekasper): we can skip this if we know we're updating.
  string dir = storage_dir_;
  for (int n = 0; n < storage_depth_; ++n) {
    dir += "/" + StoragePathComponent(hex, n);
    CreateMissingDirectory(dir);
  }

  // == StoragePath(key)
  string filename = dir + "/" + StoragePathBasename(hex);
  AtomicWriteBinaryFile(filename, data);
}


void FileStorage::ScanFiles(const string& dir_path,
                            std::set<string>* keys) const {
  DIR* dir = CHECK_NOTNULL(opendir(dir_path.c_str()));
  struct dirent* entry;
  while ((entry = readdir(dir)) != NULL) {
    if (entry->d_name[0] == '.')
      continue;
    keys->insert(StorageKey(dir_path + "/" + entry->d_name));
  }
  closedir(dir);
}


void FileStorage::ScanDir(const string& dir_path, int depth,
                          std::set<string>* keys) const {
  CHECK_GE(depth, 0);
  if (depth > 0) {
    // Parse subdirectories. (TODO: make opendir part of filesystemop).
    DIR* dir = CHECK_NOTNULL(opendir(dir_path.c_str()));
    struct dirent* entry;
    std::set<string> result;
    while ((entry = readdir(dir)) != NULL) {
      if (entry->d_name[0] == '.')
        continue;
      ScanDir(dir_path + "/" + entry->d_name, depth - 1, keys);
    }
    closedir(dir);
  } else {
    // depth == 0; parse files.
    ScanFiles(dir_path, keys);
  }
}


bool FileStorage::FileExists(const string& file_path) const {
  if (file_op_->access(file_path, F_OK) == 0)
    return true;

  CHECK_EQ(errno, ENOENT);

  return false;
}


void FileStorage::AtomicWriteBinaryFile(const string& file_path,
                                        const string& data) {
  const string tmp_file(
      util::WriteTemporaryBinaryFile(tmp_file_template_, data));

  CHECK(!tmp_file.empty());
  CHECK_EQ(file_op_->rename(tmp_file, file_path), 0);
}


void FileStorage::CreateMissingDirectory(const string& dir_path) {
  if (file_op_->mkdir(dir_path, 0700) != 0) {
    CHECK_EQ(errno, EEXIST);
  }
}


}  // namespace cert_trans