View.php 65 KB

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