SMB.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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 OCA\Files_External\Lib\Storage;
  8. use Icewind\SMB\ACL;
  9. use Icewind\SMB\BasicAuth;
  10. use Icewind\SMB\Exception\AlreadyExistsException;
  11. use Icewind\SMB\Exception\ConnectException;
  12. use Icewind\SMB\Exception\Exception;
  13. use Icewind\SMB\Exception\ForbiddenException;
  14. use Icewind\SMB\Exception\InvalidArgumentException;
  15. use Icewind\SMB\Exception\InvalidTypeException;
  16. use Icewind\SMB\Exception\NotFoundException;
  17. use Icewind\SMB\Exception\OutOfSpaceException;
  18. use Icewind\SMB\Exception\TimedOutException;
  19. use Icewind\SMB\IFileInfo;
  20. use Icewind\SMB\Native\NativeServer;
  21. use Icewind\SMB\Options;
  22. use Icewind\SMB\ServerFactory;
  23. use Icewind\SMB\Wrapped\Server;
  24. use Icewind\Streams\CallbackWrapper;
  25. use Icewind\Streams\IteratorDirectory;
  26. use OC\Files\Filesystem;
  27. use OC\Files\Storage\Common;
  28. use OCA\Files_External\Lib\Notify\SMBNotifyHandler;
  29. use OCP\Cache\CappedMemoryCache;
  30. use OCP\Constants;
  31. use OCP\Files\EntityTooLargeException;
  32. use OCP\Files\Notify\IChange;
  33. use OCP\Files\Notify\IRenameChange;
  34. use OCP\Files\NotPermittedException;
  35. use OCP\Files\Storage\INotifyStorage;
  36. use OCP\Files\StorageAuthException;
  37. use OCP\Files\StorageNotAvailableException;
  38. use Psr\Log\LoggerInterface;
  39. class SMB extends Common implements INotifyStorage {
  40. /**
  41. * @var \Icewind\SMB\IServer
  42. */
  43. protected $server;
  44. /**
  45. * @var \Icewind\SMB\IShare
  46. */
  47. protected $share;
  48. /**
  49. * @var string
  50. */
  51. protected $root;
  52. /** @var CappedMemoryCache<IFileInfo> */
  53. protected CappedMemoryCache $statCache;
  54. /** @var LoggerInterface */
  55. protected $logger;
  56. /** @var bool */
  57. protected $showHidden;
  58. private bool $caseSensitive;
  59. /** @var bool */
  60. protected $checkAcl;
  61. public function __construct(array $parameters) {
  62. if (!isset($parameters['host'])) {
  63. throw new \Exception('Invalid configuration, no host provided');
  64. }
  65. if (isset($parameters['auth'])) {
  66. $auth = $parameters['auth'];
  67. } elseif (isset($parameters['user']) && isset($parameters['password']) && isset($parameters['share'])) {
  68. [$workgroup, $user] = $this->splitUser($parameters['user']);
  69. $auth = new BasicAuth($user, $workgroup, $parameters['password']);
  70. } else {
  71. throw new \Exception('Invalid configuration, no credentials provided');
  72. }
  73. if (isset($parameters['logger'])) {
  74. if (!$parameters['logger'] instanceof LoggerInterface) {
  75. throw new \Exception(
  76. 'Invalid logger. Got '
  77. . get_class($parameters['logger'])
  78. . ' Expected ' . LoggerInterface::class
  79. );
  80. }
  81. $this->logger = $parameters['logger'];
  82. } else {
  83. $this->logger = \OCP\Server::get(LoggerInterface::class);
  84. }
  85. $options = new Options();
  86. if (isset($parameters['timeout'])) {
  87. $timeout = (int)$parameters['timeout'];
  88. if ($timeout > 0) {
  89. $options->setTimeout($timeout);
  90. }
  91. }
  92. $system = \OCP\Server::get(SystemBridge::class);
  93. $serverFactory = new ServerFactory($options, $system);
  94. $this->server = $serverFactory->createServer($parameters['host'], $auth);
  95. $this->share = $this->server->getShare(trim($parameters['share'], '/'));
  96. $this->root = $parameters['root'] ?? '/';
  97. $this->root = '/' . ltrim($this->root, '/');
  98. $this->root = rtrim($this->root, '/') . '/';
  99. $this->showHidden = isset($parameters['show_hidden']) && $parameters['show_hidden'];
  100. $this->caseSensitive = (bool)($parameters['case_sensitive'] ?? true);
  101. $this->checkAcl = isset($parameters['check_acl']) && $parameters['check_acl'];
  102. $this->statCache = new CappedMemoryCache();
  103. parent::__construct($parameters);
  104. }
  105. private function splitUser(string $user): array {
  106. if (str_contains($user, '/')) {
  107. return explode('/', $user, 2);
  108. } elseif (str_contains($user, '\\')) {
  109. return explode('\\', $user);
  110. }
  111. return [null, $user];
  112. }
  113. public function getId(): string {
  114. // FIXME: double slash to keep compatible with the old storage ids,
  115. // failure to do so will lead to creation of a new storage id and
  116. // loss of shares from the storage
  117. return 'smb::' . $this->server->getAuth()->getUsername() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
  118. }
  119. protected function buildPath(string $path): string {
  120. return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
  121. }
  122. protected function relativePath(string $fullPath): ?string {
  123. if ($fullPath === $this->root) {
  124. return '';
  125. } elseif (substr($fullPath, 0, strlen($this->root)) === $this->root) {
  126. return substr($fullPath, strlen($this->root));
  127. } else {
  128. return null;
  129. }
  130. }
  131. /**
  132. * @throws StorageAuthException
  133. * @throws \OCP\Files\NotFoundException
  134. * @throws \OCP\Files\ForbiddenException
  135. */
  136. protected function getFileInfo(string $path): IFileInfo {
  137. try {
  138. $path = $this->buildPath($path);
  139. $cached = $this->statCache[$path] ?? null;
  140. if ($cached instanceof IFileInfo) {
  141. return $cached;
  142. } else {
  143. $stat = $this->share->stat($path);
  144. $this->statCache[$path] = $stat;
  145. return $stat;
  146. }
  147. } catch (ConnectException $e) {
  148. $this->throwUnavailable($e);
  149. } catch (NotFoundException $e) {
  150. throw new \OCP\Files\NotFoundException($e->getMessage(), 0, $e);
  151. } catch (ForbiddenException $e) {
  152. // with php-smbclient, this exception is thrown when the provided password is invalid.
  153. // Possible is also ForbiddenException with a different error code, so we check it.
  154. if ($e->getCode() === 1) {
  155. $this->throwUnavailable($e);
  156. }
  157. throw new \OCP\Files\ForbiddenException($e->getMessage(), false, $e);
  158. }
  159. }
  160. /**
  161. * @throws StorageAuthException
  162. */
  163. protected function throwUnavailable(\Exception $e): never {
  164. $this->logger->error('Error while getting file info', ['exception' => $e]);
  165. throw new StorageAuthException($e->getMessage(), $e);
  166. }
  167. /**
  168. * get the acl from fileinfo that is relevant for the configured user
  169. */
  170. private function getACL(IFileInfo $file): ?ACL {
  171. $acls = $file->getAcls();
  172. foreach ($acls as $user => $acl) {
  173. [, $user] = $this->splitUser($user); // strip domain
  174. if ($user === $this->server->getAuth()->getUsername()) {
  175. return $acl;
  176. }
  177. }
  178. return null;
  179. }
  180. /**
  181. * @return \Generator<IFileInfo>
  182. * @throws StorageNotAvailableException
  183. */
  184. protected function getFolderContents(string $path): iterable {
  185. try {
  186. $path = ltrim($this->buildPath($path), '/');
  187. try {
  188. $files = $this->share->dir($path);
  189. } catch (ForbiddenException $e) {
  190. $this->logger->critical($e->getMessage(), ['exception' => $e]);
  191. throw new NotPermittedException();
  192. } catch (InvalidTypeException $e) {
  193. return;
  194. }
  195. foreach ($files as $file) {
  196. $this->statCache[$path . '/' . $file->getName()] = $file;
  197. }
  198. foreach ($files as $file) {
  199. try {
  200. // the isHidden check is done before checking the config boolean to ensure that the metadata is always fetch
  201. // so we trigger the below exceptions where applicable
  202. $hide = $file->isHidden() && !$this->showHidden;
  203. if ($this->checkAcl && $acl = $this->getACL($file)) {
  204. // if there is no explicit deny, we assume it's allowed
  205. // this doesn't take inheritance fully into account but if read permissions is denied for a parent we wouldn't be in this folder
  206. // additionally, it's better to have false negatives here then false positives
  207. if ($acl->denies(ACL::MASK_READ) || $acl->denies(ACL::MASK_EXECUTE)) {
  208. $this->logger->debug('Hiding non readable entry ' . $file->getName());
  209. continue;
  210. }
  211. }
  212. if ($hide) {
  213. $this->logger->debug('hiding hidden file ' . $file->getName());
  214. }
  215. if (!$hide) {
  216. yield $file;
  217. }
  218. } catch (ForbiddenException $e) {
  219. $this->logger->debug($e->getMessage(), ['exception' => $e]);
  220. } catch (NotFoundException $e) {
  221. $this->logger->debug('Hiding forbidden entry ' . $file->getName(), ['exception' => $e]);
  222. }
  223. }
  224. } catch (ConnectException $e) {
  225. $this->logger->error('Error while getting folder content', ['exception' => $e]);
  226. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  227. } catch (NotFoundException $e) {
  228. throw new \OCP\Files\NotFoundException($e->getMessage(), 0, $e);
  229. }
  230. }
  231. protected function formatInfo(IFileInfo $info): array {
  232. $result = [
  233. 'size' => $info->getSize(),
  234. 'mtime' => $info->getMTime(),
  235. ];
  236. if ($info->isDirectory()) {
  237. $result['type'] = 'dir';
  238. } else {
  239. $result['type'] = 'file';
  240. }
  241. return $result;
  242. }
  243. /**
  244. * Rename the files. If the source or the target is the root, the rename won't happen.
  245. *
  246. * @param string $source the old name of the path
  247. * @param string $target the new name of the path
  248. */
  249. public function rename(string $source, string $target, bool $retry = true): bool {
  250. if ($this->isRootDir($source) || $this->isRootDir($target)) {
  251. return false;
  252. }
  253. if ($this->caseSensitive === false
  254. && mb_strtolower($target) === mb_strtolower($source)
  255. ) {
  256. // Forbid changing case only on case-insensitive file system
  257. return false;
  258. }
  259. $absoluteSource = $this->buildPath($source);
  260. $absoluteTarget = $this->buildPath($target);
  261. try {
  262. $result = $this->share->rename($absoluteSource, $absoluteTarget);
  263. } catch (AlreadyExistsException $e) {
  264. if ($retry) {
  265. $this->remove($target);
  266. $result = $this->share->rename($absoluteSource, $absoluteTarget);
  267. } else {
  268. $this->logger->warning($e->getMessage(), ['exception' => $e]);
  269. return false;
  270. }
  271. } catch (InvalidArgumentException $e) {
  272. if ($retry) {
  273. $this->remove($target);
  274. $result = $this->share->rename($absoluteSource, $absoluteTarget);
  275. } else {
  276. $this->logger->warning($e->getMessage(), ['exception' => $e]);
  277. return false;
  278. }
  279. } catch (\Exception $e) {
  280. $this->logger->warning($e->getMessage(), ['exception' => $e]);
  281. return false;
  282. }
  283. unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
  284. return $result;
  285. }
  286. public function stat(string $path, bool $retry = true): array|false {
  287. try {
  288. $result = $this->formatInfo($this->getFileInfo($path));
  289. } catch (\OCP\Files\ForbiddenException $e) {
  290. return false;
  291. } catch (\OCP\Files\NotFoundException $e) {
  292. return false;
  293. } catch (TimedOutException $e) {
  294. if ($retry) {
  295. return $this->stat($path, false);
  296. } else {
  297. throw $e;
  298. }
  299. }
  300. if ($this->remoteIsShare() && $this->isRootDir($path)) {
  301. $result['mtime'] = $this->shareMTime();
  302. }
  303. return $result;
  304. }
  305. /**
  306. * get the best guess for the modification time of the share
  307. */
  308. private function shareMTime(): int {
  309. $highestMTime = 0;
  310. $files = $this->share->dir($this->root);
  311. foreach ($files as $fileInfo) {
  312. try {
  313. if ($fileInfo->getMTime() > $highestMTime) {
  314. $highestMTime = $fileInfo->getMTime();
  315. }
  316. } catch (NotFoundException $e) {
  317. // Ignore this, can happen on unavailable DFS shares
  318. } catch (ForbiddenException $e) {
  319. // Ignore this too - it's a symlink
  320. }
  321. }
  322. return $highestMTime;
  323. }
  324. /**
  325. * Check if the path is our root dir (not the smb one)
  326. */
  327. private function isRootDir(string $path): bool {
  328. return $path === '' || $path === '/' || $path === '.';
  329. }
  330. /**
  331. * Check if our root points to a smb share
  332. */
  333. private function remoteIsShare(): bool {
  334. return $this->share->getName() && (!$this->root || $this->root === '/');
  335. }
  336. public function unlink(string $path): bool {
  337. if ($this->isRootDir($path)) {
  338. return false;
  339. }
  340. try {
  341. if ($this->is_dir($path)) {
  342. return $this->rmdir($path);
  343. } else {
  344. $path = $this->buildPath($path);
  345. unset($this->statCache[$path]);
  346. $this->share->del($path);
  347. return true;
  348. }
  349. } catch (NotFoundException $e) {
  350. return false;
  351. } catch (ForbiddenException $e) {
  352. return false;
  353. } catch (ConnectException $e) {
  354. $this->logger->error('Error while deleting file', ['exception' => $e]);
  355. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  356. }
  357. }
  358. /**
  359. * check if a file or folder has been updated since $time
  360. */
  361. public function hasUpdated(string $path, int $time): bool {
  362. if (!$path and $this->root === '/') {
  363. // mtime doesn't work for shares, but giving the nature of the backend,
  364. // doing a full update is still just fast enough
  365. return true;
  366. } else {
  367. $actualTime = $this->filemtime($path);
  368. return $actualTime > $time;
  369. }
  370. }
  371. /**
  372. * @return resource|false
  373. */
  374. public function fopen(string $path, string $mode) {
  375. $fullPath = $this->buildPath($path);
  376. try {
  377. switch ($mode) {
  378. case 'r':
  379. case 'rb':
  380. if (!$this->file_exists($path)) {
  381. return false;
  382. }
  383. return $this->share->read($fullPath);
  384. case 'w':
  385. case 'wb':
  386. $source = $this->share->write($fullPath);
  387. return CallBackWrapper::wrap($source, null, null, function () use ($fullPath): void {
  388. unset($this->statCache[$fullPath]);
  389. });
  390. case 'a':
  391. case 'ab':
  392. case 'r+':
  393. case 'w+':
  394. case 'wb+':
  395. case 'a+':
  396. case 'x':
  397. case 'x+':
  398. case 'c':
  399. case 'c+':
  400. //emulate these
  401. if (strrpos($path, '.') !== false) {
  402. $ext = substr($path, strrpos($path, '.'));
  403. } else {
  404. $ext = '';
  405. }
  406. if ($this->file_exists($path)) {
  407. if (!$this->isUpdatable($path)) {
  408. return false;
  409. }
  410. $tmpFile = $this->getCachedFile($path);
  411. } else {
  412. if (!$this->isCreatable(dirname($path))) {
  413. return false;
  414. }
  415. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  416. }
  417. $source = fopen($tmpFile, $mode);
  418. $share = $this->share;
  419. return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share): void {
  420. unset($this->statCache[$fullPath]);
  421. $share->put($tmpFile, $fullPath);
  422. unlink($tmpFile);
  423. });
  424. }
  425. return false;
  426. } catch (NotFoundException $e) {
  427. return false;
  428. } catch (ForbiddenException $e) {
  429. return false;
  430. } catch (OutOfSpaceException $e) {
  431. throw new EntityTooLargeException('not enough available space to create file', 0, $e);
  432. } catch (ConnectException $e) {
  433. $this->logger->error('Error while opening file', ['exception' => $e]);
  434. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  435. }
  436. }
  437. public function rmdir(string $path): bool {
  438. if ($this->isRootDir($path)) {
  439. return false;
  440. }
  441. try {
  442. $this->statCache = new CappedMemoryCache();
  443. $content = $this->share->dir($this->buildPath($path));
  444. foreach ($content as $file) {
  445. if ($file->isDirectory()) {
  446. $this->rmdir($path . '/' . $file->getName());
  447. } else {
  448. $this->share->del($file->getPath());
  449. }
  450. }
  451. $this->share->rmdir($this->buildPath($path));
  452. return true;
  453. } catch (NotFoundException $e) {
  454. return false;
  455. } catch (ForbiddenException $e) {
  456. return false;
  457. } catch (ConnectException $e) {
  458. $this->logger->error('Error while removing folder', ['exception' => $e]);
  459. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  460. }
  461. }
  462. public function touch(string $path, ?int $mtime = null): bool {
  463. try {
  464. if (!$this->file_exists($path)) {
  465. $fh = $this->share->write($this->buildPath($path));
  466. fclose($fh);
  467. return true;
  468. }
  469. return false;
  470. } catch (OutOfSpaceException $e) {
  471. throw new EntityTooLargeException('not enough available space to create file', 0, $e);
  472. } catch (ConnectException $e) {
  473. $this->logger->error('Error while creating file', ['exception' => $e]);
  474. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  475. }
  476. }
  477. public function getMetaData(string $path): ?array {
  478. try {
  479. $fileInfo = $this->getFileInfo($path);
  480. } catch (\OCP\Files\NotFoundException $e) {
  481. return null;
  482. } catch (\OCP\Files\ForbiddenException $e) {
  483. return null;
  484. }
  485. return $this->getMetaDataFromFileInfo($fileInfo);
  486. }
  487. private function getMetaDataFromFileInfo(IFileInfo $fileInfo): array {
  488. $permissions = Constants::PERMISSION_READ + Constants::PERMISSION_SHARE;
  489. if (
  490. !$fileInfo->isReadOnly() || $fileInfo->isDirectory()
  491. ) {
  492. $permissions += Constants::PERMISSION_DELETE;
  493. $permissions += Constants::PERMISSION_UPDATE;
  494. if ($fileInfo->isDirectory()) {
  495. $permissions += Constants::PERMISSION_CREATE;
  496. }
  497. }
  498. $data = [];
  499. if ($fileInfo->isDirectory()) {
  500. $data['mimetype'] = 'httpd/unix-directory';
  501. } else {
  502. $data['mimetype'] = \OC::$server->getMimeTypeDetector()->detectPath($fileInfo->getPath());
  503. }
  504. $data['mtime'] = $fileInfo->getMTime();
  505. if ($fileInfo->isDirectory()) {
  506. $data['size'] = -1; //unknown
  507. } else {
  508. $data['size'] = $fileInfo->getSize();
  509. }
  510. $data['etag'] = $this->getETag($fileInfo->getPath());
  511. $data['storage_mtime'] = $data['mtime'];
  512. $data['permissions'] = $permissions;
  513. $data['name'] = $fileInfo->getName();
  514. return $data;
  515. }
  516. public function opendir(string $path) {
  517. try {
  518. $files = $this->getFolderContents($path);
  519. } catch (NotFoundException $e) {
  520. return false;
  521. } catch (NotPermittedException $e) {
  522. return false;
  523. }
  524. $names = array_map(function ($info) {
  525. /** @var IFileInfo $info */
  526. return $info->getName();
  527. }, iterator_to_array($files));
  528. return IteratorDirectory::wrap($names);
  529. }
  530. public function getDirectoryContent(string $directory): \Traversable {
  531. try {
  532. $files = $this->getFolderContents($directory);
  533. foreach ($files as $file) {
  534. yield $this->getMetaDataFromFileInfo($file);
  535. }
  536. } catch (NotFoundException $e) {
  537. return;
  538. } catch (NotPermittedException $e) {
  539. return;
  540. }
  541. }
  542. public function filetype(string $path): string|false {
  543. try {
  544. return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
  545. } catch (\OCP\Files\NotFoundException $e) {
  546. return false;
  547. } catch (\OCP\Files\ForbiddenException $e) {
  548. return false;
  549. }
  550. }
  551. public function mkdir(string $path): bool {
  552. $path = $this->buildPath($path);
  553. try {
  554. $this->share->mkdir($path);
  555. return true;
  556. } catch (ConnectException $e) {
  557. $this->logger->error('Error while creating folder', ['exception' => $e]);
  558. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  559. } catch (Exception $e) {
  560. return false;
  561. }
  562. }
  563. public function file_exists(string $path): bool {
  564. try {
  565. // Case sensitive filesystem doesn't matter for root directory
  566. if ($this->caseSensitive === false && $path !== '') {
  567. $filename = basename($path);
  568. $siblings = $this->getDirectoryContent(dirname($this->buildPath($path)));
  569. foreach ($siblings as $sibling) {
  570. if ($sibling['name'] === $filename) {
  571. return true;
  572. }
  573. }
  574. return false;
  575. }
  576. $this->getFileInfo($path);
  577. return true;
  578. } catch (\OCP\Files\NotFoundException $e) {
  579. return false;
  580. } catch (\OCP\Files\ForbiddenException $e) {
  581. return false;
  582. } catch (ConnectException $e) {
  583. throw new StorageNotAvailableException($e->getMessage(), (int)$e->getCode(), $e);
  584. }
  585. }
  586. public function isReadable(string $path): bool {
  587. try {
  588. $info = $this->getFileInfo($path);
  589. return $this->showHidden || !$info->isHidden();
  590. } catch (\OCP\Files\NotFoundException $e) {
  591. return false;
  592. } catch (\OCP\Files\ForbiddenException $e) {
  593. return false;
  594. }
  595. }
  596. public function isUpdatable(string $path): bool {
  597. try {
  598. $info = $this->getFileInfo($path);
  599. // following windows behaviour for read-only folders: they can be written into
  600. // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
  601. return ($this->showHidden || !$info->isHidden()) && (!$info->isReadOnly() || $info->isDirectory());
  602. } catch (\OCP\Files\NotFoundException $e) {
  603. return false;
  604. } catch (\OCP\Files\ForbiddenException $e) {
  605. return false;
  606. }
  607. }
  608. public function isDeletable(string $path): bool {
  609. try {
  610. $info = $this->getFileInfo($path);
  611. return ($this->showHidden || !$info->isHidden()) && !$info->isReadOnly();
  612. } catch (\OCP\Files\NotFoundException $e) {
  613. return false;
  614. } catch (\OCP\Files\ForbiddenException $e) {
  615. return false;
  616. }
  617. }
  618. /**
  619. * check if smbclient is installed
  620. */
  621. public static function checkDependencies(): array|bool {
  622. $system = \OCP\Server::get(SystemBridge::class);
  623. return Server::available($system) || NativeServer::available($system) ?: ['smbclient'];
  624. }
  625. public function test(): bool {
  626. try {
  627. return parent::test();
  628. } catch (StorageAuthException $e) {
  629. return false;
  630. } catch (ForbiddenException $e) {
  631. return false;
  632. } catch (Exception $e) {
  633. $this->logger->error($e->getMessage(), ['exception' => $e]);
  634. return false;
  635. }
  636. }
  637. public function listen(string $path, callable $callback): void {
  638. $this->notify($path)->listen(function (IChange $change) use ($callback) {
  639. if ($change instanceof IRenameChange) {
  640. return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
  641. } else {
  642. return $callback($change->getType(), $change->getPath());
  643. }
  644. });
  645. }
  646. public function notify(string $path): SMBNotifyHandler {
  647. $path = '/' . ltrim($path, '/');
  648. $shareNotifyHandler = $this->share->notify($this->buildPath($path));
  649. return new SMBNotifyHandler($shareNotifyHandler, $this->root);
  650. }
  651. }