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(pool.begin(), pool.end(), 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(pool.begin(), pool.end(), 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(pool.begin(), pool.end(), 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(pool.begin(), pool.end(), 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(const TclObject& list)
184 {
185  int result = 0;
186  unsigned num = list.getListLength();
187  for (unsigned i = 0; i < num; ++i) {
188  string_ref elem = list.getListIndex(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  const TclObject& all = filePoolSetting->getValue();
214  unsigned numLines = all.getListLength();
215  for (unsigned i = 0; i < numLines; ++i) {
216  Entry entry;
217  bool hasPath = false;
218  entry.types = 0;
219  TclObject line = all.getListIndex(i);
220  unsigned numItems = line.getListLength();
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(j + 0).getString();
228  TclObject value = line.getListIndex(j + 1);
229  if (name == "-path") {
230  entry.path = value.getString().str();
231  hasPath = true;
232  } else if (name == "-types") {
233  entry.types = parseTypes(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 unique_ptr<File> FilePool::getFile(FileType fileType, const Sha1Sum& sha1sum)
253 {
254  unique_ptr<File> result;
255  result = getFromPool(sha1sum);
256  if (result) return result;
257 
258  // not found in cache, need to scan directories
259  ScanProgress progress;
260  progress.lastTime = Timer::getTime();
261  progress.amountScanned = 0;
262 
263  Directories directories;
264  try {
265  directories = getDirectories();
266  } catch (CommandException& e) {
267  cliComm.printWarning("Error while parsing '__filepool' setting" +
268  e.getMessage());
269  }
270  for (auto& d : directories) {
271  if (d.types & fileType) {
272  string path = FileOperations::expandTilde(d.path);
273  result = scanDirectory(sha1sum, path, d.path, progress);
274  if (result) return result;
275  }
276  }
277 
278  return result; // not found
279 }
280 
281 static Sha1Sum calcSha1sum(File& file, CliComm& cliComm, EventDistributor& distributor)
282 {
283  size_t size;
284  const byte* data = file.mmap(size);
285  return SHA1::calcWithProgress(data, size, file.getOriginalName(), cliComm, distributor);
286 }
287 
288 unique_ptr<File> FilePool::getFromPool(const Sha1Sum& sha1sum)
289 {
290  auto bound = equal_range(pool.begin(), pool.end(), sha1sum,
292  // use indices instead of iterators
293  auto i = distance(pool.begin(), bound.first);
294  auto last = distance(pool.begin(), bound.second);
295  while (i != last) {
296  auto it = pool.begin() + i;
297  auto& time = get<1>(*it);
298  const auto& filename = get<2>(*it);
299  try {
300  auto file = make_unique<File>(filename);
301  auto newTime = file->getModificationDate();
302  if (time == newTime) {
303  // When modification time is unchanged, assume
304  // sha1sum is also unchanged. So avoid
305  // expensive sha1sum calculation.
306  return file;
307  }
308  time = newTime; // update timestamp
309  needWrite = true;
310  auto newSum = calcSha1sum(*file, cliComm, distributor);
311  if (newSum == sha1sum) {
312  // Modification time was changed, but
313  // (recalculated) sha1sum is still the same.
314  return file;
315  }
316  // Sha1sum has changed: update sha1sum, move entry to
317  // new position new sum and continue searching.
318  if (adjust(it, newSum)) {
319  // after
320  --last; // no ++i
321  } else {
322  // before (or at)
323  ++i;
324  }
325  } catch (FileException&) {
326  // Error reading file: remove from db and continue
327  // searching.
328  remove(it);
329  --last;
330  }
331  }
332  return nullptr; // not found
333 }
334 
335 unique_ptr<File> FilePool::scanDirectory(
336  const Sha1Sum& sha1sum, const string& directory, const string& poolPath,
337  ScanProgress& progress)
338 {
339  ReadDir dir(directory);
340  while (dirent* d = dir.getEntry()) {
341  if (quit) {
342  // Scanning can take a long time. Allow to exit
343  // openmsx when it takes too long. Stop scanning
344  // by pretending we didn't find the file.
345  return nullptr;
346  }
347  string file = d->d_name;
348  string path = directory + '/' + file;
350  if (FileOperations::getStat(path, st)) {
351  unique_ptr<File> result;
353  result = scanFile(sha1sum, path, st, poolPath, progress);
354  } else if (FileOperations::isDirectory(st)) {
355  if ((file != ".") && (file != "..")) {
356  result = scanDirectory(sha1sum, path, poolPath, progress);
357  }
358  }
359  if (result) return result;
360  }
361  }
362  return nullptr; // not found
363 }
364 
365 unique_ptr<File> FilePool::scanFile(const Sha1Sum& sha1sum, const string& filename,
366  const FileOperations::Stat& st, const string& poolPath,
367  ScanProgress& progress)
368 {
369  ++progress.amountScanned;
370  // Periodically send a progress message with the current filename
371  auto now = Timer::getTime();
372  if (now > (progress.lastTime + 250000)) { // 4Hz
373  progress.lastTime = now;
374  cliComm.printProgress("Searching for file with sha1sum " +
375  sha1sum.toString() + "...\nIndexing filepool " + poolPath +
376  ": [" + StringOp::toString(progress.amountScanned) + "]: " +
377  filename.substr(poolPath.size()));
378  }
379 
380  // deliverEvents() is relatively cheap when there are no events to
381  // deliver, so it's ok to call on each file.
382  distributor.deliverEvents();
383 
384  auto it = findInDatabase(filename);
385  if (it == pool.end()) {
386  // not in pool
387  try {
388  auto file = make_unique<File>(filename);
389  auto sum = calcSha1sum(*file, cliComm, distributor);
390  auto time = FileOperations::getModificationDate(st);
391  insert(sum, time, filename);
392  if (sum == sha1sum) {
393  return file;
394  }
395  } catch (FileException&) {
396  // ignore
397  }
398  } else {
399  // already in pool
400  assert(filename == get<2>(*it));
401  try {
402  auto time = FileOperations::getModificationDate(st);
403  if (time == get<1>(*it)) {
404  // db is still up to date
405  if (get<0>(*it) == sha1sum) {
406  return make_unique<File>(filename);
407  }
408  } else {
409  // db outdated
410  auto file = make_unique<File>(filename);
411  auto sum = calcSha1sum(*file, cliComm, distributor);
412  get<1>(*it) = time;
413  adjust(it, sum);
414  if (sum == sha1sum) {
415  return file;
416  }
417  }
418  } catch (FileException&) {
419  // error reading file, remove from db
420  remove(it);
421  }
422  }
423  return nullptr; // not found
424 }
425 
426 FilePool::Pool::iterator FilePool::findInDatabase(const string& filename)
427 {
428  // Linear search in pool for filename.
429  // Search from back to front because often, soon after this search, we
430  // will insert/remove an element from the vector. This requires
431  // shifting all elements in the vector starting from a certain
432  // position. Starting the search from the back increases the likelihood
433  // that the to-be-shifted elements are already in the memory cache.
434  for (auto it = pool.rbegin(); it != pool.rend(); ++it) {
435  if (get<2>(*it) == filename) {
436  return it.base() - 1;
437  }
438  }
439  return pool.end(); // not found
440 }
441 
443 {
444  auto time = file.getModificationDate();
445  const auto& filename = file.getURL();
446 
447  auto it = findInDatabase(filename);
448  if ((it != pool.end()) && (get<1>(*it) == time)) {
449  // in database and modification time matches,
450  // assume sha1sum also matches
451  return get<0>(*it);
452  }
453 
454  // not in database or timestamp mismatch
455  auto sum = calcSha1sum(file, cliComm, distributor);
456  if (it == pool.end()) {
457  // was not yet in database, insert new entry
458  insert(sum, time, filename);
459  } else {
460  // was already in database, but with wrong timestamp (and sha1sum)
461  get<1>(*it) = time;
462  adjust(it, sum);
463  }
464  return sum;
465 }
466 
468 {
469  auto it = findInDatabase(file.getURL());
470  if (it != pool.end()) {
471  remove(it);
472  }
473 }
474 
475 int FilePool::signalEvent(const std::shared_ptr<const Event>& event)
476 {
477  (void)event; // avoid warning for non-assert compiles
478  assert(event->getType() == OPENMSX_QUIT_EVENT);
479  quit = true;
480  return 0;
481 }
482 
483 } // namespace openmsx
bool isRegularFile(const Stat &st)
std::string str() const
Definition: string_ref.cc:10
void removeSha1Sum(File &file)
Remove sha1sum for this file from the cache.
Definition: FilePool.cc:467
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
string_ref getString() const
Definition: TclObject.cc:213
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
string toString(long long a)
Definition: StringOp.cc:155
static Sha1Sum calcWithProgress(const uint8_t *data, size_t len, const std::string &filename, CliComm &cliComm, EventDistributor &distributor)
Easier to use interface, if you can pass all data in one go.
Definition: sha1.cc:300
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:252
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
bool getStat(const string &filename_, Stat &st)
Call stat() and return the stat structure.
void deliverEvents()
This actually delivers the events.
This class represents the result of a sha1 calculation (a 160-bit value).
Definition: sha1.hh:18
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)
const std::string getOriginalName()
Get Original filename for this object.
Definition: File.cc:126
FilePool(CommandController &controler, EventDistributor &distributor)
Definition: FilePool.cc:57
void addListElement(string_ref element)
Definition: TclObject.cc:154
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:442
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
const byte * mmap(size_t &size)
Map file in memory.
Definition: File.cc:81
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
std::unique_ptr< T > make_unique()
Definition: memory.hh:27
time_t getModificationDate(const Stat &st)
Get the date/time of last modification.