SMB.php 22 KB

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