1
0

Scanner.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Utils;
  8. use OC\Files\Cache\Cache;
  9. use OC\Files\Filesystem;
  10. use OC\Files\Storage\FailedStorage;
  11. use OC\Files\Storage\Home;
  12. use OC\ForbiddenException;
  13. use OC\Hooks\PublicEmitter;
  14. use OC\Lock\DBLockingProvider;
  15. use OCA\Files_Sharing\SharedStorage;
  16. use OCP\EventDispatcher\IEventDispatcher;
  17. use OCP\Files\Events\BeforeFileScannedEvent;
  18. use OCP\Files\Events\BeforeFolderScannedEvent;
  19. use OCP\Files\Events\FileCacheUpdated;
  20. use OCP\Files\Events\FileScannedEvent;
  21. use OCP\Files\Events\FolderScannedEvent;
  22. use OCP\Files\Events\NodeAddedToCache;
  23. use OCP\Files\Events\NodeRemovedFromCache;
  24. use OCP\Files\NotFoundException;
  25. use OCP\Files\Storage\IStorage;
  26. use OCP\Files\StorageNotAvailableException;
  27. use OCP\IDBConnection;
  28. use OCP\Lock\ILockingProvider;
  29. use Psr\Log\LoggerInterface;
  30. /**
  31. * Class Scanner
  32. *
  33. * Hooks available in scope \OC\Utils\Scanner
  34. * - scanFile(string $absolutePath)
  35. * - scanFolder(string $absolutePath)
  36. *
  37. * @package OC\Files\Utils
  38. */
  39. class Scanner extends PublicEmitter {
  40. public const MAX_ENTRIES_TO_COMMIT = 10000;
  41. /** @var string $user */
  42. private $user;
  43. /** @var IDBConnection */
  44. protected $db;
  45. /** @var IEventDispatcher */
  46. private $dispatcher;
  47. protected LoggerInterface $logger;
  48. /**
  49. * Whether to use a DB transaction
  50. *
  51. * @var bool
  52. */
  53. protected $useTransaction;
  54. /**
  55. * Number of entries scanned to commit
  56. *
  57. * @var int
  58. */
  59. protected $entriesToCommit;
  60. /**
  61. * @param string $user
  62. * @param IDBConnection|null $db
  63. * @param IEventDispatcher $dispatcher
  64. */
  65. public function __construct($user, $db, IEventDispatcher $dispatcher, LoggerInterface $logger) {
  66. $this->user = $user;
  67. $this->db = $db;
  68. $this->dispatcher = $dispatcher;
  69. $this->logger = $logger;
  70. // when DB locking is used, no DB transactions will be used
  71. $this->useTransaction = !(\OC::$server->get(ILockingProvider::class) instanceof DBLockingProvider);
  72. }
  73. /**
  74. * get all storages for $dir
  75. *
  76. * @param string $dir
  77. * @return \OC\Files\Mount\MountPoint[]
  78. */
  79. protected function getMounts($dir) {
  80. //TODO: move to the node based fileapi once that's done
  81. \OC_Util::tearDownFS();
  82. \OC_Util::setupFS($this->user);
  83. $mountManager = Filesystem::getMountManager();
  84. $mounts = $mountManager->findIn($dir);
  85. $mounts[] = $mountManager->find($dir);
  86. $mounts = array_reverse($mounts); //start with the mount of $dir
  87. return $mounts;
  88. }
  89. /**
  90. * attach listeners to the scanner
  91. *
  92. * @param \OC\Files\Mount\MountPoint $mount
  93. */
  94. protected function attachListener($mount) {
  95. $scanner = $mount->getStorage()->getScanner();
  96. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
  97. $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
  98. $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
  99. });
  100. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
  101. $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
  102. $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
  103. });
  104. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
  105. $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
  106. $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
  107. });
  108. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
  109. $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
  110. $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
  111. });
  112. $scanner->listen('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', function ($path) use ($mount) {
  113. $this->emit('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', [$path]);
  114. });
  115. }
  116. /**
  117. * @param string $dir
  118. */
  119. public function backgroundScan($dir) {
  120. $mounts = $this->getMounts($dir);
  121. foreach ($mounts as $mount) {
  122. try {
  123. $storage = $mount->getStorage();
  124. if (is_null($storage)) {
  125. continue;
  126. }
  127. // don't bother scanning failed storages (shortcut for same result)
  128. if ($storage->instanceOfStorage(FailedStorage::class)) {
  129. continue;
  130. }
  131. $scanner = $storage->getScanner();
  132. $this->attachListener($mount);
  133. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  134. $this->triggerPropagator($storage, $path);
  135. });
  136. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  137. $this->triggerPropagator($storage, $path);
  138. });
  139. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  140. $this->triggerPropagator($storage, $path);
  141. });
  142. $propagator = $storage->getPropagator();
  143. $propagator->beginBatch();
  144. $scanner->backgroundScan();
  145. $propagator->commitBatch();
  146. } catch (\Exception $e) {
  147. $this->logger->error("Error while trying to scan mount as {$mount->getMountPoint()}:" . $e->getMessage(), ['exception' => $e, 'app' => 'files']);
  148. }
  149. }
  150. }
  151. /**
  152. * @param string $dir
  153. * @param $recursive
  154. * @param callable|null $mountFilter
  155. * @throws ForbiddenException
  156. * @throws NotFoundException
  157. */
  158. public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, ?callable $mountFilter = null) {
  159. if (!Filesystem::isValidPath($dir)) {
  160. throw new \InvalidArgumentException('Invalid path to scan');
  161. }
  162. $mounts = $this->getMounts($dir);
  163. foreach ($mounts as $mount) {
  164. if ($mountFilter && !$mountFilter($mount)) {
  165. continue;
  166. }
  167. $storage = $mount->getStorage();
  168. if (is_null($storage)) {
  169. continue;
  170. }
  171. // don't bother scanning failed storages (shortcut for same result)
  172. if ($storage->instanceOfStorage(FailedStorage::class)) {
  173. continue;
  174. }
  175. // if the home storage isn't writable then the scanner is run as the wrong user
  176. if ($storage->instanceOfStorage(Home::class)) {
  177. /** @var Home $storage */
  178. foreach (['', 'files'] as $path) {
  179. if (!$storage->isCreatable($path)) {
  180. $fullPath = $storage->getSourcePath($path);
  181. if (!$storage->is_dir($path) && $storage->getCache()->inCache($path)) {
  182. throw new NotFoundException("User folder $fullPath exists in cache but not on disk");
  183. } elseif ($storage->is_dir($path)) {
  184. $ownerUid = fileowner($fullPath);
  185. $owner = posix_getpwuid($ownerUid);
  186. $owner = $owner['name'] ?? $ownerUid;
  187. $permissions = decoct(fileperms($fullPath));
  188. throw new ForbiddenException("User folder $fullPath is not writable, folders is owned by $owner and has mode $permissions");
  189. } else {
  190. // if the root exists in neither the cache nor the storage the user isn't setup yet
  191. break 2;
  192. }
  193. }
  194. }
  195. }
  196. // don't scan received local shares, these can be scanned when scanning the owner's storage
  197. if ($storage->instanceOfStorage(SharedStorage::class)) {
  198. continue;
  199. }
  200. $relativePath = $mount->getInternalPath($dir);
  201. $scanner = $storage->getScanner();
  202. $scanner->setUseTransactions(false);
  203. $this->attachListener($mount);
  204. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  205. $this->postProcessEntry($storage, $path);
  206. $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
  207. });
  208. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  209. $this->postProcessEntry($storage, $path);
  210. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  211. });
  212. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path, $storageId, $data, $fileId) use ($storage) {
  213. $this->postProcessEntry($storage, $path);
  214. if ($fileId) {
  215. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  216. } else {
  217. $this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
  218. }
  219. });
  220. if (!$storage->file_exists($relativePath)) {
  221. throw new NotFoundException($dir);
  222. }
  223. if ($this->useTransaction) {
  224. $this->db->beginTransaction();
  225. }
  226. try {
  227. $propagator = $storage->getPropagator();
  228. $propagator->beginBatch();
  229. $scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
  230. $cache = $storage->getCache();
  231. if ($cache instanceof Cache) {
  232. // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
  233. $cache->correctFolderSize($relativePath);
  234. }
  235. $propagator->commitBatch();
  236. } catch (StorageNotAvailableException $e) {
  237. $this->logger->error('Storage ' . $storage->getId() . ' not available', ['exception' => $e]);
  238. $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
  239. }
  240. if ($this->useTransaction) {
  241. $this->db->commit();
  242. }
  243. }
  244. }
  245. private function triggerPropagator(IStorage $storage, $internalPath) {
  246. $storage->getPropagator()->propagateChange($internalPath, time());
  247. }
  248. private function postProcessEntry(IStorage $storage, $internalPath) {
  249. $this->triggerPropagator($storage, $internalPath);
  250. if ($this->useTransaction) {
  251. $this->entriesToCommit++;
  252. if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
  253. $propagator = $storage->getPropagator();
  254. $this->entriesToCommit = 0;
  255. $this->db->commit();
  256. $propagator->commitBatch();
  257. $this->db->beginTransaction();
  258. $propagator->beginBatch();
  259. }
  260. }
  261. }
  262. }