View.php 66 KB

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