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  // Calculate sha1 in several steps so that we can show progress
291  // information. We take a fixed step size for an efficient calculation.
292  static const size_t STEP_SIZE = 1024 * 1024; // 1MB
293 
294  size_t size;
295  const byte* data = file.mmap(size);
296  string filename = file.getOriginalName();
297 
298  SHA1 sha1;
299  size_t done = 0;
300  size_t remaining = size;
301  auto lastShowedProgress = Timer::getTime();
302  bool everShowedProgress = false;
303 
304  // Loop over all-but-the last blocks. For small files this loop is skipped.
305  while (remaining > STEP_SIZE) {
306  sha1.update(&data[done], STEP_SIZE);
307  done += STEP_SIZE;
308  remaining -= STEP_SIZE;
309 
310  auto now = Timer::getTime();
311  if ((now - lastShowedProgress) > 1000000) {
312  reportProgress(filename, (100 * done) / size, cliComm, distributor);
313  lastShowedProgress = now;
314  everShowedProgress = true;
315  }
316  }
317  // last block
318  sha1.update(&data[done], remaining);
319  if (everShowedProgress) {
320  reportProgress(filename, 100, cliComm, distributor);
321  }
322  return sha1.digest();
323 }
324 
325 File FilePool::getFromPool(const Sha1Sum& sha1sum)
326 {
327  auto bound = equal_range(begin(pool), end(pool), sha1sum,
329  // use indices instead of iterators
330  auto i = distance(begin(pool), bound.first);
331  auto last = distance(begin(pool), bound.second);
332  while (i != last) {
333  auto it = begin(pool) + i;
334  auto& time = get<1>(*it);
335  const auto& filename = get<2>(*it);
336  try {
337  File file(filename);
338  auto newTime = file.getModificationDate();
339  if (time == newTime) {
340  // When modification time is unchanged, assume
341  // sha1sum is also unchanged. So avoid
342  // expensive sha1sum calculation.
343  return file;
344  }
345  time = newTime; // update timestamp
346  needWrite = true;
347  auto newSum = calcSha1sum(file, cliComm, distributor);
348  if (newSum == sha1sum) {
349  // Modification time was changed, but
350  // (recalculated) sha1sum is still the same.
351  return file;
352  }
353  // Sha1sum has changed: update sha1sum, move entry to
354  // new position new sum and continue searching.
355  if (adjust(it, newSum)) {
356  // after
357  --last; // no ++i
358  } else {
359  // before (or at)
360  ++i;
361  }
362  } catch (FileException&) {
363  // Error reading file: remove from db and continue
364  // searching.
365  remove(it);
366  --last;
367  }
368  }
369  return File(); // not found
370 }
371 
372 File FilePool::scanDirectory(
373  const Sha1Sum& sha1sum, const string& directory, const string& poolPath,
374  ScanProgress& progress)
375 {
376  ReadDir dir(directory);
377  while (dirent* d = dir.getEntry()) {
378  if (quit) {
379  // Scanning can take a long time. Allow to exit
380  // openmsx when it takes too long. Stop scanning
381  // by pretending we didn't find the file.
382  return File();
383  }
384  string file = d->d_name;
385  string path = directory + '/' + file;
387  if (FileOperations::getStat(path, st)) {
388  File result;
390  result = scanFile(sha1sum, path, st, poolPath, progress);
391  } else if (FileOperations::isDirectory(st)) {
392  if ((file != ".") && (file != "..")) {
393  result = scanDirectory(sha1sum, path, poolPath, progress);
394  }
395  }
396  if (result.is_open()) return result;
397  }
398  }
399  return File(); // not found
400 }
401 
402 File FilePool::scanFile(const Sha1Sum& sha1sum, const string& filename,
403  const FileOperations::Stat& st, const string& poolPath,
404  ScanProgress& progress)
405 {
406  ++progress.amountScanned;
407  // Periodically send a progress message with the current filename
408  auto now = Timer::getTime();
409  if (now > (progress.lastTime + 250000)) { // 4Hz
410  progress.lastTime = now;
411  cliComm.printProgress("Searching for file with sha1sum " +
412  sha1sum.toString() + "...\nIndexing filepool " + poolPath +
413  ": [" + StringOp::toString(progress.amountScanned) + "]: " +
414  filename.substr(poolPath.size()));
415  }
416 
417  // deliverEvents() is relatively cheap when there are no events to
418  // deliver, so it's ok to call on each file.
419  distributor.deliverEvents();
420 
421  auto it = findInDatabase(filename);
422  if (it == end(pool)) {
423  // not in pool
424  try {
425  File file(filename);
426  auto sum = calcSha1sum(file, cliComm, distributor);
427  auto time = FileOperations::getModificationDate(st);
428  insert(sum, time, filename);
429  if (sum == sha1sum) {
430  return file;
431  }
432  } catch (FileException&) {
433  // ignore
434  }
435  } else {
436  // already in pool
437  assert(filename == get<2>(*it));
438  try {
439  auto time = FileOperations::getModificationDate(st);
440  if (time == get<1>(*it)) {
441  // db is still up to date
442  if (get<0>(*it) == sha1sum) {
443  return File(filename);
444  }
445  } else {
446  // db outdated
447  File file(filename);
448  auto sum = calcSha1sum(file, cliComm, distributor);
449  get<1>(*it) = time;
450  adjust(it, sum);
451  if (sum == sha1sum) {
452  return file;
453  }
454  }
455  } catch (FileException&) {
456  // error reading file, remove from db
457  remove(it);
458  }
459  }
460  return File(); // not found
461 }
462 
463 FilePool::Pool::iterator FilePool::findInDatabase(const string& filename)
464 {
465  // Linear search in pool for filename.
466  // Search from back to front because often, soon after this search, we
467  // will insert/remove an element from the vector. This requires
468  // shifting all elements in the vector starting from a certain
469  // position. Starting the search from the back increases the likelihood
470  // that the to-be-shifted elements are already in the memory cache.
471  for (auto it = pool.rbegin(); it != pool.rend(); ++it) {
472  if (get<2>(*it) == filename) {
473  return it.base() - 1;
474  }
475  }
476  return end(pool); // not found
477 }
478 
480 {
481  auto time = file.getModificationDate();
482  const auto& filename = file.getURL();
483 
484  auto it = findInDatabase(filename);
485  if ((it != end(pool)) && (get<1>(*it) == time)) {
486  // in database and modification time matches,
487  // assume sha1sum also matches
488  return get<0>(*it);
489  }
490 
491  // not in database or timestamp mismatch
492  auto sum = calcSha1sum(file, cliComm, distributor);
493  if (it == end(pool)) {
494  // was not yet in database, insert new entry
495  insert(sum, time, filename);
496  } else {
497  // was already in database, but with wrong timestamp (and sha1sum)
498  get<1>(*it) = time;
499  adjust(it, sum);
500  }
501  return sum;
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 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.
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:162
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:479
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:133
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:8
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.