SMB.php 21 KB

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