1
0

View.php 66 KB

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