Storage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Maxence Lange <maxence@artificial-owl.com>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Vincent Petry <vincent@nextcloud.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_Sharing\External;
  35. use GuzzleHttp\Exception\ClientException;
  36. use GuzzleHttp\Exception\ConnectException;
  37. use GuzzleHttp\Exception\RequestException;
  38. use OC\Files\Storage\DAV;
  39. use OC\ForbiddenException;
  40. use OCA\Files_Sharing\External\Manager as ExternalShareManager;
  41. use OCA\Files_Sharing\ISharedStorage;
  42. use OCP\AppFramework\Http;
  43. use OCP\Constants;
  44. use OCP\Federation\ICloudId;
  45. use OCP\Files\NotFoundException;
  46. use OCP\Files\Storage\IDisableEncryptionStorage;
  47. use OCP\Files\Storage\IReliableEtagStorage;
  48. use OCP\Files\StorageInvalidException;
  49. use OCP\Files\StorageNotAvailableException;
  50. use OCP\Http\Client\IClientService;
  51. use OCP\Http\Client\LocalServerException;
  52. use OCP\ICacheFactory;
  53. use OCP\OCM\Exceptions\OCMArgumentException;
  54. use OCP\OCM\Exceptions\OCMProviderException;
  55. use OCP\OCM\IOCMDiscoveryService;
  56. use OCP\Server;
  57. use Psr\Log\LoggerInterface;
  58. class Storage extends DAV implements ISharedStorage, IDisableEncryptionStorage, IReliableEtagStorage {
  59. private ICloudId $cloudId;
  60. private string $mountPoint;
  61. private string $token;
  62. private ICacheFactory $memcacheFactory;
  63. private IClientService $httpClient;
  64. private bool $updateChecked = false;
  65. private ExternalShareManager $manager;
  66. /**
  67. * @param array{HttpClientService: IClientService, manager: ExternalShareManager, cloudId: ICloudId, mountpoint: string, token: string, password: ?string}|array $options
  68. */
  69. public function __construct($options) {
  70. $this->memcacheFactory = \OC::$server->getMemCacheFactory();
  71. $this->httpClient = $options['HttpClientService'];
  72. $this->manager = $options['manager'];
  73. $this->cloudId = $options['cloudId'];
  74. $this->logger = Server::get(LoggerInterface::class);
  75. $discoveryService = Server::get(IOCMDiscoveryService::class);
  76. // use default path to webdav if not found on discovery
  77. try {
  78. $ocmProvider = $discoveryService->discover($this->cloudId->getRemote());
  79. $webDavEndpoint = $ocmProvider->extractProtocolEntry('file', 'webdav');
  80. $remote = $ocmProvider->getEndPoint();
  81. } catch (OCMProviderException|OCMArgumentException $e) {
  82. $this->logger->notice('exception while retrieving webdav endpoint', ['exception' => $e]);
  83. $webDavEndpoint = '/public.php/webdav';
  84. $remote = $this->cloudId->getRemote();
  85. }
  86. $host = parse_url($remote, PHP_URL_HOST);
  87. $port = parse_url($remote, PHP_URL_PORT);
  88. $host .= (null === $port) ? '' : ':' . $port; // we add port if available
  89. // in case remote NC is on a sub folder and using deprecated ocm provider
  90. $tmpPath = rtrim(parse_url($this->cloudId->getRemote(), PHP_URL_PATH) ?? '', '/');
  91. if (!str_starts_with($webDavEndpoint, $tmpPath)) {
  92. $webDavEndpoint = $tmpPath . $webDavEndpoint;
  93. }
  94. $this->mountPoint = $options['mountpoint'];
  95. $this->token = $options['token'];
  96. parent::__construct(
  97. [
  98. 'secure' => ((parse_url($remote, PHP_URL_SCHEME) ?? 'https') === 'https'),
  99. 'host' => $host,
  100. 'root' => $webDavEndpoint,
  101. 'user' => $options['token'],
  102. 'authType' => \Sabre\DAV\Client::AUTH_BASIC,
  103. 'password' => (string)$options['password']
  104. ]
  105. );
  106. }
  107. public function getWatcher($path = '', $storage = null) {
  108. if (!$storage) {
  109. $storage = $this;
  110. }
  111. if (!isset($this->watcher)) {
  112. $this->watcher = new Watcher($storage);
  113. $this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
  114. }
  115. return $this->watcher;
  116. }
  117. public function getRemoteUser(): string {
  118. return $this->cloudId->getUser();
  119. }
  120. public function getRemote(): string {
  121. return $this->cloudId->getRemote();
  122. }
  123. public function getMountPoint(): string {
  124. return $this->mountPoint;
  125. }
  126. public function getToken(): string {
  127. return $this->token;
  128. }
  129. public function getPassword(): ?string {
  130. return $this->password;
  131. }
  132. /**
  133. * Get id of the mount point.
  134. * @return string
  135. */
  136. public function getId() {
  137. return 'shared::' . md5($this->token . '@' . $this->getRemote());
  138. }
  139. public function getCache($path = '', $storage = null) {
  140. if (is_null($this->cache)) {
  141. $this->cache = new Cache($this, $this->cloudId);
  142. }
  143. return $this->cache;
  144. }
  145. /**
  146. * @param string $path
  147. * @param \OC\Files\Storage\Storage $storage
  148. * @return \OCA\Files_Sharing\External\Scanner
  149. */
  150. public function getScanner($path = '', $storage = null) {
  151. if (!$storage) {
  152. $storage = $this;
  153. }
  154. if (!isset($this->scanner)) {
  155. $this->scanner = new Scanner($storage);
  156. }
  157. return $this->scanner;
  158. }
  159. /**
  160. * Check if a file or folder has been updated since $time
  161. *
  162. * @param string $path
  163. * @param int $time
  164. * @throws \OCP\Files\StorageNotAvailableException
  165. * @throws \OCP\Files\StorageInvalidException
  166. * @return bool
  167. */
  168. public function hasUpdated($path, $time) {
  169. // since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
  170. // because of that we only do one check for the entire storage per request
  171. if ($this->updateChecked) {
  172. return false;
  173. }
  174. $this->updateChecked = true;
  175. try {
  176. return parent::hasUpdated('', $time);
  177. } catch (StorageInvalidException $e) {
  178. // check if it needs to be removed
  179. $this->checkStorageAvailability();
  180. throw $e;
  181. } catch (StorageNotAvailableException $e) {
  182. // check if it needs to be removed or just temp unavailable
  183. $this->checkStorageAvailability();
  184. throw $e;
  185. }
  186. }
  187. public function test() {
  188. try {
  189. return parent::test();
  190. } catch (StorageInvalidException $e) {
  191. // check if it needs to be removed
  192. $this->checkStorageAvailability();
  193. throw $e;
  194. } catch (StorageNotAvailableException $e) {
  195. // check if it needs to be removed or just temp unavailable
  196. $this->checkStorageAvailability();
  197. throw $e;
  198. }
  199. }
  200. /**
  201. * Check whether this storage is permanently or temporarily
  202. * unavailable
  203. *
  204. * @throws \OCP\Files\StorageNotAvailableException
  205. * @throws \OCP\Files\StorageInvalidException
  206. */
  207. public function checkStorageAvailability() {
  208. // see if we can find out why the share is unavailable
  209. try {
  210. $this->getShareInfo(0);
  211. } catch (NotFoundException $e) {
  212. // a 404 can either mean that the share no longer exists or there is no Nextcloud on the remote
  213. if ($this->testRemote()) {
  214. // valid Nextcloud instance means that the public share no longer exists
  215. // since this is permanent (re-sharing the file will create a new token)
  216. // we remove the invalid storage
  217. $this->manager->removeShare($this->mountPoint);
  218. $this->manager->getMountManager()->removeMount($this->mountPoint);
  219. throw new StorageInvalidException("Remote share not found", 0, $e);
  220. } else {
  221. // Nextcloud instance is gone, likely to be a temporary server configuration error
  222. throw new StorageNotAvailableException("No nextcloud instance found at remote", 0, $e);
  223. }
  224. } catch (ForbiddenException $e) {
  225. // auth error, remove share for now (provide a dialog in the future)
  226. $this->manager->removeShare($this->mountPoint);
  227. $this->manager->getMountManager()->removeMount($this->mountPoint);
  228. throw new StorageInvalidException("Auth error when getting remote share");
  229. } catch (\GuzzleHttp\Exception\ConnectException $e) {
  230. throw new StorageNotAvailableException("Failed to connect to remote instance", 0, $e);
  231. } catch (\GuzzleHttp\Exception\RequestException $e) {
  232. throw new StorageNotAvailableException("Error while sending request to remote instance", 0, $e);
  233. }
  234. }
  235. public function file_exists($path) {
  236. if ($path === '') {
  237. return true;
  238. } else {
  239. return parent::file_exists($path);
  240. }
  241. }
  242. /**
  243. * Check if the configured remote is a valid federated share provider
  244. *
  245. * @return bool
  246. */
  247. protected function testRemote(): bool {
  248. try {
  249. return $this->testRemoteUrl($this->getRemote() . '/ocm-provider/index.php')
  250. || $this->testRemoteUrl($this->getRemote() . '/ocm-provider/')
  251. || $this->testRemoteUrl($this->getRemote() . '/status.php');
  252. } catch (\Exception $e) {
  253. return false;
  254. }
  255. }
  256. private function testRemoteUrl(string $url): bool {
  257. $cache = $this->memcacheFactory->createDistributed('files_sharing_remote_url');
  258. if ($cache->hasKey($url)) {
  259. return (bool)$cache->get($url);
  260. }
  261. $client = $this->httpClient->newClient();
  262. try {
  263. $result = $client->get($url, [
  264. 'timeout' => 10,
  265. 'connect_timeout' => 10,
  266. ])->getBody();
  267. $data = json_decode($result);
  268. $returnValue = (is_object($data) && !empty($data->version));
  269. } catch (ConnectException $e) {
  270. $returnValue = false;
  271. } catch (ClientException $e) {
  272. $returnValue = false;
  273. } catch (RequestException $e) {
  274. $returnValue = false;
  275. }
  276. $cache->set($url, $returnValue, 60 * 60 * 24);
  277. return $returnValue;
  278. }
  279. /**
  280. * Check whether the remote is an ownCloud/Nextcloud. This is needed since some sharing
  281. * features are not standardized.
  282. *
  283. * @throws LocalServerException
  284. */
  285. public function remoteIsOwnCloud(): bool {
  286. if (defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
  287. return false;
  288. }
  289. return true;
  290. }
  291. /**
  292. * @return mixed
  293. * @throws ForbiddenException
  294. * @throws NotFoundException
  295. * @throws \Exception
  296. */
  297. public function getShareInfo(int $depth = -1) {
  298. $remote = $this->getRemote();
  299. $token = $this->getToken();
  300. $password = $this->getPassword();
  301. try {
  302. // If remote is not an ownCloud do not try to get any share info
  303. if (!$this->remoteIsOwnCloud()) {
  304. return ['status' => 'unsupported'];
  305. }
  306. } catch (LocalServerException $e) {
  307. // throw this to be on the safe side: the share will still be visible
  308. // in the UI in case the failure is intermittent, and the user will
  309. // be able to decide whether to remove it if it's really gone
  310. throw new StorageNotAvailableException();
  311. }
  312. $url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
  313. // TODO: DI
  314. $client = \OC::$server->getHTTPClientService()->newClient();
  315. try {
  316. $response = $client->post($url, [
  317. 'body' => ['password' => $password, 'depth' => $depth],
  318. 'timeout' => 10,
  319. 'connect_timeout' => 10,
  320. ]);
  321. } catch (\GuzzleHttp\Exception\RequestException $e) {
  322. if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
  323. throw new ForbiddenException();
  324. }
  325. if ($e->getCode() === Http::STATUS_NOT_FOUND) {
  326. throw new NotFoundException();
  327. }
  328. // throw this to be on the safe side: the share will still be visible
  329. // in the UI in case the failure is intermittent, and the user will
  330. // be able to decide whether to remove it if it's really gone
  331. throw new StorageNotAvailableException();
  332. }
  333. return json_decode($response->getBody(), true);
  334. }
  335. public function getOwner($path) {
  336. return $this->cloudId->getDisplayId();
  337. }
  338. public function isSharable($path): bool {
  339. if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
  340. return false;
  341. }
  342. return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
  343. }
  344. public function getPermissions($path): int {
  345. $response = $this->propfind($path);
  346. // old federated sharing permissions
  347. if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
  348. $permissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
  349. } elseif (isset($response['{http://open-cloud-mesh.org/ns}share-permissions'])) {
  350. // permissions provided by the OCM API
  351. $permissions = $this->ocmPermissions2ncPermissions($response['{http://open-collaboration-services.org/ns}share-permissions'], $path);
  352. } elseif (isset($response['{http://owncloud.org/ns}permissions'])) {
  353. return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  354. } else {
  355. // use default permission if remote server doesn't provide the share permissions
  356. $permissions = $this->getDefaultPermissions($path);
  357. }
  358. return $permissions;
  359. }
  360. public function needsPartFile() {
  361. return false;
  362. }
  363. /**
  364. * Translate OCM Permissions to Nextcloud permissions
  365. *
  366. * @param string $ocmPermissions json encoded OCM permissions
  367. * @param string $path path to file
  368. * @return int
  369. */
  370. protected function ocmPermissions2ncPermissions(string $ocmPermissions, string $path): int {
  371. try {
  372. $ocmPermissions = json_decode($ocmPermissions);
  373. $ncPermissions = 0;
  374. foreach ($ocmPermissions as $permission) {
  375. switch (strtolower($permission)) {
  376. case 'read':
  377. $ncPermissions += Constants::PERMISSION_READ;
  378. break;
  379. case 'write':
  380. $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
  381. break;
  382. case 'share':
  383. $ncPermissions += Constants::PERMISSION_SHARE;
  384. break;
  385. default:
  386. throw new \Exception();
  387. }
  388. }
  389. } catch (\Exception $e) {
  390. $ncPermissions = $this->getDefaultPermissions($path);
  391. }
  392. return $ncPermissions;
  393. }
  394. /**
  395. * Calculate the default permissions in case no permissions are provided
  396. */
  397. protected function getDefaultPermissions(string $path): int {
  398. if ($this->is_dir($path)) {
  399. $permissions = Constants::PERMISSION_ALL;
  400. } else {
  401. $permissions = Constants::PERMISSION_ALL & ~Constants::PERMISSION_CREATE;
  402. }
  403. return $permissions;
  404. }
  405. public function free_space($path) {
  406. return parent::free_space("");
  407. }
  408. }