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.

Storage.php 14KB

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. 'password' => (string)$options['password']
  103. ]
  104. );
  105. }
  106. public function getWatcher($path = '', $storage = null) {
  107. if (!$storage) {
  108. $storage = $this;
  109. }
  110. if (!isset($this->watcher)) {
  111. $this->watcher = new Watcher($storage);
  112. $this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
  113. }
  114. return $this->watcher;
  115. }
  116. public function getRemoteUser(): string {
  117. return $this->cloudId->getUser();
  118. }
  119. public function getRemote(): string {
  120. return $this->cloudId->getRemote();
  121. }
  122. public function getMountPoint(): string {
  123. return $this->mountPoint;
  124. }
  125. public function getToken(): string {
  126. return $this->token;
  127. }
  128. public function getPassword(): ?string {
  129. return $this->password;
  130. }
  131. /**
  132. * Get id of the mount point.
  133. * @return string
  134. */
  135. public function getId() {
  136. return 'shared::' . md5($this->token . '@' . $this->getRemote());
  137. }
  138. public function getCache($path = '', $storage = null) {
  139. if (is_null($this->cache)) {
  140. $this->cache = new Cache($this, $this->cloudId);
  141. }
  142. return $this->cache;
  143. }
  144. /**
  145. * @param string $path
  146. * @param \OC\Files\Storage\Storage $storage
  147. * @return \OCA\Files_Sharing\External\Scanner
  148. */
  149. public function getScanner($path = '', $storage = null) {
  150. if (!$storage) {
  151. $storage = $this;
  152. }
  153. if (!isset($this->scanner)) {
  154. $this->scanner = new Scanner($storage);
  155. }
  156. return $this->scanner;
  157. }
  158. /**
  159. * Check if a file or folder has been updated since $time
  160. *
  161. * @param string $path
  162. * @param int $time
  163. * @throws \OCP\Files\StorageNotAvailableException
  164. * @throws \OCP\Files\StorageInvalidException
  165. * @return bool
  166. */
  167. public function hasUpdated($path, $time) {
  168. // since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
  169. // because of that we only do one check for the entire storage per request
  170. if ($this->updateChecked) {
  171. return false;
  172. }
  173. $this->updateChecked = true;
  174. try {
  175. return parent::hasUpdated('', $time);
  176. } catch (StorageInvalidException $e) {
  177. // check if it needs to be removed
  178. $this->checkStorageAvailability();
  179. throw $e;
  180. } catch (StorageNotAvailableException $e) {
  181. // check if it needs to be removed or just temp unavailable
  182. $this->checkStorageAvailability();
  183. throw $e;
  184. }
  185. }
  186. public function test() {
  187. try {
  188. return parent::test();
  189. } catch (StorageInvalidException $e) {
  190. // check if it needs to be removed
  191. $this->checkStorageAvailability();
  192. throw $e;
  193. } catch (StorageNotAvailableException $e) {
  194. // check if it needs to be removed or just temp unavailable
  195. $this->checkStorageAvailability();
  196. throw $e;
  197. }
  198. }
  199. /**
  200. * Check whether this storage is permanently or temporarily
  201. * unavailable
  202. *
  203. * @throws \OCP\Files\StorageNotAvailableException
  204. * @throws \OCP\Files\StorageInvalidException
  205. */
  206. public function checkStorageAvailability() {
  207. // see if we can find out why the share is unavailable
  208. try {
  209. $this->getShareInfo(0);
  210. } catch (NotFoundException $e) {
  211. // a 404 can either mean that the share no longer exists or there is no Nextcloud on the remote
  212. if ($this->testRemote()) {
  213. // valid Nextcloud instance means that the public share no longer exists
  214. // since this is permanent (re-sharing the file will create a new token)
  215. // we remove the invalid storage
  216. $this->manager->removeShare($this->mountPoint);
  217. $this->manager->getMountManager()->removeMount($this->mountPoint);
  218. throw new StorageInvalidException("Remote share not found", 0, $e);
  219. } else {
  220. // Nextcloud instance is gone, likely to be a temporary server configuration error
  221. throw new StorageNotAvailableException("No nextcloud instance found at remote", 0, $e);
  222. }
  223. } catch (ForbiddenException $e) {
  224. // auth error, remove share for now (provide a dialog in the future)
  225. $this->manager->removeShare($this->mountPoint);
  226. $this->manager->getMountManager()->removeMount($this->mountPoint);
  227. throw new StorageInvalidException("Auth error when getting remote share");
  228. } catch (\GuzzleHttp\Exception\ConnectException $e) {
  229. throw new StorageNotAvailableException("Failed to connect to remote instance", 0, $e);
  230. } catch (\GuzzleHttp\Exception\RequestException $e) {
  231. throw new StorageNotAvailableException("Error while sending request to remote instance", 0, $e);
  232. }
  233. }
  234. public function file_exists($path) {
  235. if ($path === '') {
  236. return true;
  237. } else {
  238. return parent::file_exists($path);
  239. }
  240. }
  241. /**
  242. * Check if the configured remote is a valid federated share provider
  243. *
  244. * @return bool
  245. */
  246. protected function testRemote(): bool {
  247. try {
  248. return $this->testRemoteUrl($this->getRemote() . '/ocm-provider/index.php')
  249. || $this->testRemoteUrl($this->getRemote() . '/ocm-provider/')
  250. || $this->testRemoteUrl($this->getRemote() . '/status.php');
  251. } catch (\Exception $e) {
  252. return false;
  253. }
  254. }
  255. private function testRemoteUrl(string $url): bool {
  256. $cache = $this->memcacheFactory->createDistributed('files_sharing_remote_url');
  257. $cached = $cache->get($url);
  258. if ($cached !== null) {
  259. return (bool)$cached;
  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. }