View.php 69 KB

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