View.php 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  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;
  8. use Icewind\Streams\CallbackWrapper;
  9. use OC\Files\Mount\MoveableMount;
  10. use OC\Files\Storage\Storage;
  11. use OC\Share\Share;
  12. use OC\User\LazyUser;
  13. use OC\User\Manager as UserManager;
  14. use OC\User\User;
  15. use OCA\Files_Sharing\SharedMount;
  16. use OCP\Constants;
  17. use OCP\Files\Cache\ICacheEntry;
  18. use OCP\Files\ConnectionLostException;
  19. use OCP\Files\EmptyFileNameException;
  20. use OCP\Files\FileNameTooLongException;
  21. use OCP\Files\ForbiddenException;
  22. use OCP\Files\InvalidCharacterInPathException;
  23. use OCP\Files\InvalidDirectoryException;
  24. use OCP\Files\InvalidPathException;
  25. use OCP\Files\Mount\IMountPoint;
  26. use OCP\Files\NotFoundException;
  27. use OCP\Files\ReservedWordException;
  28. use OCP\IUser;
  29. use OCP\IUserManager;
  30. use OCP\Lock\ILockingProvider;
  31. use OCP\Lock\LockedException;
  32. use OCP\Server;
  33. use OCP\Share\IManager;
  34. use OCP\Share\IShare;
  35. use Psr\Log\LoggerInterface;
  36. /**
  37. * Class to provide access to ownCloud filesystem via a "view", and methods for
  38. * working with files within that view (e.g. read, write, delete, etc.). Each
  39. * view is restricted to a set of directories via a virtual root. The default view
  40. * uses the currently logged in user's data directory as root (parts of
  41. * OC_Filesystem are merely a wrapper for OC\Files\View).
  42. *
  43. * Apps that need to access files outside of the user data folders (to modify files
  44. * belonging to a user other than the one currently logged in, for example) should
  45. * use this class directly rather than using OC_Filesystem, or making use of PHP's
  46. * built-in file manipulation functions. This will ensure all hooks and proxies
  47. * are triggered correctly.
  48. *
  49. * Filesystem functions are not called directly; they are passed to the correct
  50. * \OC\Files\Storage\Storage object
  51. */
  52. class View {
  53. private string $fakeRoot = '';
  54. private ILockingProvider $lockingProvider;
  55. private bool $lockingEnabled;
  56. private bool $updaterEnabled = true;
  57. private UserManager $userManager;
  58. private LoggerInterface $logger;
  59. /**
  60. * @throws \Exception If $root contains an invalid path
  61. */
  62. public function __construct(string $root = '') {
  63. if (!Filesystem::isValidPath($root)) {
  64. throw new \Exception();
  65. }
  66. $this->fakeRoot = $root;
  67. $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
  68. $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
  69. $this->userManager = \OC::$server->getUserManager();
  70. $this->logger = \OC::$server->get(LoggerInterface::class);
  71. }
  72. /**
  73. * @param ?string $path
  74. * @psalm-template S as string|null
  75. * @psalm-param S $path
  76. * @psalm-return (S is string ? string : null)
  77. */
  78. public function getAbsolutePath($path = '/'): ?string {
  79. if ($path === null) {
  80. return null;
  81. }
  82. $this->assertPathLength($path);
  83. if ($path === '') {
  84. $path = '/';
  85. }
  86. if ($path[0] !== '/') {
  87. $path = '/' . $path;
  88. }
  89. return $this->fakeRoot . $path;
  90. }
  91. /**
  92. * Change the root to a fake root
  93. *
  94. * @param string $fakeRoot
  95. */
  96. public function chroot($fakeRoot): void {
  97. if (!$fakeRoot == '') {
  98. if ($fakeRoot[0] !== '/') {
  99. $fakeRoot = '/' . $fakeRoot;
  100. }
  101. }
  102. $this->fakeRoot = $fakeRoot;
  103. }
  104. /**
  105. * Get the fake root
  106. */
  107. public function getRoot(): string {
  108. return $this->fakeRoot;
  109. }
  110. /**
  111. * get path relative to the root of the view
  112. *
  113. * @param string $path
  114. */
  115. public function getRelativePath($path): ?string {
  116. $this->assertPathLength($path);
  117. if ($this->fakeRoot == '') {
  118. return $path;
  119. }
  120. if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
  121. return '/';
  122. }
  123. // missing slashes can cause wrong matches!
  124. $root = rtrim($this->fakeRoot, '/') . '/';
  125. if (!str_starts_with($path, $root)) {
  126. return null;
  127. } else {
  128. $path = substr($path, strlen($this->fakeRoot));
  129. if (strlen($path) === 0) {
  130. return '/';
  131. } else {
  132. return $path;
  133. }
  134. }
  135. }
  136. /**
  137. * Get the mountpoint of the storage object for a path
  138. * ( note: because a storage is not always mounted inside the fakeroot, the
  139. * returned mountpoint is relative to the absolute root of the filesystem
  140. * and does not take the chroot into account )
  141. *
  142. * @param string $path
  143. */
  144. public function getMountPoint($path): string {
  145. return Filesystem::getMountPoint($this->getAbsolutePath($path));
  146. }
  147. /**
  148. * Get the mountpoint of the storage object for a path
  149. * ( note: because a storage is not always mounted inside the fakeroot, the
  150. * returned mountpoint is relative to the absolute root of the filesystem
  151. * and does not take the chroot into account )
  152. *
  153. * @param string $path
  154. */
  155. public function getMount($path): IMountPoint {
  156. return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
  157. }
  158. /**
  159. * Resolve a path to a storage and internal path
  160. *
  161. * @param string $path
  162. * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
  163. */
  164. public function resolvePath($path): array {
  165. $a = $this->getAbsolutePath($path);
  166. $p = Filesystem::normalizePath($a);
  167. return Filesystem::resolvePath($p);
  168. }
  169. /**
  170. * Return the path to a local version of the file
  171. * we need this because we can't know if a file is stored local or not from
  172. * outside the filestorage and for some purposes a local file is needed
  173. *
  174. * @param string $path
  175. */
  176. public function getLocalFile($path): string|false {
  177. $parent = substr($path, 0, strrpos($path, '/') ?: 0);
  178. $path = $this->getAbsolutePath($path);
  179. [$storage, $internalPath] = Filesystem::resolvePath($path);
  180. if (Filesystem::isValidPath($parent) && $storage) {
  181. return $storage->getLocalFile($internalPath);
  182. } else {
  183. return false;
  184. }
  185. }
  186. /**
  187. * the following functions operate with arguments and return values identical
  188. * to those of their PHP built-in equivalents. Mostly they are merely wrappers
  189. * for \OC\Files\Storage\Storage via basicOperation().
  190. */
  191. public function mkdir($path) {
  192. return $this->basicOperation('mkdir', $path, ['create', 'write']);
  193. }
  194. /**
  195. * remove mount point
  196. *
  197. * @param IMountPoint $mount
  198. * @param string $path relative to data/
  199. */
  200. protected function removeMount($mount, $path): bool {
  201. if ($mount instanceof MoveableMount) {
  202. // cut of /user/files to get the relative path to data/user/files
  203. $pathParts = explode('/', $path, 4);
  204. $relPath = '/' . $pathParts[3];
  205. $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  206. \OC_Hook::emit(
  207. Filesystem::CLASSNAME, 'umount',
  208. [Filesystem::signal_param_path => $relPath]
  209. );
  210. $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
  211. $result = $mount->removeMount();
  212. $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
  213. if ($result) {
  214. \OC_Hook::emit(
  215. Filesystem::CLASSNAME, 'post_umount',
  216. [Filesystem::signal_param_path => $relPath]
  217. );
  218. }
  219. $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  220. return $result;
  221. } else {
  222. // do not allow deleting the storage's root / the mount point
  223. // because for some storages it might delete the whole contents
  224. // but isn't supposed to work that way
  225. return false;
  226. }
  227. }
  228. public function disableCacheUpdate(): void {
  229. $this->updaterEnabled = false;
  230. }
  231. public function enableCacheUpdate(): void {
  232. $this->updaterEnabled = true;
  233. }
  234. protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
  235. if ($this->updaterEnabled) {
  236. if (is_null($time)) {
  237. $time = time();
  238. }
  239. $storage->getUpdater()->update($internalPath, $time, $sizeDifference);
  240. }
  241. }
  242. protected function removeUpdate(Storage $storage, string $internalPath): void {
  243. if ($this->updaterEnabled) {
  244. $storage->getUpdater()->remove($internalPath);
  245. }
  246. }
  247. protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
  248. if ($this->updaterEnabled) {
  249. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  250. }
  251. }
  252. protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
  253. if ($this->updaterEnabled) {
  254. $targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  255. }
  256. }
  257. /**
  258. * @param string $path
  259. * @return bool|mixed
  260. */
  261. public function rmdir($path) {
  262. $absolutePath = $this->getAbsolutePath($path);
  263. $mount = Filesystem::getMountManager()->find($absolutePath);
  264. if ($mount->getInternalPath($absolutePath) === '') {
  265. return $this->removeMount($mount, $absolutePath);
  266. }
  267. if ($this->is_dir($path)) {
  268. $result = $this->basicOperation('rmdir', $path, ['delete']);
  269. } else {
  270. $result = false;
  271. }
  272. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  273. $storage = $mount->getStorage();
  274. $internalPath = $mount->getInternalPath($absolutePath);
  275. $storage->getUpdater()->remove($internalPath);
  276. }
  277. return $result;
  278. }
  279. /**
  280. * @param string $path
  281. * @return resource|false
  282. */
  283. public function opendir($path) {
  284. return $this->basicOperation('opendir', $path, ['read']);
  285. }
  286. /**
  287. * @param string $path
  288. * @return bool|mixed
  289. */
  290. public function is_dir($path) {
  291. if ($path == '/') {
  292. return true;
  293. }
  294. return $this->basicOperation('is_dir', $path);
  295. }
  296. /**
  297. * @param string $path
  298. * @return bool|mixed
  299. */
  300. public function is_file($path) {
  301. if ($path == '/') {
  302. return false;
  303. }
  304. return $this->basicOperation('is_file', $path);
  305. }
  306. /**
  307. * @param string $path
  308. * @return mixed
  309. */
  310. public function stat($path) {
  311. return $this->basicOperation('stat', $path);
  312. }
  313. /**
  314. * @param string $path
  315. * @return mixed
  316. */
  317. public function filetype($path) {
  318. return $this->basicOperation('filetype', $path);
  319. }
  320. /**
  321. * @param string $path
  322. * @return mixed
  323. */
  324. public function filesize(string $path) {
  325. return $this->basicOperation('filesize', $path);
  326. }
  327. /**
  328. * @param string $path
  329. * @return bool|mixed
  330. * @throws InvalidPathException
  331. */
  332. public function readfile($path) {
  333. $this->assertPathLength($path);
  334. if (ob_get_level()) {
  335. ob_end_clean();
  336. }
  337. $handle = $this->fopen($path, 'rb');
  338. if ($handle) {
  339. $chunkSize = 524288; // 512 kiB chunks
  340. while (!feof($handle)) {
  341. echo fread($handle, $chunkSize);
  342. flush();
  343. $this->checkConnectionStatus();
  344. }
  345. fclose($handle);
  346. return $this->filesize($path);
  347. }
  348. return false;
  349. }
  350. /**
  351. * @param string $path
  352. * @param int $from
  353. * @param int $to
  354. * @return bool|mixed
  355. * @throws InvalidPathException
  356. * @throws \OCP\Files\UnseekableException
  357. */
  358. public function readfilePart($path, $from, $to) {
  359. $this->assertPathLength($path);
  360. if (ob_get_level()) {
  361. ob_end_clean();
  362. }
  363. $handle = $this->fopen($path, 'rb');
  364. if ($handle) {
  365. $chunkSize = 524288; // 512 kiB chunks
  366. $startReading = true;
  367. if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
  368. // forward file handle via chunked fread because fseek seem to have failed
  369. $end = $from + 1;
  370. while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
  371. $len = $from - ftell($handle);
  372. if ($len > $chunkSize) {
  373. $len = $chunkSize;
  374. }
  375. $result = fread($handle, $len);
  376. if ($result === false) {
  377. $startReading = false;
  378. break;
  379. }
  380. }
  381. }
  382. if ($startReading) {
  383. $end = $to + 1;
  384. while (!feof($handle) && ftell($handle) < $end) {
  385. $len = $end - ftell($handle);
  386. if ($len > $chunkSize) {
  387. $len = $chunkSize;
  388. }
  389. echo fread($handle, $len);
  390. flush();
  391. $this->checkConnectionStatus();
  392. }
  393. return ftell($handle) - $from;
  394. }
  395. throw new \OCP\Files\UnseekableException('fseek error');
  396. }
  397. return false;
  398. }
  399. private function checkConnectionStatus(): void {
  400. $connectionStatus = \connection_status();
  401. if ($connectionStatus !== CONNECTION_NORMAL) {
  402. throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
  403. }
  404. }
  405. /**
  406. * @param string $path
  407. * @return mixed
  408. */
  409. public function isCreatable($path) {
  410. return $this->basicOperation('isCreatable', $path);
  411. }
  412. /**
  413. * @param string $path
  414. * @return mixed
  415. */
  416. public function isReadable($path) {
  417. return $this->basicOperation('isReadable', $path);
  418. }
  419. /**
  420. * @param string $path
  421. * @return mixed
  422. */
  423. public function isUpdatable($path) {
  424. return $this->basicOperation('isUpdatable', $path);
  425. }
  426. /**
  427. * @param string $path
  428. * @return bool|mixed
  429. */
  430. public function isDeletable($path) {
  431. $absolutePath = $this->getAbsolutePath($path);
  432. $mount = Filesystem::getMountManager()->find($absolutePath);
  433. if ($mount->getInternalPath($absolutePath) === '') {
  434. return $mount instanceof MoveableMount;
  435. }
  436. return $this->basicOperation('isDeletable', $path);
  437. }
  438. /**
  439. * @param string $path
  440. * @return mixed
  441. */
  442. public function isSharable($path) {
  443. return $this->basicOperation('isSharable', $path);
  444. }
  445. /**
  446. * @param string $path
  447. * @return bool|mixed
  448. */
  449. public function file_exists($path) {
  450. if ($path == '/') {
  451. return true;
  452. }
  453. return $this->basicOperation('file_exists', $path);
  454. }
  455. /**
  456. * @param string $path
  457. * @return mixed
  458. */
  459. public function filemtime($path) {
  460. return $this->basicOperation('filemtime', $path);
  461. }
  462. /**
  463. * @param string $path
  464. * @param int|string $mtime
  465. */
  466. public function touch($path, $mtime = null): bool {
  467. if (!is_null($mtime) && !is_numeric($mtime)) {
  468. $mtime = strtotime($mtime);
  469. }
  470. $hooks = ['touch'];
  471. if (!$this->file_exists($path)) {
  472. $hooks[] = 'create';
  473. $hooks[] = 'write';
  474. }
  475. try {
  476. $result = $this->basicOperation('touch', $path, $hooks, $mtime);
  477. } catch (\Exception $e) {
  478. $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
  479. $result = false;
  480. }
  481. if (!$result) {
  482. // If create file fails because of permissions on external storage like SMB folders,
  483. // check file exists and return false if not.
  484. if (!$this->file_exists($path)) {
  485. return false;
  486. }
  487. if (is_null($mtime)) {
  488. $mtime = time();
  489. }
  490. //if native touch fails, we emulate it by changing the mtime in the cache
  491. $this->putFileInfo($path, ['mtime' => floor($mtime)]);
  492. }
  493. return true;
  494. }
  495. /**
  496. * @param string $path
  497. * @return string|false
  498. * @throws LockedException
  499. */
  500. public function file_get_contents($path) {
  501. return $this->basicOperation('file_get_contents', $path, ['read']);
  502. }
  503. protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
  504. if (!$exists) {
  505. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
  506. Filesystem::signal_param_path => $this->getHookPath($path),
  507. Filesystem::signal_param_run => &$run,
  508. ]);
  509. } else {
  510. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
  511. Filesystem::signal_param_path => $this->getHookPath($path),
  512. Filesystem::signal_param_run => &$run,
  513. ]);
  514. }
  515. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
  516. Filesystem::signal_param_path => $this->getHookPath($path),
  517. Filesystem::signal_param_run => &$run,
  518. ]);
  519. }
  520. protected function emit_file_hooks_post(bool $exists, string $path): void {
  521. if (!$exists) {
  522. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
  523. Filesystem::signal_param_path => $this->getHookPath($path),
  524. ]);
  525. } else {
  526. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
  527. Filesystem::signal_param_path => $this->getHookPath($path),
  528. ]);
  529. }
  530. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
  531. Filesystem::signal_param_path => $this->getHookPath($path),
  532. ]);
  533. }
  534. /**
  535. * @param string $path
  536. * @param string|resource $data
  537. * @return bool|mixed
  538. * @throws LockedException
  539. */
  540. public function file_put_contents($path, $data) {
  541. if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
  542. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  543. if (Filesystem::isValidPath($path)
  544. && !Filesystem::isFileBlacklisted($path)
  545. ) {
  546. $path = $this->getRelativePath($absolutePath);
  547. if ($path === null) {
  548. throw new InvalidPathException("Path $absolutePath is not in the expected root");
  549. }
  550. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  551. $exists = $this->file_exists($path);
  552. $run = true;
  553. if ($this->shouldEmitHooks($path)) {
  554. $this->emit_file_hooks_pre($exists, $path, $run);
  555. }
  556. if (!$run) {
  557. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  558. return false;
  559. }
  560. try {
  561. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  562. } catch (\Exception $e) {
  563. // Release the shared lock before throwing.
  564. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  565. throw $e;
  566. }
  567. /** @var Storage $storage */
  568. [$storage, $internalPath] = $this->resolvePath($path);
  569. $target = $storage->fopen($internalPath, 'w');
  570. if ($target) {
  571. [, $result] = \OC_Helper::streamCopy($data, $target);
  572. fclose($target);
  573. fclose($data);
  574. $this->writeUpdate($storage, $internalPath);
  575. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  576. if ($this->shouldEmitHooks($path) && $result !== false) {
  577. $this->emit_file_hooks_post($exists, $path);
  578. }
  579. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  580. return $result;
  581. } else {
  582. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  583. return false;
  584. }
  585. } else {
  586. return false;
  587. }
  588. } else {
  589. $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
  590. return $this->basicOperation('file_put_contents', $path, $hooks, $data);
  591. }
  592. }
  593. /**
  594. * @param string $path
  595. * @return bool|mixed
  596. */
  597. public function unlink($path) {
  598. if ($path === '' || $path === '/') {
  599. // do not allow deleting the root
  600. return false;
  601. }
  602. $postFix = (substr($path, -1) === '/') ? '/' : '';
  603. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  604. $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
  605. if ($mount->getInternalPath($absolutePath) === '') {
  606. return $this->removeMount($mount, $absolutePath);
  607. }
  608. if ($this->is_dir($path)) {
  609. $result = $this->basicOperation('rmdir', $path, ['delete']);
  610. } else {
  611. $result = $this->basicOperation('unlink', $path, ['delete']);
  612. }
  613. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  614. $storage = $mount->getStorage();
  615. $internalPath = $mount->getInternalPath($absolutePath);
  616. $storage->getUpdater()->remove($internalPath);
  617. return true;
  618. } else {
  619. return $result;
  620. }
  621. }
  622. /**
  623. * @param string $directory
  624. * @return bool|mixed
  625. */
  626. public function deleteAll($directory) {
  627. return $this->rmdir($directory);
  628. }
  629. /**
  630. * Rename/move a file or folder from the source path to target path.
  631. *
  632. * @param string $source source path
  633. * @param string $target target path
  634. *
  635. * @return bool|mixed
  636. * @throws LockedException
  637. */
  638. public function rename($source, $target) {
  639. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
  640. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
  641. if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
  642. throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
  643. }
  644. $targetParts = explode('/', $absolutePath2);
  645. $targetUser = $targetParts[1] ?? null;
  646. $result = false;
  647. if (
  648. Filesystem::isValidPath($target)
  649. && Filesystem::isValidPath($source)
  650. && !Filesystem::isFileBlacklisted($target)
  651. ) {
  652. $source = $this->getRelativePath($absolutePath1);
  653. $target = $this->getRelativePath($absolutePath2);
  654. $exists = $this->file_exists($target);
  655. if ($source == null || $target == null) {
  656. return false;
  657. }
  658. try {
  659. $this->verifyPath(dirname($target), basename($target));
  660. } catch (InvalidPathException) {
  661. return false;
  662. }
  663. $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
  664. try {
  665. $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
  666. $run = true;
  667. if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
  668. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  669. $this->emit_file_hooks_pre($exists, $target, $run);
  670. } elseif ($this->shouldEmitHooks($source)) {
  671. $sourcePath = $this->getHookPath($source);
  672. $targetPath = $this->getHookPath($target);
  673. if ($sourcePath !== null && $targetPath !== null) {
  674. \OC_Hook::emit(
  675. Filesystem::CLASSNAME, Filesystem::signal_rename,
  676. [
  677. Filesystem::signal_param_oldpath => $sourcePath,
  678. Filesystem::signal_param_newpath => $targetPath,
  679. Filesystem::signal_param_run => &$run
  680. ]
  681. );
  682. }
  683. }
  684. if ($run) {
  685. $manager = Filesystem::getMountManager();
  686. $mount1 = $this->getMount($source);
  687. $mount2 = $this->getMount($target);
  688. $storage1 = $mount1->getStorage();
  689. $storage2 = $mount2->getStorage();
  690. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  691. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  692. $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
  693. try {
  694. $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
  695. if ($internalPath1 === '') {
  696. if ($mount1 instanceof MoveableMount) {
  697. $sourceParentMount = $this->getMount(dirname($source));
  698. if ($sourceParentMount === $mount2 && $this->targetIsNotShared($targetUser, $absolutePath2)) {
  699. /**
  700. * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
  701. */
  702. $sourceMountPoint = $mount1->getMountPoint();
  703. $result = $mount1->moveMount($absolutePath2);
  704. $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
  705. } else {
  706. $result = false;
  707. }
  708. } else {
  709. $result = false;
  710. }
  711. // moving a file/folder within the same mount point
  712. } elseif ($storage1 === $storage2) {
  713. if ($storage1) {
  714. $result = $storage1->rename($internalPath1, $internalPath2);
  715. } else {
  716. $result = false;
  717. }
  718. // moving a file/folder between storages (from $storage1 to $storage2)
  719. } else {
  720. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  721. }
  722. if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
  723. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  724. $this->writeUpdate($storage2, $internalPath2);
  725. } elseif ($result) {
  726. if ($internalPath1 !== '') { // don't do a cache update for moved mounts
  727. $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
  728. }
  729. }
  730. } catch (\Exception $e) {
  731. throw $e;
  732. } finally {
  733. $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
  734. $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
  735. }
  736. if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
  737. if ($this->shouldEmitHooks()) {
  738. $this->emit_file_hooks_post($exists, $target);
  739. }
  740. } elseif ($result) {
  741. if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
  742. $sourcePath = $this->getHookPath($source);
  743. $targetPath = $this->getHookPath($target);
  744. if ($sourcePath !== null && $targetPath !== null) {
  745. \OC_Hook::emit(
  746. Filesystem::CLASSNAME,
  747. Filesystem::signal_post_rename,
  748. [
  749. Filesystem::signal_param_oldpath => $sourcePath,
  750. Filesystem::signal_param_newpath => $targetPath,
  751. ]
  752. );
  753. }
  754. }
  755. }
  756. }
  757. } catch (\Exception $e) {
  758. throw $e;
  759. } finally {
  760. $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
  761. $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
  762. }
  763. }
  764. return $result;
  765. }
  766. /**
  767. * Copy a file/folder from the source path to target path
  768. *
  769. * @param string $source source path
  770. * @param string $target target path
  771. * @param bool $preserveMtime whether to preserve mtime on the copy
  772. *
  773. * @return bool|mixed
  774. */
  775. public function copy($source, $target, $preserveMtime = false) {
  776. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
  777. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
  778. $result = false;
  779. if (
  780. Filesystem::isValidPath($target)
  781. && Filesystem::isValidPath($source)
  782. && !Filesystem::isFileBlacklisted($target)
  783. ) {
  784. $source = $this->getRelativePath($absolutePath1);
  785. $target = $this->getRelativePath($absolutePath2);
  786. if ($source == null || $target == null) {
  787. return false;
  788. }
  789. $run = true;
  790. $this->lockFile($target, ILockingProvider::LOCK_SHARED);
  791. $this->lockFile($source, ILockingProvider::LOCK_SHARED);
  792. $lockTypePath1 = ILockingProvider::LOCK_SHARED;
  793. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  794. try {
  795. $exists = $this->file_exists($target);
  796. if ($this->shouldEmitHooks()) {
  797. \OC_Hook::emit(
  798. Filesystem::CLASSNAME,
  799. Filesystem::signal_copy,
  800. [
  801. Filesystem::signal_param_oldpath => $this->getHookPath($source),
  802. Filesystem::signal_param_newpath => $this->getHookPath($target),
  803. Filesystem::signal_param_run => &$run
  804. ]
  805. );
  806. $this->emit_file_hooks_pre($exists, $target, $run);
  807. }
  808. if ($run) {
  809. $mount1 = $this->getMount($source);
  810. $mount2 = $this->getMount($target);
  811. $storage1 = $mount1->getStorage();
  812. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  813. $storage2 = $mount2->getStorage();
  814. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  815. $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
  816. $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
  817. if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
  818. if ($storage1) {
  819. $result = $storage1->copy($internalPath1, $internalPath2);
  820. } else {
  821. $result = false;
  822. }
  823. } else {
  824. $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
  825. }
  826. if ($result) {
  827. $this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
  828. }
  829. $this->changeLock($target, ILockingProvider::LOCK_SHARED);
  830. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  831. if ($this->shouldEmitHooks() && $result !== false) {
  832. \OC_Hook::emit(
  833. Filesystem::CLASSNAME,
  834. Filesystem::signal_post_copy,
  835. [
  836. Filesystem::signal_param_oldpath => $this->getHookPath($source),
  837. Filesystem::signal_param_newpath => $this->getHookPath($target)
  838. ]
  839. );
  840. $this->emit_file_hooks_post($exists, $target);
  841. }
  842. }
  843. } catch (\Exception $e) {
  844. $this->unlockFile($target, $lockTypePath2);
  845. $this->unlockFile($source, $lockTypePath1);
  846. throw $e;
  847. }
  848. $this->unlockFile($target, $lockTypePath2);
  849. $this->unlockFile($source, $lockTypePath1);
  850. }
  851. return $result;
  852. }
  853. /**
  854. * @param string $path
  855. * @param string $mode 'r' or 'w'
  856. * @return resource|false
  857. * @throws LockedException
  858. */
  859. public function fopen($path, $mode) {
  860. $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
  861. $hooks = [];
  862. switch ($mode) {
  863. case 'r':
  864. $hooks[] = 'read';
  865. break;
  866. case 'r+':
  867. case 'w+':
  868. case 'x+':
  869. case 'a+':
  870. $hooks[] = 'read';
  871. $hooks[] = 'write';
  872. break;
  873. case 'w':
  874. case 'x':
  875. case 'a':
  876. $hooks[] = 'write';
  877. break;
  878. default:
  879. $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
  880. }
  881. if ($mode !== 'r' && $mode !== 'w') {
  882. $this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
  883. }
  884. $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
  885. if (!is_resource($handle) && $mode === 'r') {
  886. // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
  887. $mount = $this->getMount($path);
  888. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  889. $storage = $mount->getStorage();
  890. if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
  891. $this->writeUpdate($storage, $internalPath);
  892. }
  893. }
  894. return $handle;
  895. }
  896. /**
  897. * @param string $path
  898. * @throws InvalidPathException
  899. */
  900. public function toTmpFile($path): string|false {
  901. $this->assertPathLength($path);
  902. if (Filesystem::isValidPath($path)) {
  903. $source = $this->fopen($path, 'r');
  904. if ($source) {
  905. $extension = pathinfo($path, PATHINFO_EXTENSION);
  906. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
  907. file_put_contents($tmpFile, $source);
  908. return $tmpFile;
  909. } else {
  910. return false;
  911. }
  912. } else {
  913. return false;
  914. }
  915. }
  916. /**
  917. * @param string $tmpFile
  918. * @param string $path
  919. * @return bool|mixed
  920. * @throws InvalidPathException
  921. */
  922. public function fromTmpFile($tmpFile, $path) {
  923. $this->assertPathLength($path);
  924. if (Filesystem::isValidPath($path)) {
  925. // Get directory that the file is going into
  926. $filePath = dirname($path);
  927. // Create the directories if any
  928. if (!$this->file_exists($filePath)) {
  929. $result = $this->createParentDirectories($filePath);
  930. if ($result === false) {
  931. return false;
  932. }
  933. }
  934. $source = fopen($tmpFile, 'r');
  935. if ($source) {
  936. $result = $this->file_put_contents($path, $source);
  937. /**
  938. * $this->file_put_contents() might have already closed
  939. * the resource, so we check it, before trying to close it
  940. * to avoid messages in the error log.
  941. * @psalm-suppress RedundantCondition false-positive
  942. */
  943. if (is_resource($source)) {
  944. fclose($source);
  945. }
  946. unlink($tmpFile);
  947. return $result;
  948. } else {
  949. return false;
  950. }
  951. } else {
  952. return false;
  953. }
  954. }
  955. /**
  956. * @param string $path
  957. * @return mixed
  958. * @throws InvalidPathException
  959. */
  960. public function getMimeType($path) {
  961. $this->assertPathLength($path);
  962. return $this->basicOperation('getMimeType', $path);
  963. }
  964. /**
  965. * @param string $type
  966. * @param string $path
  967. * @param bool $raw
  968. */
  969. public function hash($type, $path, $raw = false): string|bool {
  970. $postFix = (substr($path, -1) === '/') ? '/' : '';
  971. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  972. if (Filesystem::isValidPath($path)) {
  973. $path = $this->getRelativePath($absolutePath);
  974. if ($path == null) {
  975. return false;
  976. }
  977. if ($this->shouldEmitHooks($path)) {
  978. \OC_Hook::emit(
  979. Filesystem::CLASSNAME,
  980. Filesystem::signal_read,
  981. [Filesystem::signal_param_path => $this->getHookPath($path)]
  982. );
  983. }
  984. /** @var Storage|null $storage */
  985. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  986. if ($storage) {
  987. return $storage->hash($type, $internalPath, $raw);
  988. }
  989. }
  990. return false;
  991. }
  992. /**
  993. * @param string $path
  994. * @return mixed
  995. * @throws InvalidPathException
  996. */
  997. public function free_space($path = '/') {
  998. $this->assertPathLength($path);
  999. $result = $this->basicOperation('free_space', $path);
  1000. if ($result === null) {
  1001. throw new InvalidPathException();
  1002. }
  1003. return $result;
  1004. }
  1005. /**
  1006. * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
  1007. *
  1008. * @param mixed $extraParam (optional)
  1009. * @return mixed
  1010. * @throws LockedException
  1011. *
  1012. * This method takes requests for basic filesystem functions (e.g. reading & writing
  1013. * files), processes hooks and proxies, sanitises paths, and finally passes them on to
  1014. * \OC\Files\Storage\Storage for delegation to a storage backend for execution
  1015. */
  1016. private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
  1017. $postFix = (substr($path, -1) === '/') ? '/' : '';
  1018. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  1019. if (Filesystem::isValidPath($path)
  1020. && !Filesystem::isFileBlacklisted($path)
  1021. ) {
  1022. $path = $this->getRelativePath($absolutePath);
  1023. if ($path == null) {
  1024. return false;
  1025. }
  1026. if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
  1027. // always a shared lock during pre-hooks so the hook can read the file
  1028. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  1029. }
  1030. $run = $this->runHooks($hooks, $path);
  1031. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  1032. if ($run && $storage) {
  1033. /** @var Storage $storage */
  1034. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1035. try {
  1036. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  1037. } catch (LockedException $e) {
  1038. // release the shared lock we acquired before quitting
  1039. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1040. throw $e;
  1041. }
  1042. }
  1043. try {
  1044. if (!is_null($extraParam)) {
  1045. $result = $storage->$operation($internalPath, $extraParam);
  1046. } else {
  1047. $result = $storage->$operation($internalPath);
  1048. }
  1049. } catch (\Exception $e) {
  1050. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1051. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1052. } elseif (in_array('read', $hooks)) {
  1053. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1054. }
  1055. throw $e;
  1056. }
  1057. if ($result !== false && in_array('delete', $hooks)) {
  1058. $this->removeUpdate($storage, $internalPath);
  1059. }
  1060. if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
  1061. $isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
  1062. $sizeDifference = $operation === 'mkdir' ? 0 : $result;
  1063. $this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
  1064. }
  1065. if ($result !== false && in_array('touch', $hooks)) {
  1066. $this->writeUpdate($storage, $internalPath, $extraParam, 0);
  1067. }
  1068. if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
  1069. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  1070. }
  1071. $unlockLater = false;
  1072. if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
  1073. $unlockLater = true;
  1074. // make sure our unlocking callback will still be called if connection is aborted
  1075. ignore_user_abort(true);
  1076. $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
  1077. if (in_array('write', $hooks)) {
  1078. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1079. } elseif (in_array('read', $hooks)) {
  1080. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1081. }
  1082. });
  1083. }
  1084. if ($this->shouldEmitHooks($path) && $result !== false) {
  1085. if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
  1086. $this->runHooks($hooks, $path, true);
  1087. }
  1088. }
  1089. if (!$unlockLater
  1090. && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
  1091. ) {
  1092. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1093. }
  1094. return $result;
  1095. } else {
  1096. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1097. }
  1098. }
  1099. return null;
  1100. }
  1101. /**
  1102. * get the path relative to the default root for hook usage
  1103. *
  1104. * @param string $path
  1105. * @return ?string
  1106. */
  1107. private function getHookPath($path): ?string {
  1108. $view = Filesystem::getView();
  1109. if (!$view) {
  1110. return $path;
  1111. }
  1112. return $view->getRelativePath($this->getAbsolutePath($path));
  1113. }
  1114. private function shouldEmitHooks(string $path = ''): bool {
  1115. if ($path && Cache\Scanner::isPartialFile($path)) {
  1116. return false;
  1117. }
  1118. if (!Filesystem::$loaded) {
  1119. return false;
  1120. }
  1121. $defaultRoot = Filesystem::getRoot();
  1122. if ($defaultRoot === null) {
  1123. return false;
  1124. }
  1125. if ($this->fakeRoot === $defaultRoot) {
  1126. return true;
  1127. }
  1128. $fullPath = $this->getAbsolutePath($path);
  1129. if ($fullPath === $defaultRoot) {
  1130. return true;
  1131. }
  1132. return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
  1133. }
  1134. /**
  1135. * @param string[] $hooks
  1136. * @param string $path
  1137. * @param bool $post
  1138. * @return bool
  1139. */
  1140. private function runHooks($hooks, $path, $post = false) {
  1141. $relativePath = $path;
  1142. $path = $this->getHookPath($path);
  1143. $prefix = $post ? 'post_' : '';
  1144. $run = true;
  1145. if ($this->shouldEmitHooks($relativePath)) {
  1146. foreach ($hooks as $hook) {
  1147. if ($hook != 'read') {
  1148. \OC_Hook::emit(
  1149. Filesystem::CLASSNAME,
  1150. $prefix . $hook,
  1151. [
  1152. Filesystem::signal_param_run => &$run,
  1153. Filesystem::signal_param_path => $path
  1154. ]
  1155. );
  1156. } elseif (!$post) {
  1157. \OC_Hook::emit(
  1158. Filesystem::CLASSNAME,
  1159. $prefix . $hook,
  1160. [
  1161. Filesystem::signal_param_path => $path
  1162. ]
  1163. );
  1164. }
  1165. }
  1166. }
  1167. return $run;
  1168. }
  1169. /**
  1170. * check if a file or folder has been updated since $time
  1171. *
  1172. * @param string $path
  1173. * @param int $time
  1174. * @return bool
  1175. */
  1176. public function hasUpdated($path, $time) {
  1177. return $this->basicOperation('hasUpdated', $path, [], $time);
  1178. }
  1179. /**
  1180. * @param string $ownerId
  1181. * @return IUser
  1182. */
  1183. private function getUserObjectForOwner(string $ownerId) {
  1184. return new LazyUser($ownerId, $this->userManager);
  1185. }
  1186. /**
  1187. * Get file info from cache
  1188. *
  1189. * If the file is not in cached it will be scanned
  1190. * If the file has changed on storage the cache will be updated
  1191. *
  1192. * @param Storage $storage
  1193. * @param string $internalPath
  1194. * @param string $relativePath
  1195. * @return ICacheEntry|bool
  1196. */
  1197. private function getCacheEntry($storage, $internalPath, $relativePath) {
  1198. $cache = $storage->getCache($internalPath);
  1199. $data = $cache->get($internalPath);
  1200. $watcher = $storage->getWatcher($internalPath);
  1201. try {
  1202. // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
  1203. if (!$data || (isset($data['size']) && $data['size'] === -1)) {
  1204. if (!$storage->file_exists($internalPath)) {
  1205. return false;
  1206. }
  1207. // don't need to get a lock here since the scanner does it's own locking
  1208. $scanner = $storage->getScanner($internalPath);
  1209. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1210. $data = $cache->get($internalPath);
  1211. } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
  1212. $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1213. $watcher->update($internalPath, $data);
  1214. $storage->getPropagator()->propagateChange($internalPath, time());
  1215. $data = $cache->get($internalPath);
  1216. $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1217. }
  1218. } catch (LockedException $e) {
  1219. // if the file is locked we just use the old cache info
  1220. }
  1221. return $data;
  1222. }
  1223. /**
  1224. * get the filesystem info
  1225. *
  1226. * @param string $path
  1227. * @param bool|string $includeMountPoints true to add mountpoint sizes,
  1228. * 'ext' to add only ext storage mount point sizes. Defaults to true.
  1229. * @return \OC\Files\FileInfo|false False if file does not exist
  1230. */
  1231. public function getFileInfo($path, $includeMountPoints = true) {
  1232. $this->assertPathLength($path);
  1233. if (!Filesystem::isValidPath($path)) {
  1234. return false;
  1235. }
  1236. $relativePath = $path;
  1237. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1238. $mount = Filesystem::getMountManager()->find($path);
  1239. $storage = $mount->getStorage();
  1240. $internalPath = $mount->getInternalPath($path);
  1241. if ($storage) {
  1242. $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
  1243. if (!$data instanceof ICacheEntry) {
  1244. if (Cache\Scanner::isPartialFile($relativePath)) {
  1245. return $this->getPartFileInfo($relativePath);
  1246. }
  1247. return false;
  1248. }
  1249. if ($mount instanceof MoveableMount && $internalPath === '') {
  1250. $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
  1251. }
  1252. if ($internalPath === '' && $data['name']) {
  1253. $data['name'] = basename($path);
  1254. }
  1255. $ownerId = $storage->getOwner($internalPath);
  1256. $owner = null;
  1257. if ($ownerId !== false) {
  1258. // ownerId might be null if files are accessed with an access token without file system access
  1259. $owner = $this->getUserObjectForOwner($ownerId);
  1260. }
  1261. $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
  1262. if (isset($data['fileid'])) {
  1263. if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
  1264. //add the sizes of other mount points to the folder
  1265. $extOnly = ($includeMountPoints === 'ext');
  1266. $this->addSubMounts($info, $extOnly);
  1267. }
  1268. }
  1269. return $info;
  1270. } else {
  1271. $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
  1272. }
  1273. return false;
  1274. }
  1275. /**
  1276. * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
  1277. */
  1278. public function addSubMounts(FileInfo $info, $extOnly = false): void {
  1279. $mounts = Filesystem::getMountManager()->findIn($info->getPath());
  1280. $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
  1281. $subStorage = $mount->getStorage();
  1282. return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
  1283. }));
  1284. }
  1285. /**
  1286. * get the content of a directory
  1287. *
  1288. * @param string $directory path under datadirectory
  1289. * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  1290. * @return FileInfo[]
  1291. */
  1292. public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
  1293. $this->assertPathLength($directory);
  1294. if (!Filesystem::isValidPath($directory)) {
  1295. return [];
  1296. }
  1297. $path = $this->getAbsolutePath($directory);
  1298. $path = Filesystem::normalizePath($path);
  1299. $mount = $this->getMount($directory);
  1300. $storage = $mount->getStorage();
  1301. $internalPath = $mount->getInternalPath($path);
  1302. if (!$storage) {
  1303. return [];
  1304. }
  1305. $cache = $storage->getCache($internalPath);
  1306. $user = \OC_User::getUser();
  1307. if (!$directoryInfo) {
  1308. $data = $this->getCacheEntry($storage, $internalPath, $directory);
  1309. if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
  1310. return [];
  1311. }
  1312. } else {
  1313. $data = $directoryInfo;
  1314. }
  1315. if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
  1316. return [];
  1317. }
  1318. $folderId = $data->getId();
  1319. $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
  1320. $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
  1321. $fileNames = array_map(function (ICacheEntry $content) {
  1322. return $content->getName();
  1323. }, $contents);
  1324. /**
  1325. * @var \OC\Files\FileInfo[] $fileInfos
  1326. */
  1327. $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
  1328. if ($sharingDisabled) {
  1329. $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1330. }
  1331. $ownerId = $storage->getOwner($content['path']);
  1332. if ($ownerId !== false) {
  1333. $owner = $this->getUserObjectForOwner($ownerId);
  1334. } else {
  1335. $owner = null;
  1336. }
  1337. return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
  1338. }, $contents);
  1339. $files = array_combine($fileNames, $fileInfos);
  1340. //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
  1341. $mounts = Filesystem::getMountManager()->findIn($path);
  1342. // make sure nested mounts are sorted after their parent mounts
  1343. // otherwise doesn't propagate the etag across storage boundaries correctly
  1344. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1345. return $a->getMountPoint() <=> $b->getMountPoint();
  1346. });
  1347. $dirLength = strlen($path);
  1348. foreach ($mounts as $mount) {
  1349. $mountPoint = $mount->getMountPoint();
  1350. $subStorage = $mount->getStorage();
  1351. if ($subStorage) {
  1352. $subCache = $subStorage->getCache('');
  1353. $rootEntry = $subCache->get('');
  1354. if (!$rootEntry) {
  1355. $subScanner = $subStorage->getScanner();
  1356. try {
  1357. $subScanner->scanFile('');
  1358. } catch (\OCP\Files\StorageNotAvailableException $e) {
  1359. continue;
  1360. } catch (\OCP\Files\StorageInvalidException $e) {
  1361. continue;
  1362. } catch (\Exception $e) {
  1363. // sometimes when the storage is not available it can be any exception
  1364. $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
  1365. 'exception' => $e,
  1366. 'app' => 'core',
  1367. ]);
  1368. continue;
  1369. }
  1370. $rootEntry = $subCache->get('');
  1371. }
  1372. if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
  1373. $relativePath = trim(substr($mountPoint, $dirLength), '/');
  1374. if ($pos = strpos($relativePath, '/')) {
  1375. //mountpoint inside subfolder add size to the correct folder
  1376. $entryName = substr($relativePath, 0, $pos);
  1377. // Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
  1378. if (!isset($files[$entryName])) {
  1379. try {
  1380. if ($this->mkdir($path . '/' . $entryName) !== false) {
  1381. $info = $this->getFileInfo($path . '/' . $entryName);
  1382. if ($info !== false) {
  1383. $files[$entryName] = $info;
  1384. }
  1385. }
  1386. } catch (\Exception $e) {
  1387. // Creating the parent folder might not be possible, for example due to a lack of permissions.
  1388. $this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
  1389. }
  1390. }
  1391. if (isset($files[$entryName])) {
  1392. $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
  1393. }
  1394. } else { //mountpoint in this folder, add an entry for it
  1395. $rootEntry['name'] = $relativePath;
  1396. $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
  1397. $permissions = $rootEntry['permissions'];
  1398. // do not allow renaming/deleting the mount point if they are not shared files/folders
  1399. // for shared files/folders we use the permissions given by the owner
  1400. if ($mount instanceof MoveableMount) {
  1401. $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
  1402. } else {
  1403. $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
  1404. }
  1405. $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
  1406. // if sharing was disabled for the user we remove the share permissions
  1407. if ($sharingDisabled) {
  1408. $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1409. }
  1410. $ownerId = $subStorage->getOwner('');
  1411. if ($ownerId !== false) {
  1412. $owner = $this->getUserObjectForOwner($ownerId);
  1413. } else {
  1414. $owner = null;
  1415. }
  1416. $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
  1417. }
  1418. }
  1419. }
  1420. }
  1421. if ($mimetype_filter) {
  1422. $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
  1423. if (strpos($mimetype_filter, '/')) {
  1424. return $file->getMimetype() === $mimetype_filter;
  1425. } else {
  1426. return $file->getMimePart() === $mimetype_filter;
  1427. }
  1428. });
  1429. }
  1430. return array_values($files);
  1431. }
  1432. /**
  1433. * change file metadata
  1434. *
  1435. * @param string $path
  1436. * @param array|\OCP\Files\FileInfo $data
  1437. * @return int
  1438. *
  1439. * returns the fileid of the updated file
  1440. */
  1441. public function putFileInfo($path, $data) {
  1442. $this->assertPathLength($path);
  1443. if ($data instanceof FileInfo) {
  1444. $data = $data->getData();
  1445. }
  1446. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1447. /**
  1448. * @var Storage $storage
  1449. * @var string $internalPath
  1450. */
  1451. [$storage, $internalPath] = Filesystem::resolvePath($path);
  1452. if ($storage) {
  1453. $cache = $storage->getCache($path);
  1454. if (!$cache->inCache($internalPath)) {
  1455. $scanner = $storage->getScanner($internalPath);
  1456. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1457. }
  1458. return $cache->put($internalPath, $data);
  1459. } else {
  1460. return -1;
  1461. }
  1462. }
  1463. /**
  1464. * search for files with the name matching $query
  1465. *
  1466. * @param string $query
  1467. * @return FileInfo[]
  1468. */
  1469. public function search($query) {
  1470. return $this->searchCommon('search', ['%' . $query . '%']);
  1471. }
  1472. /**
  1473. * search for files with the name matching $query
  1474. *
  1475. * @param string $query
  1476. * @return FileInfo[]
  1477. */
  1478. public function searchRaw($query) {
  1479. return $this->searchCommon('search', [$query]);
  1480. }
  1481. /**
  1482. * search for files by mimetype
  1483. *
  1484. * @param string $mimetype
  1485. * @return FileInfo[]
  1486. */
  1487. public function searchByMime($mimetype) {
  1488. return $this->searchCommon('searchByMime', [$mimetype]);
  1489. }
  1490. /**
  1491. * search for files by tag
  1492. *
  1493. * @param string|int $tag name or tag id
  1494. * @param string $userId owner of the tags
  1495. * @return FileInfo[]
  1496. */
  1497. public function searchByTag($tag, $userId) {
  1498. return $this->searchCommon('searchByTag', [$tag, $userId]);
  1499. }
  1500. /**
  1501. * @param string $method cache method
  1502. * @param array $args
  1503. * @return FileInfo[]
  1504. */
  1505. private function searchCommon($method, $args) {
  1506. $files = [];
  1507. $rootLength = strlen($this->fakeRoot);
  1508. $mount = $this->getMount('');
  1509. $mountPoint = $mount->getMountPoint();
  1510. $storage = $mount->getStorage();
  1511. $userManager = \OC::$server->getUserManager();
  1512. if ($storage) {
  1513. $cache = $storage->getCache('');
  1514. $results = call_user_func_array([$cache, $method], $args);
  1515. foreach ($results as $result) {
  1516. if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
  1517. $internalPath = $result['path'];
  1518. $path = $mountPoint . $result['path'];
  1519. $result['path'] = substr($mountPoint . $result['path'], $rootLength);
  1520. $ownerId = $storage->getOwner($internalPath);
  1521. if ($ownerId !== false) {
  1522. $owner = $userManager->get($ownerId);
  1523. } else {
  1524. $owner = null;
  1525. }
  1526. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1527. }
  1528. }
  1529. $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
  1530. foreach ($mounts as $mount) {
  1531. $mountPoint = $mount->getMountPoint();
  1532. $storage = $mount->getStorage();
  1533. if ($storage) {
  1534. $cache = $storage->getCache('');
  1535. $relativeMountPoint = substr($mountPoint, $rootLength);
  1536. $results = call_user_func_array([$cache, $method], $args);
  1537. if ($results) {
  1538. foreach ($results as $result) {
  1539. $internalPath = $result['path'];
  1540. $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
  1541. $path = rtrim($mountPoint . $internalPath, '/');
  1542. $ownerId = $storage->getOwner($internalPath);
  1543. if ($ownerId !== false) {
  1544. $owner = $userManager->get($ownerId);
  1545. } else {
  1546. $owner = null;
  1547. }
  1548. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1549. }
  1550. }
  1551. }
  1552. }
  1553. }
  1554. return $files;
  1555. }
  1556. /**
  1557. * Get the owner for a file or folder
  1558. *
  1559. * @throws NotFoundException
  1560. */
  1561. public function getOwner(string $path): string {
  1562. $info = $this->getFileInfo($path);
  1563. if (!$info) {
  1564. throw new NotFoundException($path . ' not found while trying to get owner');
  1565. }
  1566. if ($info->getOwner() === null) {
  1567. throw new NotFoundException($path . ' has no owner');
  1568. }
  1569. return $info->getOwner()->getUID();
  1570. }
  1571. /**
  1572. * get the ETag for a file or folder
  1573. *
  1574. * @param string $path
  1575. * @return string|false
  1576. */
  1577. public function getETag($path) {
  1578. [$storage, $internalPath] = $this->resolvePath($path);
  1579. if ($storage) {
  1580. return $storage->getETag($internalPath);
  1581. } else {
  1582. return false;
  1583. }
  1584. }
  1585. /**
  1586. * Get the path of a file by id, relative to the view
  1587. *
  1588. * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
  1589. *
  1590. * @param int $id
  1591. * @param int|null $storageId
  1592. * @return string
  1593. * @throws NotFoundException
  1594. */
  1595. public function getPath($id, ?int $storageId = null) {
  1596. $id = (int)$id;
  1597. $manager = Filesystem::getMountManager();
  1598. $mounts = $manager->findIn($this->fakeRoot);
  1599. $mounts[] = $manager->find($this->fakeRoot);
  1600. $mounts = array_filter($mounts);
  1601. // reverse the array, so we start with the storage this view is in
  1602. // which is the most likely to contain the file we're looking for
  1603. $mounts = array_reverse($mounts);
  1604. // put non-shared mounts in front of the shared mount
  1605. // this prevents unneeded recursion into shares
  1606. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1607. return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
  1608. });
  1609. if (!is_null($storageId)) {
  1610. $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
  1611. return $mount->getNumericStorageId() === $storageId;
  1612. });
  1613. }
  1614. foreach ($mounts as $mount) {
  1615. /**
  1616. * @var \OC\Files\Mount\MountPoint $mount
  1617. */
  1618. if ($mount->getStorage()) {
  1619. $cache = $mount->getStorage()->getCache();
  1620. $internalPath = $cache->getPathById($id);
  1621. if (is_string($internalPath)) {
  1622. $fullPath = $mount->getMountPoint() . $internalPath;
  1623. if (!is_null($path = $this->getRelativePath($fullPath))) {
  1624. return $path;
  1625. }
  1626. }
  1627. }
  1628. }
  1629. throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
  1630. }
  1631. /**
  1632. * @param string $path
  1633. * @throws InvalidPathException
  1634. */
  1635. private function assertPathLength($path): void {
  1636. $maxLen = min(PHP_MAXPATHLEN, 4000);
  1637. // Check for the string length - performed using isset() instead of strlen()
  1638. // because isset() is about 5x-40x faster.
  1639. if (isset($path[$maxLen])) {
  1640. $pathLen = strlen($path);
  1641. throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
  1642. }
  1643. }
  1644. /**
  1645. * check if it is allowed to move a mount point to a given target.
  1646. * It is not allowed to move a mount point into a different mount point or
  1647. * into an already shared folder
  1648. */
  1649. private function targetIsNotShared(string $user, string $targetPath): bool {
  1650. $providers = [
  1651. IShare::TYPE_USER,
  1652. IShare::TYPE_GROUP,
  1653. IShare::TYPE_EMAIL,
  1654. IShare::TYPE_CIRCLE,
  1655. IShare::TYPE_ROOM,
  1656. IShare::TYPE_DECK,
  1657. IShare::TYPE_SCIENCEMESH
  1658. ];
  1659. $shareManager = Server::get(IManager::class);
  1660. /** @var IShare[] $shares */
  1661. $shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
  1662. return $shareManager->getSharesBy($user, $type);
  1663. }, $providers));
  1664. foreach ($shares as $share) {
  1665. $sharedPath = $share->getNode()->getPath();
  1666. if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
  1667. $this->logger->debug(
  1668. 'It is not allowed to move one mount point into a shared folder',
  1669. ['app' => 'files']);
  1670. return false;
  1671. }
  1672. }
  1673. return true;
  1674. }
  1675. /**
  1676. * Get a fileinfo object for files that are ignored in the cache (part files)
  1677. */
  1678. private function getPartFileInfo(string $path): \OC\Files\FileInfo {
  1679. $mount = $this->getMount($path);
  1680. $storage = $mount->getStorage();
  1681. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1682. $ownerId = $storage->getOwner($internalPath);
  1683. if ($ownerId !== false) {
  1684. $owner = Server::get(IUserManager::class)->get($ownerId);
  1685. } else {
  1686. $owner = null;
  1687. }
  1688. return new FileInfo(
  1689. $this->getAbsolutePath($path),
  1690. $storage,
  1691. $internalPath,
  1692. [
  1693. 'fileid' => null,
  1694. 'mimetype' => $storage->getMimeType($internalPath),
  1695. 'name' => basename($path),
  1696. 'etag' => null,
  1697. 'size' => $storage->filesize($internalPath),
  1698. 'mtime' => $storage->filemtime($internalPath),
  1699. 'encrypted' => false,
  1700. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1701. ],
  1702. $mount,
  1703. $owner
  1704. );
  1705. }
  1706. /**
  1707. * @param string $path
  1708. * @param string $fileName
  1709. * @param bool $readonly Check only if the path is allowed for read-only access
  1710. * @throws InvalidPathException
  1711. */
  1712. public function verifyPath($path, $fileName, $readonly = false): void {
  1713. // All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
  1714. if (!Filesystem::isValidPath($path ?: '/')) {
  1715. $l = \OCP\Util::getL10N('lib');
  1716. throw new InvalidPathException($l->t('Path contains invalid segments'));
  1717. }
  1718. // Short cut for read-only validation
  1719. if ($readonly) {
  1720. $validator = Server::get(FilenameValidator::class);
  1721. if ($validator->isForbidden($fileName)) {
  1722. $l = \OCP\Util::getL10N('lib');
  1723. throw new InvalidPathException($l->t('Filename is a reserved word'));
  1724. }
  1725. return;
  1726. }
  1727. try {
  1728. /** @type \OCP\Files\Storage $storage */
  1729. [$storage, $internalPath] = $this->resolvePath($path);
  1730. $storage->verifyPath($internalPath, $fileName);
  1731. } catch (ReservedWordException $ex) {
  1732. $l = \OCP\Util::getL10N('lib');
  1733. throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
  1734. } catch (InvalidCharacterInPathException $ex) {
  1735. $l = \OCP\Util::getL10N('lib');
  1736. throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
  1737. } catch (FileNameTooLongException $ex) {
  1738. $l = \OCP\Util::getL10N('lib');
  1739. throw new InvalidPathException($l->t('Filename is too long'));
  1740. } catch (InvalidDirectoryException $ex) {
  1741. $l = \OCP\Util::getL10N('lib');
  1742. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1743. } catch (EmptyFileNameException $ex) {
  1744. $l = \OCP\Util::getL10N('lib');
  1745. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1746. }
  1747. }
  1748. /**
  1749. * get all parent folders of $path
  1750. *
  1751. * @param string $path
  1752. * @return string[]
  1753. */
  1754. private function getParents($path) {
  1755. $path = trim($path, '/');
  1756. if (!$path) {
  1757. return [];
  1758. }
  1759. $parts = explode('/', $path);
  1760. // remove the single file
  1761. array_pop($parts);
  1762. $result = ['/'];
  1763. $resultPath = '';
  1764. foreach ($parts as $part) {
  1765. if ($part) {
  1766. $resultPath .= '/' . $part;
  1767. $result[] = $resultPath;
  1768. }
  1769. }
  1770. return $result;
  1771. }
  1772. /**
  1773. * Returns the mount point for which to lock
  1774. *
  1775. * @param string $absolutePath absolute path
  1776. * @param bool $useParentMount true to return parent mount instead of whatever
  1777. * is mounted directly on the given path, false otherwise
  1778. * @return IMountPoint mount point for which to apply locks
  1779. */
  1780. private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
  1781. $mount = Filesystem::getMountManager()->find($absolutePath);
  1782. if ($useParentMount) {
  1783. // find out if something is mounted directly on the path
  1784. $internalPath = $mount->getInternalPath($absolutePath);
  1785. if ($internalPath === '') {
  1786. // resolve the parent mount instead
  1787. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1788. }
  1789. }
  1790. return $mount;
  1791. }
  1792. /**
  1793. * Lock the given path
  1794. *
  1795. * @param string $path the path of the file to lock, relative to the view
  1796. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1797. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1798. *
  1799. * @return bool False if the path is excluded from locking, true otherwise
  1800. * @throws LockedException if the path is already locked
  1801. */
  1802. private function lockPath($path, $type, $lockMountPoint = false) {
  1803. $absolutePath = $this->getAbsolutePath($path);
  1804. $absolutePath = Filesystem::normalizePath($absolutePath);
  1805. if (!$this->shouldLockFile($absolutePath)) {
  1806. return false;
  1807. }
  1808. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1809. try {
  1810. $storage = $mount->getStorage();
  1811. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1812. $storage->acquireLock(
  1813. $mount->getInternalPath($absolutePath),
  1814. $type,
  1815. $this->lockingProvider
  1816. );
  1817. }
  1818. } catch (LockedException $e) {
  1819. // rethrow with the a human-readable path
  1820. throw new LockedException(
  1821. $this->getPathRelativeToFiles($absolutePath),
  1822. $e,
  1823. $e->getExistingLock()
  1824. );
  1825. }
  1826. return true;
  1827. }
  1828. /**
  1829. * Change the lock type
  1830. *
  1831. * @param string $path the path of the file to lock, relative to the view
  1832. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1833. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1834. *
  1835. * @return bool False if the path is excluded from locking, true otherwise
  1836. * @throws LockedException if the path is already locked
  1837. */
  1838. public function changeLock($path, $type, $lockMountPoint = false) {
  1839. $path = Filesystem::normalizePath($path);
  1840. $absolutePath = $this->getAbsolutePath($path);
  1841. $absolutePath = Filesystem::normalizePath($absolutePath);
  1842. if (!$this->shouldLockFile($absolutePath)) {
  1843. return false;
  1844. }
  1845. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1846. try {
  1847. $storage = $mount->getStorage();
  1848. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1849. $storage->changeLock(
  1850. $mount->getInternalPath($absolutePath),
  1851. $type,
  1852. $this->lockingProvider
  1853. );
  1854. }
  1855. } catch (LockedException $e) {
  1856. try {
  1857. // rethrow with the a human-readable path
  1858. throw new LockedException(
  1859. $this->getPathRelativeToFiles($absolutePath),
  1860. $e,
  1861. $e->getExistingLock()
  1862. );
  1863. } catch (\InvalidArgumentException $ex) {
  1864. throw new LockedException(
  1865. $absolutePath,
  1866. $ex,
  1867. $e->getExistingLock()
  1868. );
  1869. }
  1870. }
  1871. return true;
  1872. }
  1873. /**
  1874. * Unlock the given path
  1875. *
  1876. * @param string $path the path of the file to unlock, relative to the view
  1877. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1878. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1879. *
  1880. * @return bool False if the path is excluded from locking, true otherwise
  1881. * @throws LockedException
  1882. */
  1883. private function unlockPath($path, $type, $lockMountPoint = false) {
  1884. $absolutePath = $this->getAbsolutePath($path);
  1885. $absolutePath = Filesystem::normalizePath($absolutePath);
  1886. if (!$this->shouldLockFile($absolutePath)) {
  1887. return false;
  1888. }
  1889. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1890. $storage = $mount->getStorage();
  1891. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1892. $storage->releaseLock(
  1893. $mount->getInternalPath($absolutePath),
  1894. $type,
  1895. $this->lockingProvider
  1896. );
  1897. }
  1898. return true;
  1899. }
  1900. /**
  1901. * Lock a path and all its parents up to the root of the view
  1902. *
  1903. * @param string $path the path of the file to lock relative to the view
  1904. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1905. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1906. *
  1907. * @return bool False if the path is excluded from locking, true otherwise
  1908. * @throws LockedException
  1909. */
  1910. public function lockFile($path, $type, $lockMountPoint = false) {
  1911. $absolutePath = $this->getAbsolutePath($path);
  1912. $absolutePath = Filesystem::normalizePath($absolutePath);
  1913. if (!$this->shouldLockFile($absolutePath)) {
  1914. return false;
  1915. }
  1916. $this->lockPath($path, $type, $lockMountPoint);
  1917. $parents = $this->getParents($path);
  1918. foreach ($parents as $parent) {
  1919. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1920. }
  1921. return true;
  1922. }
  1923. /**
  1924. * Unlock a path and all its parents up to the root of the view
  1925. *
  1926. * @param string $path the path of the file to lock relative to the view
  1927. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1928. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1929. *
  1930. * @return bool False if the path is excluded from locking, true otherwise
  1931. * @throws LockedException
  1932. */
  1933. public function unlockFile($path, $type, $lockMountPoint = false) {
  1934. $absolutePath = $this->getAbsolutePath($path);
  1935. $absolutePath = Filesystem::normalizePath($absolutePath);
  1936. if (!$this->shouldLockFile($absolutePath)) {
  1937. return false;
  1938. }
  1939. $this->unlockPath($path, $type, $lockMountPoint);
  1940. $parents = $this->getParents($path);
  1941. foreach ($parents as $parent) {
  1942. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1943. }
  1944. return true;
  1945. }
  1946. /**
  1947. * Only lock files in data/user/files/
  1948. *
  1949. * @param string $path Absolute path to the file/folder we try to (un)lock
  1950. * @return bool
  1951. */
  1952. protected function shouldLockFile($path) {
  1953. $path = Filesystem::normalizePath($path);
  1954. $pathSegments = explode('/', $path);
  1955. if (isset($pathSegments[2])) {
  1956. // E.g.: /username/files/path-to-file
  1957. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1958. }
  1959. return !str_starts_with($path, '/appdata_');
  1960. }
  1961. /**
  1962. * Shortens the given absolute path to be relative to
  1963. * "$user/files".
  1964. *
  1965. * @param string $absolutePath absolute path which is under "files"
  1966. *
  1967. * @return string path relative to "files" with trimmed slashes or null
  1968. * if the path was NOT relative to files
  1969. *
  1970. * @throws \InvalidArgumentException if the given path was not under "files"
  1971. * @since 8.1.0
  1972. */
  1973. public function getPathRelativeToFiles($absolutePath) {
  1974. $path = Filesystem::normalizePath($absolutePath);
  1975. $parts = explode('/', trim($path, '/'), 3);
  1976. // "$user", "files", "path/to/dir"
  1977. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1978. $this->logger->error(
  1979. '$absolutePath must be relative to "files", value is "{absolutePath}"',
  1980. [
  1981. 'absolutePath' => $absolutePath,
  1982. ]
  1983. );
  1984. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1985. }
  1986. if (isset($parts[2])) {
  1987. return $parts[2];
  1988. }
  1989. return '';
  1990. }
  1991. /**
  1992. * @param string $filename
  1993. * @return array
  1994. * @throws \OC\User\NoUserException
  1995. * @throws NotFoundException
  1996. */
  1997. public function getUidAndFilename($filename) {
  1998. $info = $this->getFileInfo($filename);
  1999. if (!$info instanceof \OCP\Files\FileInfo) {
  2000. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  2001. }
  2002. $uid = $info->getOwner()->getUID();
  2003. if ($uid != \OC_User::getUser()) {
  2004. Filesystem::initMountPoints($uid);
  2005. $ownerView = new View('/' . $uid . '/files');
  2006. try {
  2007. $filename = $ownerView->getPath($info['fileid']);
  2008. } catch (NotFoundException $e) {
  2009. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  2010. }
  2011. }
  2012. return [$uid, $filename];
  2013. }
  2014. /**
  2015. * Creates parent non-existing folders
  2016. *
  2017. * @param string $filePath
  2018. * @return bool
  2019. */
  2020. private function createParentDirectories($filePath) {
  2021. $directoryParts = explode('/', $filePath);
  2022. $directoryParts = array_filter($directoryParts);
  2023. foreach ($directoryParts as $key => $part) {
  2024. $currentPathElements = array_slice($directoryParts, 0, $key);
  2025. $currentPath = '/' . implode('/', $currentPathElements);
  2026. if ($this->is_file($currentPath)) {
  2027. return false;
  2028. }
  2029. if (!$this->file_exists($currentPath)) {
  2030. $this->mkdir($currentPath);
  2031. }
  2032. }
  2033. return true;
  2034. }
  2035. }