Scanner.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Blaok <i@blaok.me>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Olivier Paroz <github@oparoz.com>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <vincent@nextcloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Files\Utils;
  31. use OC\Files\Cache\Cache;
  32. use OC\Files\Filesystem;
  33. use OC\Files\Storage\FailedStorage;
  34. use OC\Files\Storage\Home;
  35. use OC\ForbiddenException;
  36. use OC\Hooks\PublicEmitter;
  37. use OC\Lock\DBLockingProvider;
  38. use OCA\Files_Sharing\SharedStorage;
  39. use OCP\EventDispatcher\IEventDispatcher;
  40. use OCP\Files\Events\BeforeFileScannedEvent;
  41. use OCP\Files\Events\BeforeFolderScannedEvent;
  42. use OCP\Files\Events\FileCacheUpdated;
  43. use OCP\Files\Events\FileScannedEvent;
  44. use OCP\Files\Events\FolderScannedEvent;
  45. use OCP\Files\Events\NodeAddedToCache;
  46. use OCP\Files\Events\NodeRemovedFromCache;
  47. use OCP\Files\NotFoundException;
  48. use OCP\Files\Storage\IStorage;
  49. use OCP\Files\StorageNotAvailableException;
  50. use OCP\IDBConnection;
  51. use Psr\Log\LoggerInterface;
  52. /**
  53. * Class Scanner
  54. *
  55. * Hooks available in scope \OC\Utils\Scanner
  56. * - scanFile(string $absolutePath)
  57. * - scanFolder(string $absolutePath)
  58. *
  59. * @package OC\Files\Utils
  60. */
  61. class Scanner extends PublicEmitter {
  62. public const MAX_ENTRIES_TO_COMMIT = 10000;
  63. /** @var string $user */
  64. private $user;
  65. /** @var IDBConnection */
  66. protected $db;
  67. /** @var IEventDispatcher */
  68. private $dispatcher;
  69. protected LoggerInterface $logger;
  70. /**
  71. * Whether to use a DB transaction
  72. *
  73. * @var bool
  74. */
  75. protected $useTransaction;
  76. /**
  77. * Number of entries scanned to commit
  78. *
  79. * @var int
  80. */
  81. protected $entriesToCommit;
  82. /**
  83. * @param string $user
  84. * @param IDBConnection|null $db
  85. * @param IEventDispatcher $dispatcher
  86. */
  87. public function __construct($user, $db, IEventDispatcher $dispatcher, LoggerInterface $logger) {
  88. $this->user = $user;
  89. $this->db = $db;
  90. $this->dispatcher = $dispatcher;
  91. $this->logger = $logger;
  92. // when DB locking is used, no DB transactions will be used
  93. $this->useTransaction = !(\OC::$server->getLockingProvider() instanceof DBLockingProvider);
  94. }
  95. /**
  96. * get all storages for $dir
  97. *
  98. * @param string $dir
  99. * @return \OC\Files\Mount\MountPoint[]
  100. */
  101. protected function getMounts($dir) {
  102. //TODO: move to the node based fileapi once that's done
  103. \OC_Util::tearDownFS();
  104. \OC_Util::setupFS($this->user);
  105. $mountManager = Filesystem::getMountManager();
  106. $mounts = $mountManager->findIn($dir);
  107. $mounts[] = $mountManager->find($dir);
  108. $mounts = array_reverse($mounts); //start with the mount of $dir
  109. return $mounts;
  110. }
  111. /**
  112. * attach listeners to the scanner
  113. *
  114. * @param \OC\Files\Mount\MountPoint $mount
  115. */
  116. protected function attachListener($mount) {
  117. $scanner = $mount->getStorage()->getScanner();
  118. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
  119. $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
  120. $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
  121. });
  122. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
  123. $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
  124. $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
  125. });
  126. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
  127. $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
  128. $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
  129. });
  130. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
  131. $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
  132. $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
  133. });
  134. $scanner->listen('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', function ($path) use ($mount) {
  135. $this->emit('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', [$path]);
  136. });
  137. }
  138. /**
  139. * @param string $dir
  140. */
  141. public function backgroundScan($dir) {
  142. $mounts = $this->getMounts($dir);
  143. foreach ($mounts as $mount) {
  144. try {
  145. $storage = $mount->getStorage();
  146. if (is_null($storage)) {
  147. continue;
  148. }
  149. // don't bother scanning failed storages (shortcut for same result)
  150. if ($storage->instanceOfStorage(FailedStorage::class)) {
  151. continue;
  152. }
  153. $scanner = $storage->getScanner();
  154. $this->attachListener($mount);
  155. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  156. $this->triggerPropagator($storage, $path);
  157. });
  158. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  159. $this->triggerPropagator($storage, $path);
  160. });
  161. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  162. $this->triggerPropagator($storage, $path);
  163. });
  164. $propagator = $storage->getPropagator();
  165. $propagator->beginBatch();
  166. $scanner->backgroundScan();
  167. $propagator->commitBatch();
  168. } catch (\Exception $e) {
  169. $this->logger->error("Error while trying to scan mount as {$mount->getMountPoint()}:" . $e->getMessage(), ['exception' => $e, 'app' => 'files']);
  170. }
  171. }
  172. }
  173. /**
  174. * @param string $dir
  175. * @param $recursive
  176. * @param callable|null $mountFilter
  177. * @throws ForbiddenException
  178. * @throws NotFoundException
  179. */
  180. public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, callable $mountFilter = null) {
  181. if (!Filesystem::isValidPath($dir)) {
  182. throw new \InvalidArgumentException('Invalid path to scan');
  183. }
  184. $mounts = $this->getMounts($dir);
  185. foreach ($mounts as $mount) {
  186. if ($mountFilter && !$mountFilter($mount)) {
  187. continue;
  188. }
  189. $storage = $mount->getStorage();
  190. if (is_null($storage)) {
  191. continue;
  192. }
  193. // don't bother scanning failed storages (shortcut for same result)
  194. if ($storage->instanceOfStorage(FailedStorage::class)) {
  195. continue;
  196. }
  197. // if the home storage isn't writable then the scanner is run as the wrong user
  198. if ($storage->instanceOfStorage(Home::class)) {
  199. /** @var Home $storage */
  200. foreach (['', 'files'] as $path) {
  201. if (!$storage->isCreatable($path)) {
  202. $fullPath = $storage->getSourcePath($path);
  203. if (!$storage->is_dir($path) && $storage->getCache()->inCache($path)) {
  204. throw new NotFoundException("User folder $fullPath exists in cache but not on disk");
  205. } elseif ($storage->is_dir($path)) {
  206. $ownerUid = fileowner($fullPath);
  207. $owner = posix_getpwuid($ownerUid);
  208. $owner = $owner['name'] ?? $ownerUid;
  209. $permissions = decoct(fileperms($fullPath));
  210. throw new ForbiddenException("User folder $fullPath is not writable, folders is owned by $owner and has mode $permissions");
  211. } else {
  212. // if the root exists in neither the cache nor the storage the user isn't setup yet
  213. break 2;
  214. }
  215. }
  216. }
  217. }
  218. // don't scan received local shares, these can be scanned when scanning the owner's storage
  219. if ($storage->instanceOfStorage(SharedStorage::class)) {
  220. continue;
  221. }
  222. $relativePath = $mount->getInternalPath($dir);
  223. $scanner = $storage->getScanner();
  224. $scanner->setUseTransactions(false);
  225. $this->attachListener($mount);
  226. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  227. $this->postProcessEntry($storage, $path);
  228. $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
  229. });
  230. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  231. $this->postProcessEntry($storage, $path);
  232. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  233. });
  234. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path, $storageId, $data, $fileId) use ($storage) {
  235. $this->postProcessEntry($storage, $path);
  236. if ($fileId) {
  237. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  238. } else {
  239. $this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
  240. }
  241. });
  242. if (!$storage->file_exists($relativePath)) {
  243. throw new NotFoundException($dir);
  244. }
  245. if ($this->useTransaction) {
  246. $this->db->beginTransaction();
  247. }
  248. try {
  249. $propagator = $storage->getPropagator();
  250. $propagator->beginBatch();
  251. $scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
  252. $cache = $storage->getCache();
  253. if ($cache instanceof Cache) {
  254. // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
  255. $cache->correctFolderSize($relativePath);
  256. }
  257. $propagator->commitBatch();
  258. } catch (StorageNotAvailableException $e) {
  259. $this->logger->error('Storage ' . $storage->getId() . ' not available', ['exception' => $e]);
  260. $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
  261. }
  262. if ($this->useTransaction) {
  263. $this->db->commit();
  264. }
  265. }
  266. }
  267. private function triggerPropagator(IStorage $storage, $internalPath) {
  268. $storage->getPropagator()->propagateChange($internalPath, time());
  269. }
  270. private function postProcessEntry(IStorage $storage, $internalPath) {
  271. $this->triggerPropagator($storage, $internalPath);
  272. if ($this->useTransaction) {
  273. $this->entriesToCommit++;
  274. if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
  275. $propagator = $storage->getPropagator();
  276. $this->entriesToCommit = 0;
  277. $this->db->commit();
  278. $propagator->commitBatch();
  279. $this->db->beginTransaction();
  280. $propagator->beginBatch();
  281. }
  282. }
  283. }
  284. }