You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Scanner.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Ari Selseng <ari@selseng.net>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Jagszent <daniel@jagszent.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Martin Mattel <martin.mattel@diemattels.at>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Owen Winkler <a_github@midnightcircus.com>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Vincent Petry <vincent@nextcloud.com>
  20. *
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. namespace OC\Files\Cache;
  37. use Doctrine\DBAL\Exception;
  38. use OC\Files\Filesystem;
  39. use OC\Hooks\BasicEmitter;
  40. use OCP\Files\Cache\IScanner;
  41. use OCP\Files\ForbiddenException;
  42. use OCP\ILogger;
  43. use OCP\Lock\ILockingProvider;
  44. /**
  45. * Class Scanner
  46. *
  47. * Hooks available in scope \OC\Files\Cache\Scanner:
  48. * - scanFile(string $path, string $storageId)
  49. * - scanFolder(string $path, string $storageId)
  50. * - postScanFile(string $path, string $storageId)
  51. * - postScanFolder(string $path, string $storageId)
  52. *
  53. * @package OC\Files\Cache
  54. */
  55. class Scanner extends BasicEmitter implements IScanner {
  56. /**
  57. * @var \OC\Files\Storage\Storage $storage
  58. */
  59. protected $storage;
  60. /**
  61. * @var string $storageId
  62. */
  63. protected $storageId;
  64. /**
  65. * @var \OC\Files\Cache\Cache $cache
  66. */
  67. protected $cache;
  68. /**
  69. * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
  70. */
  71. protected $cacheActive;
  72. /**
  73. * @var bool $useTransactions whether to use transactions
  74. */
  75. protected $useTransactions = true;
  76. /**
  77. * @var \OCP\Lock\ILockingProvider
  78. */
  79. protected $lockingProvider;
  80. public function __construct(\OC\Files\Storage\Storage $storage) {
  81. $this->storage = $storage;
  82. $this->storageId = $this->storage->getId();
  83. $this->cache = $storage->getCache();
  84. $this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
  85. $this->lockingProvider = \OC::$server->getLockingProvider();
  86. }
  87. /**
  88. * Whether to wrap the scanning of a folder in a database transaction
  89. * On default transactions are used
  90. *
  91. * @param bool $useTransactions
  92. */
  93. public function setUseTransactions($useTransactions) {
  94. $this->useTransactions = $useTransactions;
  95. }
  96. /**
  97. * get all the metadata of a file or folder
  98. * *
  99. *
  100. * @param string $path
  101. * @return array an array of metadata of the file
  102. */
  103. protected function getData($path) {
  104. $data = $this->storage->getMetaData($path);
  105. if (is_null($data)) {
  106. \OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", ILogger::DEBUG);
  107. }
  108. return $data;
  109. }
  110. /**
  111. * scan a single file and store it in the cache
  112. *
  113. * @param string $file
  114. * @param int $reuseExisting
  115. * @param int $parentId
  116. * @param array|null|false $cacheData existing data in the cache for the file to be scanned
  117. * @param bool $lock set to false to disable getting an additional read lock during scanning
  118. * @param null $data the metadata for the file, as returned by the storage
  119. * @return array an array of metadata of the scanned file
  120. * @throws \OCP\Lock\LockedException
  121. */
  122. public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true, $data = null) {
  123. if ($file !== '') {
  124. try {
  125. $this->storage->verifyPath(dirname($file), basename($file));
  126. } catch (\Exception $e) {
  127. return null;
  128. }
  129. }
  130. // only proceed if $file is not a partial file nor a blacklisted file
  131. if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
  132. //acquire a lock
  133. if ($lock) {
  134. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  135. $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  136. }
  137. }
  138. try {
  139. $data = $data ?? $this->getData($file);
  140. } catch (ForbiddenException $e) {
  141. if ($lock) {
  142. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  143. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  144. }
  145. }
  146. return null;
  147. }
  148. try {
  149. if ($data) {
  150. // pre-emit only if it was a file. By that we avoid counting/treating folders as files
  151. if ($data['mimetype'] !== 'httpd/unix-directory') {
  152. $this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]);
  153. \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]);
  154. }
  155. $parent = dirname($file);
  156. if ($parent === '.' or $parent === '/') {
  157. $parent = '';
  158. }
  159. if ($parentId === -1) {
  160. $parentId = $this->cache->getParentId($file);
  161. }
  162. // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
  163. if ($file and $parentId === -1) {
  164. $parentData = $this->scanFile($parent);
  165. if (!$parentData) {
  166. return null;
  167. }
  168. $parentId = $parentData['fileid'];
  169. }
  170. if ($parent) {
  171. $data['parent'] = $parentId;
  172. }
  173. if (is_null($cacheData)) {
  174. /** @var CacheEntry $cacheData */
  175. $cacheData = $this->cache->get($file);
  176. }
  177. if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
  178. // prevent empty etag
  179. if (empty($cacheData['etag'])) {
  180. $etag = $data['etag'];
  181. } else {
  182. $etag = $cacheData['etag'];
  183. }
  184. $fileId = $cacheData['fileid'];
  185. $data['fileid'] = $fileId;
  186. // only reuse data if the file hasn't explicitly changed
  187. if (isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
  188. $data['mtime'] = $cacheData['mtime'];
  189. if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
  190. $data['size'] = $cacheData['size'];
  191. }
  192. if ($reuseExisting & self::REUSE_ETAG) {
  193. $data['etag'] = $etag;
  194. }
  195. }
  196. // Only update metadata that has changed
  197. $newData = array_diff_assoc($data, $cacheData->getData());
  198. } else {
  199. $newData = $data;
  200. $fileId = -1;
  201. }
  202. if (!empty($newData)) {
  203. // Reset the checksum if the data has changed
  204. $newData['checksum'] = '';
  205. $newData['parent'] = $parentId;
  206. $data['fileid'] = $this->addToCache($file, $newData, $fileId);
  207. }
  208. if ($cacheData && isset($cacheData['size'])) {
  209. $data['oldSize'] = $cacheData['size'];
  210. } else {
  211. $data['oldSize'] = 0;
  212. }
  213. if ($cacheData && isset($cacheData['encrypted'])) {
  214. $data['encrypted'] = $cacheData['encrypted'];
  215. }
  216. // post-emit only if it was a file. By that we avoid counting/treating folders as files
  217. if ($data['mimetype'] !== 'httpd/unix-directory') {
  218. $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]);
  219. \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]);
  220. }
  221. } else {
  222. $this->removeFromCache($file);
  223. }
  224. } catch (\Exception $e) {
  225. if ($lock) {
  226. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  227. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  228. }
  229. }
  230. throw $e;
  231. }
  232. //release the acquired lock
  233. if ($lock) {
  234. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  235. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  236. }
  237. }
  238. if ($data && !isset($data['encrypted'])) {
  239. $data['encrypted'] = false;
  240. }
  241. return $data;
  242. }
  243. return null;
  244. }
  245. protected function removeFromCache($path) {
  246. \OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]);
  247. $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]);
  248. if ($this->cacheActive) {
  249. $this->cache->remove($path);
  250. }
  251. }
  252. /**
  253. * @param string $path
  254. * @param array $data
  255. * @param int $fileId
  256. * @return int the id of the added file
  257. */
  258. protected function addToCache($path, $data, $fileId = -1) {
  259. if (isset($data['scan_permissions'])) {
  260. $data['permissions'] = $data['scan_permissions'];
  261. }
  262. \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
  263. $this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data]);
  264. if ($this->cacheActive) {
  265. if ($fileId !== -1) {
  266. $this->cache->update($fileId, $data);
  267. return $fileId;
  268. } else {
  269. return $this->cache->insert($path, $data);
  270. }
  271. } else {
  272. return -1;
  273. }
  274. }
  275. /**
  276. * @param string $path
  277. * @param array $data
  278. * @param int $fileId
  279. */
  280. protected function updateCache($path, $data, $fileId = -1) {
  281. \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
  282. $this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]);
  283. if ($this->cacheActive) {
  284. if ($fileId !== -1) {
  285. $this->cache->update($fileId, $data);
  286. } else {
  287. $this->cache->put($path, $data);
  288. }
  289. }
  290. }
  291. /**
  292. * scan a folder and all it's children
  293. *
  294. * @param string $path
  295. * @param bool $recursive
  296. * @param int $reuse
  297. * @param bool $lock set to false to disable getting an additional read lock during scanning
  298. * @return array an array of the meta data of the scanned file or folder
  299. */
  300. public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
  301. if ($reuse === -1) {
  302. $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
  303. }
  304. if ($lock) {
  305. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  306. $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
  307. $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  308. }
  309. }
  310. try {
  311. $data = $this->scanFile($path, $reuse, -1, null, $lock);
  312. if ($data and $data['mimetype'] === 'httpd/unix-directory') {
  313. $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
  314. $data['size'] = $size;
  315. }
  316. } finally {
  317. if ($lock) {
  318. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  319. $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  320. $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
  321. }
  322. }
  323. }
  324. return $data;
  325. }
  326. /**
  327. * Get the children currently in the cache
  328. *
  329. * @param int $folderId
  330. * @return array[]
  331. */
  332. protected function getExistingChildren($folderId) {
  333. $existingChildren = [];
  334. $children = $this->cache->getFolderContentsById($folderId);
  335. foreach ($children as $child) {
  336. $existingChildren[$child['name']] = $child;
  337. }
  338. return $existingChildren;
  339. }
  340. /**
  341. * scan all the files and folders in a folder
  342. *
  343. * @param string $path
  344. * @param bool $recursive
  345. * @param int $reuse
  346. * @param int $folderId id for the folder to be scanned
  347. * @param bool $lock set to false to disable getting an additional read lock during scanning
  348. * @return int the size of the scanned folder or -1 if the size is unknown at this stage
  349. */
  350. protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
  351. if ($reuse === -1) {
  352. $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
  353. }
  354. $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]);
  355. $size = 0;
  356. if (!is_null($folderId)) {
  357. $folderId = $this->cache->getId($path);
  358. }
  359. $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
  360. foreach ($childQueue as $child => $childId) {
  361. $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
  362. if ($childSize === -1) {
  363. $size = -1;
  364. } elseif ($size !== -1) {
  365. $size += $childSize;
  366. }
  367. }
  368. if ($this->cacheActive) {
  369. $this->cache->update($folderId, ['size' => $size]);
  370. }
  371. $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]);
  372. return $size;
  373. }
  374. private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
  375. // we put this in it's own function so it cleans up the memory before we start recursing
  376. $existingChildren = $this->getExistingChildren($folderId);
  377. $newChildren = iterator_to_array($this->storage->getDirectoryContent($path));
  378. if ($this->useTransactions) {
  379. \OC::$server->getDatabaseConnection()->beginTransaction();
  380. }
  381. $exceptionOccurred = false;
  382. $childQueue = [];
  383. $newChildNames = [];
  384. foreach ($newChildren as $fileMeta) {
  385. $permissions = isset($fileMeta['scan_permissions']) ? $fileMeta['scan_permissions'] : $fileMeta['permissions'];
  386. if ($permissions === 0) {
  387. continue;
  388. }
  389. $file = $fileMeta['name'];
  390. $newChildNames[] = $file;
  391. $child = $path ? $path . '/' . $file : $file;
  392. try {
  393. $existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : false;
  394. $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock, $fileMeta);
  395. if ($data) {
  396. if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
  397. $childQueue[$child] = $data['fileid'];
  398. } elseif ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
  399. // only recurse into folders which aren't fully scanned
  400. $childQueue[$child] = $data['fileid'];
  401. } elseif ($data['size'] === -1) {
  402. $size = -1;
  403. } elseif ($size !== -1) {
  404. $size += $data['size'];
  405. }
  406. }
  407. } catch (Exception $ex) {
  408. // might happen if inserting duplicate while a scanning
  409. // process is running in parallel
  410. // log and ignore
  411. if ($this->useTransactions) {
  412. \OC::$server->getDatabaseConnection()->rollback();
  413. \OC::$server->getDatabaseConnection()->beginTransaction();
  414. }
  415. \OC::$server->getLogger()->logException($ex, [
  416. 'message' => 'Exception while scanning file "' . $child . '"',
  417. 'level' => ILogger::DEBUG,
  418. 'app' => 'core',
  419. ]);
  420. $exceptionOccurred = true;
  421. } catch (\OCP\Lock\LockedException $e) {
  422. if ($this->useTransactions) {
  423. \OC::$server->getDatabaseConnection()->rollback();
  424. }
  425. throw $e;
  426. }
  427. }
  428. $removedChildren = \array_diff(array_keys($existingChildren), $newChildNames);
  429. foreach ($removedChildren as $childName) {
  430. $child = $path ? $path . '/' . $childName : $childName;
  431. $this->removeFromCache($child);
  432. }
  433. if ($this->useTransactions) {
  434. \OC::$server->getDatabaseConnection()->commit();
  435. }
  436. if ($exceptionOccurred) {
  437. // It might happen that the parallel scan process has already
  438. // inserted mimetypes but those weren't available yet inside the transaction
  439. // To make sure to have the updated mime types in such cases,
  440. // we reload them here
  441. \OC::$server->getMimeTypeLoader()->reset();
  442. }
  443. return $childQueue;
  444. }
  445. /**
  446. * check if the file should be ignored when scanning
  447. * NOTE: files with a '.part' extension are ignored as well!
  448. * prevents unfinished put requests to be scanned
  449. *
  450. * @param string $file
  451. * @return boolean
  452. */
  453. public static function isPartialFile($file) {
  454. if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
  455. return true;
  456. }
  457. if (strpos($file, '.part/') !== false) {
  458. return true;
  459. }
  460. return false;
  461. }
  462. /**
  463. * walk over any folders that are not fully scanned yet and scan them
  464. */
  465. public function backgroundScan() {
  466. if (!$this->cache->inCache('')) {
  467. $this->runBackgroundScanJob(function () {
  468. $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
  469. }, '');
  470. } else {
  471. $lastPath = null;
  472. while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
  473. $this->runBackgroundScanJob(function () use ($path) {
  474. $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
  475. }, $path);
  476. // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
  477. // to make this possible
  478. $lastPath = $path;
  479. }
  480. }
  481. }
  482. private function runBackgroundScanJob(callable $callback, $path) {
  483. try {
  484. $callback();
  485. \OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]);
  486. if ($this->cacheActive && $this->cache instanceof Cache) {
  487. $this->cache->correctFolderSize($path, null, true);
  488. }
  489. } catch (\OCP\Files\StorageInvalidException $e) {
  490. // skip unavailable storages
  491. } catch (\OCP\Files\StorageNotAvailableException $e) {
  492. // skip unavailable storages
  493. } catch (\OCP\Files\ForbiddenException $e) {
  494. // skip forbidden storages
  495. } catch (\OCP\Lock\LockedException $e) {
  496. // skip unavailable storages
  497. }
  498. }
  499. /**
  500. * Set whether the cache is affected by scan operations
  501. *
  502. * @param boolean $active The active state of the cache
  503. */
  504. public function setCacheActive($active) {
  505. $this->cacheActive = $active;
  506. }
  507. }