Scanner.php 10 KB

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