Storage.php 13 KB

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