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