You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SMB.php 17KB

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