1
0

Storage.php 13 KB

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