SMB.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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\Exception\AlreadyExistsException;
  36. use Icewind\SMB\Exception\ConnectException;
  37. use Icewind\SMB\Exception\Exception;
  38. use Icewind\SMB\Exception\ForbiddenException;
  39. use Icewind\SMB\Exception\NotFoundException;
  40. use Icewind\SMB\IFileInfo;
  41. use Icewind\SMB\NativeServer;
  42. use Icewind\SMB\Server;
  43. use Icewind\Streams\CallbackWrapper;
  44. use Icewind\Streams\IteratorDirectory;
  45. use OC\Cache\CappedMemoryCache;
  46. use OC\Files\Filesystem;
  47. use OC\Files\Storage\Common;
  48. use OCA\Files_External\Lib\Notify\SMBNotifyHandler;
  49. use OCP\Files\Notify\IChange;
  50. use OCP\Files\Notify\IRenameChange;
  51. use OCP\Files\Storage\INotifyStorage;
  52. use OCP\Files\StorageNotAvailableException;
  53. use OCP\ILogger;
  54. use OCP\Util;
  55. class SMB extends Common implements INotifyStorage {
  56. /**
  57. * @var \Icewind\SMB\Server
  58. */
  59. protected $server;
  60. /**
  61. * @var \Icewind\SMB\Share
  62. */
  63. protected $share;
  64. /**
  65. * @var string
  66. */
  67. protected $root;
  68. /**
  69. * @var \Icewind\SMB\FileInfo[]
  70. */
  71. protected $statCache;
  72. public function __construct($params) {
  73. if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
  74. if (Server::NativeAvailable()) {
  75. $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
  76. } else {
  77. $this->server = new Server($params['host'], $params['user'], $params['password']);
  78. }
  79. $this->share = $this->server->getShare(trim($params['share'], '/'));
  80. $this->root = $params['root'] ?? '/';
  81. $this->root = '/' . ltrim($this->root, '/');
  82. $this->root = rtrim($this->root, '/') . '/';
  83. } else {
  84. throw new \Exception('Invalid configuration');
  85. }
  86. $this->statCache = new CappedMemoryCache();
  87. parent::__construct($params);
  88. }
  89. /**
  90. * @return string
  91. */
  92. public function getId() {
  93. // FIXME: double slash to keep compatible with the old storage ids,
  94. // failure to do so will lead to creation of a new storage id and
  95. // loss of shares from the storage
  96. return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
  97. }
  98. /**
  99. * @param string $path
  100. * @return string
  101. */
  102. protected function buildPath($path) {
  103. return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
  104. }
  105. protected function relativePath($fullPath) {
  106. if ($fullPath === $this->root) {
  107. return '';
  108. } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
  109. return substr($fullPath, strlen($this->root));
  110. } else {
  111. return null;
  112. }
  113. }
  114. /**
  115. * @param string $path
  116. * @return \Icewind\SMB\IFileInfo
  117. * @throws StorageNotAvailableException
  118. */
  119. protected function getFileInfo($path) {
  120. try {
  121. $path = $this->buildPath($path);
  122. if (!isset($this->statCache[$path])) {
  123. $this->statCache[$path] = $this->share->stat($path);
  124. }
  125. return $this->statCache[$path];
  126. } catch (ConnectException $e) {
  127. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  128. }
  129. }
  130. /**
  131. * @param string $path
  132. * @return \Icewind\SMB\IFileInfo[]
  133. * @throws StorageNotAvailableException
  134. */
  135. protected function getFolderContents($path) {
  136. try {
  137. $path = $this->buildPath($path);
  138. $files = $this->share->dir($path);
  139. foreach ($files as $file) {
  140. $this->statCache[$path . '/' . $file->getName()] = $file;
  141. }
  142. return array_filter($files, function (IFileInfo $file) {
  143. try {
  144. return !$file->isHidden();
  145. } catch (ForbiddenException $e) {
  146. return false;
  147. } catch (NotFoundException $e) {
  148. return false;
  149. }
  150. });
  151. } catch (ConnectException $e) {
  152. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  153. }
  154. }
  155. /**
  156. * @param \Icewind\SMB\IFileInfo $info
  157. * @return array
  158. */
  159. protected function formatInfo($info) {
  160. $result = [
  161. 'size' => $info->getSize(),
  162. 'mtime' => $info->getMTime(),
  163. ];
  164. if ($info->isDirectory()) {
  165. $result['type'] = 'dir';
  166. } else {
  167. $result['type'] = 'file';
  168. }
  169. return $result;
  170. }
  171. /**
  172. * Rename the files. If the source or the target is the root, the rename won't happen.
  173. *
  174. * @param string $source the old name of the path
  175. * @param string $target the new name of the path
  176. * @return bool true if the rename is successful, false otherwise
  177. */
  178. public function rename($source, $target) {
  179. if ($this->isRootDir($source) || $this->isRootDir($target)) {
  180. return false;
  181. }
  182. $absoluteSource = $this->buildPath($source);
  183. $absoluteTarget = $this->buildPath($target);
  184. try {
  185. $result = $this->share->rename($absoluteSource, $absoluteTarget);
  186. } catch (AlreadyExistsException $e) {
  187. $this->remove($target);
  188. $result = $this->share->rename($absoluteSource, $absoluteTarget);
  189. } catch (\Exception $e) {
  190. \OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
  191. return false;
  192. }
  193. unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
  194. return $result;
  195. }
  196. public function stat($path) {
  197. try {
  198. $result = $this->formatInfo($this->getFileInfo($path));
  199. } catch (ForbiddenException $e) {
  200. return false;
  201. } catch (NotFoundException $e) {
  202. return false;
  203. }
  204. if ($this->remoteIsShare() && $this->isRootDir($path)) {
  205. $result['mtime'] = $this->shareMTime();
  206. }
  207. return $result;
  208. }
  209. /**
  210. * get the best guess for the modification time of the share
  211. *
  212. * @return int
  213. */
  214. private function shareMTime() {
  215. $highestMTime = 0;
  216. $files = $this->share->dir($this->root);
  217. foreach ($files as $fileInfo) {
  218. try {
  219. if ($fileInfo->getMTime() > $highestMTime) {
  220. $highestMTime = $fileInfo->getMTime();
  221. }
  222. } catch (NotFoundException $e) {
  223. // Ignore this, can happen on unavailable DFS shares
  224. }
  225. }
  226. return $highestMTime;
  227. }
  228. /**
  229. * Check if the path is our root dir (not the smb one)
  230. *
  231. * @param string $path the path
  232. * @return bool
  233. */
  234. private function isRootDir($path) {
  235. return $path === '' || $path === '/' || $path === '.';
  236. }
  237. /**
  238. * Check if our root points to a smb share
  239. *
  240. * @return bool true if our root points to a share false otherwise
  241. */
  242. private function remoteIsShare() {
  243. return $this->share->getName() && (!$this->root || $this->root === '/');
  244. }
  245. /**
  246. * @param string $path
  247. * @return bool
  248. */
  249. public function unlink($path) {
  250. if ($this->isRootDir($path)) {
  251. return false;
  252. }
  253. try {
  254. if ($this->is_dir($path)) {
  255. return $this->rmdir($path);
  256. } else {
  257. $path = $this->buildPath($path);
  258. unset($this->statCache[$path]);
  259. $this->share->del($path);
  260. return true;
  261. }
  262. } catch (NotFoundException $e) {
  263. return false;
  264. } catch (ForbiddenException $e) {
  265. return false;
  266. } catch (ConnectException $e) {
  267. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  268. }
  269. }
  270. /**
  271. * check if a file or folder has been updated since $time
  272. *
  273. * @param string $path
  274. * @param int $time
  275. * @return bool
  276. */
  277. public function hasUpdated($path, $time) {
  278. if (!$path and $this->root === '/') {
  279. // mtime doesn't work for shares, but giving the nature of the backend,
  280. // doing a full update is still just fast enough
  281. return true;
  282. } else {
  283. $actualTime = $this->filemtime($path);
  284. return $actualTime > $time;
  285. }
  286. }
  287. /**
  288. * @param string $path
  289. * @param string $mode
  290. * @return resource|false
  291. */
  292. public function fopen($path, $mode) {
  293. $fullPath = $this->buildPath($path);
  294. try {
  295. switch ($mode) {
  296. case 'r':
  297. case 'rb':
  298. if (!$this->file_exists($path)) {
  299. return false;
  300. }
  301. return $this->share->read($fullPath);
  302. case 'w':
  303. case 'wb':
  304. $source = $this->share->write($fullPath);
  305. return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
  306. unset($this->statCache[$fullPath]);
  307. });
  308. case 'a':
  309. case 'ab':
  310. case 'r+':
  311. case 'w+':
  312. case 'wb+':
  313. case 'a+':
  314. case 'x':
  315. case 'x+':
  316. case 'c':
  317. case 'c+':
  318. //emulate these
  319. if (strrpos($path, '.') !== false) {
  320. $ext = substr($path, strrpos($path, '.'));
  321. } else {
  322. $ext = '';
  323. }
  324. if ($this->file_exists($path)) {
  325. if (!$this->isUpdatable($path)) {
  326. return false;
  327. }
  328. $tmpFile = $this->getCachedFile($path);
  329. } else {
  330. if (!$this->isCreatable(dirname($path))) {
  331. return false;
  332. }
  333. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  334. }
  335. $source = fopen($tmpFile, $mode);
  336. $share = $this->share;
  337. return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
  338. unset($this->statCache[$fullPath]);
  339. $share->put($tmpFile, $fullPath);
  340. unlink($tmpFile);
  341. });
  342. }
  343. return false;
  344. } catch (NotFoundException $e) {
  345. return false;
  346. } catch (ForbiddenException $e) {
  347. return false;
  348. } catch (ConnectException $e) {
  349. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  350. }
  351. }
  352. public function rmdir($path) {
  353. if ($this->isRootDir($path)) {
  354. return false;
  355. }
  356. try {
  357. $this->statCache = array();
  358. $content = $this->share->dir($this->buildPath($path));
  359. foreach ($content as $file) {
  360. if ($file->isDirectory()) {
  361. $this->rmdir($path . '/' . $file->getName());
  362. } else {
  363. $this->share->del($file->getPath());
  364. }
  365. }
  366. $this->share->rmdir($this->buildPath($path));
  367. return true;
  368. } catch (NotFoundException $e) {
  369. return false;
  370. } catch (ForbiddenException $e) {
  371. return false;
  372. } catch (ConnectException $e) {
  373. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  374. }
  375. }
  376. public function touch($path, $time = null) {
  377. try {
  378. if (!$this->file_exists($path)) {
  379. $fh = $this->share->write($this->buildPath($path));
  380. fclose($fh);
  381. return true;
  382. }
  383. return false;
  384. } catch (ConnectException $e) {
  385. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  386. }
  387. }
  388. public function opendir($path) {
  389. try {
  390. $files = $this->getFolderContents($path);
  391. } catch (NotFoundException $e) {
  392. return false;
  393. } catch (ForbiddenException $e) {
  394. return false;
  395. }
  396. $names = array_map(function ($info) {
  397. /** @var \Icewind\SMB\IFileInfo $info */
  398. return $info->getName();
  399. }, $files);
  400. return IteratorDirectory::wrap($names);
  401. }
  402. public function filetype($path) {
  403. try {
  404. return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
  405. } catch (NotFoundException $e) {
  406. return false;
  407. } catch (ForbiddenException $e) {
  408. return false;
  409. }
  410. }
  411. public function mkdir($path) {
  412. $path = $this->buildPath($path);
  413. try {
  414. $this->share->mkdir($path);
  415. return true;
  416. } catch (ConnectException $e) {
  417. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  418. } catch (Exception $e) {
  419. return false;
  420. }
  421. }
  422. public function file_exists($path) {
  423. try {
  424. $this->getFileInfo($path);
  425. return true;
  426. } catch (NotFoundException $e) {
  427. return false;
  428. } catch (ForbiddenException $e) {
  429. return false;
  430. } catch (ConnectException $e) {
  431. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  432. }
  433. }
  434. public function isReadable($path) {
  435. try {
  436. $info = $this->getFileInfo($path);
  437. return !$info->isHidden();
  438. } catch (NotFoundException $e) {
  439. return false;
  440. } catch (ForbiddenException $e) {
  441. return false;
  442. }
  443. }
  444. public function isUpdatable($path) {
  445. try {
  446. $info = $this->getFileInfo($path);
  447. // following windows behaviour for read-only folders: they can be written into
  448. // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
  449. return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
  450. } catch (NotFoundException $e) {
  451. return false;
  452. } catch (ForbiddenException $e) {
  453. return false;
  454. }
  455. }
  456. public function isDeletable($path) {
  457. try {
  458. $info = $this->getFileInfo($path);
  459. return !$info->isHidden() && !$info->isReadOnly();
  460. } catch (NotFoundException $e) {
  461. return false;
  462. } catch (ForbiddenException $e) {
  463. return false;
  464. }
  465. }
  466. /**
  467. * check if smbclient is installed
  468. */
  469. public static function checkDependencies() {
  470. return (
  471. (bool)\OC_Helper::findBinaryPath('smbclient')
  472. || Server::NativeAvailable()
  473. ) ? true : ['smbclient'];
  474. }
  475. /**
  476. * Test a storage for availability
  477. *
  478. * @return bool
  479. */
  480. public function test() {
  481. try {
  482. return parent::test();
  483. } catch (Exception $e) {
  484. return false;
  485. }
  486. }
  487. public function listen($path, callable $callback) {
  488. $this->notify($path)->listen(function (IChange $change) use ($callback) {
  489. if ($change instanceof IRenameChange) {
  490. return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
  491. } else {
  492. return $callback($change->getType(), $change->getPath());
  493. }
  494. });
  495. }
  496. public function notify($path) {
  497. $path = '/' . ltrim($path, '/');
  498. $shareNotifyHandler = $this->share->notify($this->buildPath($path));
  499. return new SMBNotifyHandler($shareNotifyHandler, $this->root);
  500. }
  501. }