openMSX
FilePool.cc
Go to the documentation of this file.
1 #include "FilePool.hh"
2 #include "File.hh"
3 #include "FileException.hh"
4 #include "FileContext.hh"
5 #include "FileOperations.hh"
6 #include "TclObject.hh"
7 #include "StringSetting.hh"
8 #include "ReadDir.hh"
9 #include "Date.hh"
10 #include "CommandController.hh"
11 #include "CommandException.hh"
12 #include "EventDistributor.hh"
13 #include "CliComm.hh"
14 #include "Timer.hh"
15 #include "StringOp.hh"
16 #include "memory.hh"
17 #include "sha1.hh"
18 #include "stl.hh"
19 #include <fstream>
20 #include <cassert>
21 
22 using std::ifstream;
23 using std::get;
24 using std::make_tuple;
25 using std::ofstream;
26 using std::pair;
27 using std::string;
28 using std::vector;
29 using std::unique_ptr;
30 
31 namespace openmsx {
32 
33 const char* const FILE_CACHE = "/.filecache";
34 
35 static string initialFilePoolSettingValue()
36 {
37  TclObject result;
38 
39  for (auto& p : SystemFileContext().getPaths()) {
40  TclObject entry1;
41  entry1.addListElement("-path");
42  entry1.addListElement(FileOperations::join(p, "systemroms"));
43  entry1.addListElement("-types");
44  entry1.addListElement("system_rom");
45  result.addListElement(entry1);
46 
47  TclObject entry2;
48  entry2.addListElement("-path");
49  entry2.addListElement(FileOperations::join(p, "software"));
50  entry2.addListElement("-types");
51  entry2.addListElement("rom disk tape");
52  result.addListElement(entry2);
53  }
54  return result.getString().str();
55 }
56 
58  : filePoolSetting(make_unique<StringSetting>(
59  controller, "__filepool",
60  "This is an internal setting. Don't change this directly, "
61  "instead use the 'filepool' command.",
62  initialFilePoolSettingValue()))
63  , distributor(distributor_)
64  , cliComm(controller.getCliComm())
65  , quit(false)
66 {
67  filePoolSetting->attach(*this);
68  distributor.registerEventListener(OPENMSX_QUIT_EVENT, *this);
69  readSha1sums();
70  needWrite = false;
71 }
72 
74 {
75  if (needWrite) {
76  writeSha1sums();
77  }
78  distributor.unregisterEventListener(OPENMSX_QUIT_EVENT, *this);
79  filePoolSetting->detach(*this);
80 }
81 
82 void FilePool::insert(const Sha1Sum& sum, time_t time, const string& filename)
83 {
84  auto it = upper_bound(begin(pool), end(pool), sum,
86  pool.insert(it, make_tuple(sum, time, filename));
87  needWrite = true;
88 }
89 
90 void FilePool::remove(Pool::iterator it)
91 {
92  pool.erase(it);
93  needWrite = true;
94 }
95 
96 // Change the sha1sum of the element pointed to by 'it' into 'newSum'.
97 // Also re-arrange the items so that pool remains sorted on sha1sum. Internally
98 // this method doesn't actually sort, it merely rotates the elements.
99 // Returns false if the new position is before (or at) the old position.
100 // Returns true if the new position is after the old position.
101 bool FilePool::adjust(Pool::iterator it, const Sha1Sum& newSum)
102 {
103  needWrite = true;
104  auto newIt = upper_bound(begin(pool), end(pool), newSum,
106  get<0>(*it) = newSum; // update sum
107  if (newIt > it) {
108  // move to back
109  rotate(it, it + 1, newIt);
110  return true;
111  } else {
112  if (newIt < it) {
113  // move to front
114  rotate(newIt, it, it + 1);
115  } else {
116  // (unlikely) sha1sum has changed, but after
117  // resorting item would remain in the same
118  // position
119  }
120  return false;
121  }
122 }
123 
124 static bool parse(const string& line, Sha1Sum& sha1, time_t& time, string& filename)
125 {
126  if (line.size() <= 68) return false;
127 
128  try {
129  sha1.parse40(line.data());
130  } catch (MSXException& /*e*/) {
131  return false;
132  }
133 
134  time = Date::fromString(line.data() + 42);
135  if (time == time_t(-1)) return false;
136 
137  filename.assign(line, 68, line.size());
138  return true;
139 }
140 
141 void FilePool::readSha1sums()
142 {
143  assert(pool.empty());
144 
145  string cacheFile = FileOperations::getUserDataDir() + FILE_CACHE;
146  ifstream file(cacheFile.c_str());
147  string line;
148  Sha1Sum sum;
149  string filename;
150  time_t time;
151  while (file.good()) {
152  getline(file, line);
153  if (parse(line, sum, time, filename)) {
154  pool.emplace_back(sum, time, filename);
155  }
156  }
157 
158  if (!std::is_sorted(begin(pool), end(pool), LessTupleElement<0>())) {
159  // This should _rarely_ happen. In fact it should only happen
160  // when .filecache was manually edited. Though because it's
161  // very important that pool is indeed sorted I've added this
162  // safety mechanism.
163  sort(begin(pool), end(pool), LessTupleElement<0>());
164  }
165 }
166 
167 void FilePool::writeSha1sums()
168 {
169  string cacheFile = FileOperations::getUserDataDir() + FILE_CACHE;
170  ofstream file;
171  FileOperations::openofstream(file, cacheFile);
172  if (!file.is_open()) {
173  return;
174  }
175  for (auto& p : pool) {
176  file << get<0>(p).toString() << " " // sum
177  << Date::toString(get<1>(p)) << " " // date
178  << get<2>(p) // filename
179  << '\n';
180  }
181 }
182 
183 static int parseTypes(Interpreter& interp, const TclObject& list)
184 {
185  int result = 0;
186  unsigned num = list.getListLength(interp);
187  for (unsigned i = 0; i < num; ++i) {
188  string_ref elem = list.getListIndex(interp, i).getString();
189  if (elem == "system_rom") {
190  result |= FilePool::SYSTEM_ROM;
191  } else if (elem == "rom") {
192  result |= FilePool::ROM;
193  } else if (elem == "disk") {
194  result |= FilePool::DISK;
195  } else if (elem == "tape") {
196  result |= FilePool::TAPE;
197  } else {
198  throw CommandException("Unknown type: " + elem);
199  }
200  }
201  return result;
202 }
203 
204 void FilePool::update(const Setting& setting)
205 {
206  assert(&setting == filePoolSetting.get()); (void)setting;
207  getDirectories(); // check for syntax errors
208 }
209 
210 FilePool::Directories FilePool::getDirectories() const
211 {
212  Directories result;
213  auto& interp = filePoolSetting->getInterpreter();
214  const TclObject& all = filePoolSetting->getValue();
215  unsigned numLines = all.getListLength(interp);
216  for (unsigned i = 0; i < numLines; ++i) {
217  Entry entry;
218  bool hasPath = false;
219  entry.types = 0;
220  TclObject line = all.getListIndex(interp, i);
221  unsigned numItems = line.getListLength(interp);
222  if (numItems & 1) {
223  throw CommandException(
224  "Expected a list with an even number "
225  "of elements, but got " + line.getString());
226  }
227  for (unsigned j = 0; j < numItems; j += 2) {
228  string_ref name = line.getListIndex(interp, j + 0).getString();
229  TclObject value = line.getListIndex(interp, j + 1);
230  if (name == "-path") {
231  entry.path = value.getString().str();
232  hasPath = true;
233  } else if (name == "-types") {
234  entry.types = parseTypes(interp, value);
235  } else {
236  throw CommandException(
237  "Unknown item: " + name);
238  }
239  }
240  if (!hasPath) {
241  throw CommandException(
242  "Missing -path item: " + line.getString());
243  }
244  if (entry.types == 0) {
245  throw CommandException(
246  "Missing -types item: " + line.getString());
247  }
248  result.push_back(entry);
249  }
250  return result;
251 }
252 
253 unique_ptr<File> FilePool::getFile(FileType fileType, const Sha1Sum& sha1sum)
254 {
255  unique_ptr<File> result;
256  result = getFromPool(sha1sum);
257  if (result) return result;
258 
259  // not found in cache, need to scan directories
260  ScanProgress progress;
261  progress.lastTime = Timer::getTime();
262  progress.amountScanned = 0;
263 
264  Directories directories;
265  try {
266  directories = getDirectories();
267  } catch (CommandException& e) {
268  cliComm.printWarning("Error while parsing '__filepool' setting" +
269  e.getMessage());
270  }
271  for (auto& d : directories) {
272  if (d.types & fileType) {
273  string path = FileOperations::expandTilde(d.path);
274  result = scanDirectory(sha1sum, path, d.path, progress);
275  if (result) return result;
276  }
277  }
278 
279  return result; // not found
280 }
281 
282 static void reportProgress(const string& filename, size_t percentage,
283  CliComm& cliComm, EventDistributor& distributor)
284 {
285  cliComm.printProgress(
286  "Calculating SHA1 sum for " + filename + "... " + StringOp::toString(percentage) + "%");
287  distributor.deliverEvents();
288 }
289 
290 static Sha1Sum calcSha1sum(File& file, CliComm& cliComm, EventDistributor& distributor)
291 {
292  size_t size;
293  const byte* data = file.mmap(size);
294 
295  if (size < 10*1024*1024) {
296  // for small files, don't show progress
297  return SHA1::calc(data, size);
298  }
299 
300  // Calculate sha1 in several steps so that we can show progress information
301  SHA1 sha1;
302  static const size_t NUMBER_OF_STEPS = 100;
303  // calculate in NUMBER_OF_STEPS steps and report progress every step
304  auto stepSize = size / NUMBER_OF_STEPS;
305  auto remainder = size % NUMBER_OF_STEPS;
306  size_t offset = 0;
307  string filename = file.getOriginalName();
308  reportProgress(filename, 0, cliComm, distributor);
309  for (size_t i = 0; i < (NUMBER_OF_STEPS - 1); ++i) {
310  sha1.update(&data[offset], stepSize);
311  offset += stepSize;
312  reportProgress(filename, i + 1, cliComm, distributor);
313  }
314  sha1.update(data + offset, stepSize + remainder);
315  reportProgress(filename, 100, cliComm, distributor);
316  return sha1.digest();
317 }
318 
319 unique_ptr<File> FilePool::getFromPool(const Sha1Sum& sha1sum)
320 {
321  auto bound = equal_range(begin(pool), end(pool), sha1sum,
323  // use indices instead of iterators
324  auto i = distance(begin(pool), bound.first);
325  auto last = distance(begin(pool), bound.second);
326  while (i != last) {
327  auto it = begin(pool) + i;
328  auto& time = get<1>(*it);
329  const auto& filename = get<2>(*it);
330  try {
331  auto file = make_unique<File>(filename);
332  auto newTime = file->getModificationDate();
333  if (time == newTime) {
334  // When modification time is unchanged, assume
335  // sha1sum is also unchanged. So avoid
336  // expensive sha1sum calculation.
337  return file;
338  }
339  time = newTime; // update timestamp
340  needWrite = true;
341  auto newSum = calcSha1sum(*file, cliComm, distributor);
342  if (newSum == sha1sum) {
343  // Modification time was changed, but
344  // (recalculated) sha1sum is still the same.
345  return file;
346  }
347  // Sha1sum has changed: update sha1sum, move entry to
348  // new position new sum and continue searching.
349  if (adjust(it, newSum)) {
350  // after
351  --last; // no ++i
352  } else {
353  // before (or at)
354  ++i;
355  }
356  } catch (FileException&) {
357  // Error reading file: remove from db and continue
358  // searching.
359  remove(it);
360  --last;
361  }
362  }
363  return nullptr; // not found
364 }
365 
366 unique_ptr<File> FilePool::scanDirectory(
367  const Sha1Sum& sha1sum, const string& directory, const string& poolPath,
368  ScanProgress& progress)
369 {
370  ReadDir dir(directory);
371  while (dirent* d = dir.getEntry()) {
372  if (quit) {
373  // Scanning can take a long time. Allow to exit
374  // openmsx when it takes too long. Stop scanning
375  // by pretending we didn't find the file.
376  return nullptr;
377  }
378  string file = d->d_name;
379  string path = directory + '/' + file;
381  if (FileOperations::getStat(path, st)) {
382  unique_ptr<File> result;
384  result = scanFile(sha1sum, path, st, poolPath, progress);
385  } else if (FileOperations::isDirectory(st)) {
386  if ((file != ".") && (file != "..")) {
387  result = scanDirectory(sha1sum, path, poolPath, progress);
388  }
389  }
390  if (result) return result;
391  }
392  }
393  return nullptr; // not found
394 }
395 
396 unique_ptr<File> FilePool::scanFile(const Sha1Sum& sha1sum, const string& filename,
397  const FileOperations::Stat& st, const string& poolPath,
398  ScanProgress& progress)
399 {
400  ++progress.amountScanned;
401  // Periodically send a progress message with the current filename
402  auto now = Timer::getTime();
403  if (now > (progress.lastTime + 250000)) { // 4Hz
404  progress.lastTime = now;
405  cliComm.printProgress("Searching for file with sha1sum " +
406  sha1sum.toString() + "...\nIndexing filepool " + poolPath +
407  ": [" + StringOp::toString(progress.amountScanned) + "]: " +
408  filename.substr(poolPath.size()));
409  }
410 
411  // deliverEvents() is relatively cheap when there are no events to
412  // deliver, so it's ok to call on each file.
413  distributor.deliverEvents();
414 
415  auto it = findInDatabase(filename);
416  if (it == end(pool)) {
417  // not in pool
418  try {
419  auto file = make_unique<File>(filename);
420  auto sum = calcSha1sum(*file, cliComm, distributor);
421  auto time = FileOperations::getModificationDate(st);
422  insert(sum, time, filename);
423  if (sum == sha1sum) {
424  return file;
425  }
426  } catch (FileException&) {
427  // ignore
428  }
429  } else {
430  // already in pool
431  assert(filename == get<2>(*it));
432  try {
433  auto time = FileOperations::getModificationDate(st);
434  if (time == get<1>(*it)) {
435  // db is still up to date
436  if (get<0>(*it) == sha1sum) {
437  return make_unique<File>(filename);
438  }
439  } else {
440  // db outdated
441  auto file = make_unique<File>(filename);
442  auto sum = calcSha1sum(*file, cliComm, distributor);
443  get<1>(*it) = time;
444  adjust(it, sum);
445  if (sum == sha1sum) {
446  return file;
447  }
448  }
449  } catch (FileException&) {
450  // error reading file, remove from db
451  remove(it);
452  }
453  }
454  return nullptr; // not found
455 }
456 
457 FilePool::Pool::iterator FilePool::findInDatabase(const string& filename)
458 {
459  // Linear search in pool for filename.
460  // Search from back to front because often, soon after this search, we
461  // will insert/remove an element from the vector. This requires
462  // shifting all elements in the vector starting from a certain
463  // position. Starting the search from the back increases the likelihood
464  // that the to-be-shifted elements are already in the memory cache.
465  for (auto it = pool.rbegin(); it != pool.rend(); ++it) {
466  if (get<2>(*it) == filename) {
467  return it.base() - 1;
468  }
469  }
470  return end(pool); // not found
471 }
472 
474 {
475  auto time = file.getModificationDate();
476  const auto& filename = file.getURL();
477 
478  auto it = findInDatabase(filename);
479  if ((it != end(pool)) && (get<1>(*it) == time)) {
480  // in database and modification time matches,
481  // assume sha1sum also matches
482  return get<0>(*it);
483  }
484 
485  // not in database or timestamp mismatch
486  auto sum = calcSha1sum(file, cliComm, distributor);
487  if (it == end(pool)) {
488  // was not yet in database, insert new entry
489  insert(sum, time, filename);
490  } else {
491  // was already in database, but with wrong timestamp (and sha1sum)
492  get<1>(*it) = time;
493  adjust(it, sum);
494  }
495  return sum;
496 }
497 
499 {
500  auto it = findInDatabase(file.getURL());
501  if (it != end(pool)) {
502  remove(it);
503  }
504 }
505 
506 int FilePool::signalEvent(const std::shared_ptr<const Event>& event)
507 {
508  (void)event; // avoid warning for non-assert compiles
509  assert(event->getType() == OPENMSX_QUIT_EVENT);
510  quit = true;
511  return 0;
512 }
513 
514 } // namespace openmsx
signed char offset
Definition: CPUCore.cc:252
bool isRegularFile(const Stat &st)
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:135
std::string str() const
Definition: string_ref.cc:10
void removeSha1Sum(File &file)
Remove sha1sum for this file from the cache.
Definition: FilePool.cc:498
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
string_ref getString() const
Definition: TclObject.cc:180
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
string toString(long long a)
Definition: StringOp.cc:155
void openofstream(std::ofstream &stream, const std::string &filename)
Open an ofstream in a platform-independent manner.
unsigned char byte
8 bit unsigned integer
Definition: openmsx.hh:33
std::unique_ptr< File > getFile(FileType fileType, const Sha1Sum &sha1sum)
Search file with the given sha1sum.
Definition: FilePool.cc:253
void printWarning(string_ref message)
Definition: CliComm.cc:28
string join(string_ref part1, string_ref part2)
Join two paths.
static Sha1Sum calc(const uint8_t *data, size_t len)
Easier to use interface, if you can pass all data in one go.
Definition: sha1.cc:281
This class implements a subset of the proposal for std::string_ref (proposed for the next c++ standar...
Definition: string_ref.hh:18
T sum(const vecN< N, T > &x)
Definition: gl_vec.hh:248
void deliverEvents()
This actually delivers the events.
bool getStat(string_ref filename_, Stat &st)
Call stat() and return the stat structure.
This class represents the result of a sha1 calculation (a 160-bit value).
Definition: sha1.hh:19
const std::string & getMessage() const
Definition: MSXException.hh:14
string getUserDataDir()
Get the openMSX data dir in the user's home directory.
time_t getModificationDate()
Get the date/time of last modification.
Definition: File.cc:137
std::string toString(time_t time)
Definition: Date.cc:152
std::iterator_traits< octet_iterator >::difference_type distance(octet_iterator first, octet_iterator last)
FilePool(CommandController &controler, EventDistributor &distributor)
Definition: FilePool.cc:57
void addListElement(string_ref element)
Definition: TclObject.cc:110
bool isDirectory(const Stat &st)
const char *const FILE_CACHE
Definition: FilePool.cc:33
void printProgress(string_ref message)
Definition: CliComm.cc:38
uint8_t * data()
Sha1Sum getSha1Sum(File &file)
Calculate sha1sum for the given File object.
Definition: FilePool.cc:473
const std::string getURL() const
Returns the URL of this file object.
Definition: File.cc:116
time_t fromString(const char *p)
Definition: Date.cc:31
size_t size() const
string expandTilde(string_ref path)
Expand the '~' character to the users home directory.
uint64_t getTime()
Get current (real) time in us.
Definition: Timer.cc:24
mat4 rotate(float angle, const vec3 &axis)
Definition: gl_transform.hh:56
string_ref::const_iterator begin(const string_ref &x)
Definition: string_ref.hh:134
std::unique_ptr< T > make_unique()
Definition: memory.hh:27
time_t getModificationDate(const Stat &st)
Get the date/time of last modification.