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.

505 lines
13 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  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 Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Robin McCorkell <robin@mccorkell.me.uk>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Vincent Petry <pvince81@owncloud.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OCA\Files_External\Lib\Storage;
  32. use Icewind\SMB\Change;
  33. use Icewind\SMB\Exception\ConnectException;
  34. use Icewind\SMB\Exception\Exception;
  35. use Icewind\SMB\Exception\ForbiddenException;
  36. use Icewind\SMB\Exception\NotFoundException;
  37. use Icewind\SMB\INotifyHandler;
  38. use Icewind\SMB\IFileInfo;
  39. use Icewind\SMB\IShare;
  40. use Icewind\SMB\NativeServer;
  41. use Icewind\SMB\Server;
  42. use Icewind\Streams\CallbackWrapper;
  43. use Icewind\Streams\IteratorDirectory;
  44. use OC\Cache\CappedMemoryCache;
  45. use OC\Files\Filesystem;
  46. use OC\Files\Storage\Common;
  47. use OCA\Files_External\Lib\Notify\SMBNotifyHandler;
  48. use OCP\Files\Notify\IChange;
  49. use OCP\Files\Notify\IRenameChange;
  50. use OCP\Files\Storage\INotifyStorage;
  51. use OCP\Files\StorageNotAvailableException;
  52. class SMB extends Common implements INotifyStorage {
  53. /**
  54. * @var \Icewind\SMB\Server
  55. */
  56. protected $server;
  57. /**
  58. * @var \Icewind\SMB\Share
  59. */
  60. protected $share;
  61. /**
  62. * @var string
  63. */
  64. protected $root;
  65. /**
  66. * @var \Icewind\SMB\FileInfo[]
  67. */
  68. protected $statCache;
  69. public function __construct($params) {
  70. if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
  71. if (Server::NativeAvailable()) {
  72. $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
  73. } else {
  74. $this->server = new Server($params['host'], $params['user'], $params['password']);
  75. }
  76. $this->share = $this->server->getShare(trim($params['share'], '/'));
  77. $this->root = isset($params['root']) ? $params['root'] : '/';
  78. if (!$this->root || $this->root[0] != '/') {
  79. $this->root = '/' . $this->root;
  80. }
  81. if (substr($this->root, -1, 1) != '/') {
  82. $this->root .= '/';
  83. }
  84. } else {
  85. throw new \Exception('Invalid configuration');
  86. }
  87. $this->statCache = new CappedMemoryCache();
  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. return !$file->isHidden();
  144. });
  145. } catch (ConnectException $e) {
  146. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  147. }
  148. }
  149. /**
  150. * @param \Icewind\SMB\IFileInfo $info
  151. * @return array
  152. */
  153. protected function formatInfo($info) {
  154. return array(
  155. 'size' => $info->getSize(),
  156. 'mtime' => $info->getMTime()
  157. );
  158. }
  159. /**
  160. * @param string $path
  161. * @return array
  162. */
  163. public function stat($path) {
  164. $result = $this->formatInfo($this->getFileInfo($path));
  165. if ($this->remoteIsShare() && $this->isRootDir($path)) {
  166. $result['mtime'] = $this->shareMTime();
  167. }
  168. return $result;
  169. }
  170. /**
  171. * get the best guess for the modification time of the share
  172. *
  173. * @return int
  174. */
  175. private function shareMTime() {
  176. $highestMTime = 0;
  177. $files = $this->share->dir($this->root);
  178. foreach ($files as $fileInfo) {
  179. if ($fileInfo->getMTime() > $highestMTime) {
  180. $highestMTime = $fileInfo->getMTime();
  181. }
  182. }
  183. return $highestMTime;
  184. }
  185. /**
  186. * Check if the path is our root dir (not the smb one)
  187. *
  188. * @param string $path the path
  189. * @return bool
  190. */
  191. private function isRootDir($path) {
  192. return $path === '' || $path === '/' || $path === '.';
  193. }
  194. /**
  195. * Check if our root points to a smb share
  196. *
  197. * @return bool true if our root points to a share false otherwise
  198. */
  199. private function remoteIsShare() {
  200. return $this->share->getName() && (!$this->root || $this->root === '/');
  201. }
  202. /**
  203. * @param string $path
  204. * @return bool
  205. */
  206. public function unlink($path) {
  207. try {
  208. if ($this->is_dir($path)) {
  209. return $this->rmdir($path);
  210. } else {
  211. $path = $this->buildPath($path);
  212. unset($this->statCache[$path]);
  213. $this->share->del($path);
  214. return true;
  215. }
  216. } catch (NotFoundException $e) {
  217. return false;
  218. } catch (ForbiddenException $e) {
  219. return false;
  220. } catch (ConnectException $e) {
  221. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  222. }
  223. }
  224. /**
  225. * @param string $path1 the old name
  226. * @param string $path2 the new name
  227. * @return bool
  228. */
  229. public function rename($path1, $path2) {
  230. try {
  231. $this->remove($path2);
  232. $path1 = $this->buildPath($path1);
  233. $path2 = $this->buildPath($path2);
  234. return $this->share->rename($path1, $path2);
  235. } catch (NotFoundException $e) {
  236. return false;
  237. } catch (ForbiddenException $e) {
  238. return false;
  239. } catch (ConnectException $e) {
  240. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  241. }
  242. }
  243. /**
  244. * check if a file or folder has been updated since $time
  245. *
  246. * @param string $path
  247. * @param int $time
  248. * @return bool
  249. */
  250. public function hasUpdated($path, $time) {
  251. if (!$path and $this->root == '/') {
  252. // mtime doesn't work for shares, but giving the nature of the backend,
  253. // doing a full update is still just fast enough
  254. return true;
  255. } else {
  256. $actualTime = $this->filemtime($path);
  257. return $actualTime > $time;
  258. }
  259. }
  260. /**
  261. * @param string $path
  262. * @param string $mode
  263. * @return resource|false
  264. */
  265. public function fopen($path, $mode) {
  266. $fullPath = $this->buildPath($path);
  267. try {
  268. switch ($mode) {
  269. case 'r':
  270. case 'rb':
  271. if (!$this->file_exists($path)) {
  272. return false;
  273. }
  274. return $this->share->read($fullPath);
  275. case 'w':
  276. case 'wb':
  277. $source = $this->share->write($fullPath);
  278. return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
  279. unset($this->statCache[$fullPath]);
  280. });
  281. case 'a':
  282. case 'ab':
  283. case 'r+':
  284. case 'w+':
  285. case 'wb+':
  286. case 'a+':
  287. case 'x':
  288. case 'x+':
  289. case 'c':
  290. case 'c+':
  291. //emulate these
  292. if (strrpos($path, '.') !== false) {
  293. $ext = substr($path, strrpos($path, '.'));
  294. } else {
  295. $ext = '';
  296. }
  297. if ($this->file_exists($path)) {
  298. if (!$this->isUpdatable($path)) {
  299. return false;
  300. }
  301. $tmpFile = $this->getCachedFile($path);
  302. } else {
  303. if (!$this->isCreatable(dirname($path))) {
  304. return false;
  305. }
  306. $tmpFile = \OCP\Files::tmpFile($ext);
  307. }
  308. $source = fopen($tmpFile, $mode);
  309. $share = $this->share;
  310. return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
  311. unset($this->statCache[$fullPath]);
  312. $share->put($tmpFile, $fullPath);
  313. unlink($tmpFile);
  314. });
  315. }
  316. return false;
  317. } catch (NotFoundException $e) {
  318. return false;
  319. } catch (ForbiddenException $e) {
  320. return false;
  321. } catch (ConnectException $e) {
  322. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  323. }
  324. }
  325. public function rmdir($path) {
  326. try {
  327. $this->statCache = array();
  328. $content = $this->share->dir($this->buildPath($path));
  329. foreach ($content as $file) {
  330. if ($file->isDirectory()) {
  331. $this->rmdir($path . '/' . $file->getName());
  332. } else {
  333. $this->share->del($file->getPath());
  334. }
  335. }
  336. $this->share->rmdir($this->buildPath($path));
  337. return true;
  338. } catch (NotFoundException $e) {
  339. return false;
  340. } catch (ForbiddenException $e) {
  341. return false;
  342. } catch (ConnectException $e) {
  343. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  344. }
  345. }
  346. public function touch($path, $time = null) {
  347. try {
  348. if (!$this->file_exists($path)) {
  349. $fh = $this->share->write($this->buildPath($path));
  350. fclose($fh);
  351. return true;
  352. }
  353. return false;
  354. } catch (ConnectException $e) {
  355. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  356. }
  357. }
  358. public function opendir($path) {
  359. try {
  360. $files = $this->getFolderContents($path);
  361. } catch (NotFoundException $e) {
  362. return false;
  363. } catch (ForbiddenException $e) {
  364. return false;
  365. }
  366. $names = array_map(function ($info) {
  367. /** @var \Icewind\SMB\IFileInfo $info */
  368. return $info->getName();
  369. }, $files);
  370. return IteratorDirectory::wrap($names);
  371. }
  372. public function filetype($path) {
  373. try {
  374. return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
  375. } catch (NotFoundException $e) {
  376. return false;
  377. } catch (ForbiddenException $e) {
  378. return false;
  379. }
  380. }
  381. public function mkdir($path) {
  382. $path = $this->buildPath($path);
  383. try {
  384. $this->share->mkdir($path);
  385. return true;
  386. } catch (ConnectException $e) {
  387. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  388. } catch (Exception $e) {
  389. return false;
  390. }
  391. }
  392. public function file_exists($path) {
  393. try {
  394. $this->getFileInfo($path);
  395. return true;
  396. } catch (NotFoundException $e) {
  397. return false;
  398. } catch (ForbiddenException $e) {
  399. return false;
  400. } catch (ConnectException $e) {
  401. throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
  402. }
  403. }
  404. public function isReadable($path) {
  405. try {
  406. $info = $this->getFileInfo($path);
  407. return !$info->isHidden();
  408. } catch (NotFoundException $e) {
  409. return false;
  410. } catch (ForbiddenException $e) {
  411. return false;
  412. }
  413. }
  414. public function isUpdatable($path) {
  415. try {
  416. $info = $this->getFileInfo($path);
  417. // following windows behaviour for read-only folders: they can be written into
  418. // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
  419. return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
  420. } catch (NotFoundException $e) {
  421. return false;
  422. } catch (ForbiddenException $e) {
  423. return false;
  424. }
  425. }
  426. public function isDeletable($path) {
  427. try {
  428. $info = $this->getFileInfo($path);
  429. return !$info->isHidden() && !$info->isReadOnly();
  430. } catch (NotFoundException $e) {
  431. return false;
  432. } catch (ForbiddenException $e) {
  433. return false;
  434. }
  435. }
  436. /**
  437. * check if smbclient is installed
  438. */
  439. public static function checkDependencies() {
  440. return (
  441. (bool)\OC_Helper::findBinaryPath('smbclient')
  442. || Server::NativeAvailable()
  443. ) ? true : ['smbclient'];
  444. }
  445. /**
  446. * Test a storage for availability
  447. *
  448. * @return bool
  449. */
  450. public function test() {
  451. try {
  452. return parent::test();
  453. } catch (Exception $e) {
  454. return false;
  455. }
  456. }
  457. public function listen($path, callable $callback) {
  458. $this->notify($path)->listen(function (IChange $change) use ($callback) {
  459. if ($change instanceof IRenameChange) {
  460. return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
  461. } else {
  462. return $callback($change->getType(), $change->getPath());
  463. }
  464. });
  465. }
  466. public function notify($path) {
  467. $shareNotifyHandler = $this->share->notify($this->buildPath($path));
  468. return new SMBNotifyHandler($shareNotifyHandler, $this->root);
  469. }
  470. }