SMB.php 12 KB

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