DAV.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Carlos Cerrillo <ccerrillo@gmail.com>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  21. * @author Vincent Petry <vincent@nextcloud.com>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OC\Files\Storage;
  39. use Exception;
  40. use Icewind\Streams\CallbackWrapper;
  41. use Icewind\Streams\IteratorDirectory;
  42. use OC\Files\Filesystem;
  43. use OC\MemCache\ArrayCache;
  44. use OCP\AppFramework\Http;
  45. use OCP\Constants;
  46. use OCP\Diagnostics\IEventLogger;
  47. use OCP\Files\FileInfo;
  48. use OCP\Files\ForbiddenException;
  49. use OCP\Files\IMimeTypeDetector;
  50. use OCP\Files\StorageInvalidException;
  51. use OCP\Files\StorageNotAvailableException;
  52. use OCP\Http\Client\IClientService;
  53. use OCP\ICertificateManager;
  54. use OCP\IConfig;
  55. use OCP\Util;
  56. use Psr\Http\Message\ResponseInterface;
  57. use Psr\Log\LoggerInterface;
  58. use Sabre\DAV\Client;
  59. use Sabre\DAV\Xml\Property\ResourceType;
  60. use Sabre\HTTP\ClientException;
  61. use Sabre\HTTP\ClientHttpException;
  62. use Sabre\HTTP\RequestInterface;
  63. /**
  64. * Class DAV
  65. *
  66. * @package OC\Files\Storage
  67. */
  68. class DAV extends Common {
  69. /** @var string */
  70. protected $password;
  71. /** @var string */
  72. protected $user;
  73. /** @var string|null */
  74. protected $authType;
  75. /** @var string */
  76. protected $host;
  77. /** @var bool */
  78. protected $secure;
  79. /** @var string */
  80. protected $root;
  81. /** @var string */
  82. protected $certPath;
  83. /** @var bool */
  84. protected $ready;
  85. /** @var Client */
  86. protected $client;
  87. /** @var ArrayCache */
  88. protected $statCache;
  89. /** @var IClientService */
  90. protected $httpClientService;
  91. /** @var ICertificateManager */
  92. protected $certManager;
  93. protected LoggerInterface $logger;
  94. protected IEventLogger $eventLogger;
  95. protected IMimeTypeDetector $mimeTypeDetector;
  96. /** @var int */
  97. private $timeout;
  98. protected const PROPFIND_PROPS = [
  99. '{DAV:}getlastmodified',
  100. '{DAV:}getcontentlength',
  101. '{DAV:}getcontenttype',
  102. '{http://owncloud.org/ns}permissions',
  103. '{http://open-collaboration-services.org/ns}share-permissions',
  104. '{DAV:}resourcetype',
  105. '{DAV:}getetag',
  106. '{DAV:}quota-available-bytes',
  107. ];
  108. /**
  109. * @param array $params
  110. * @throws \Exception
  111. */
  112. public function __construct($params) {
  113. $this->statCache = new ArrayCache();
  114. $this->httpClientService = \OC::$server->getHTTPClientService();
  115. if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
  116. $host = $params['host'];
  117. //remove leading http[s], will be generated in createBaseUri()
  118. if (str_starts_with($host, "https://")) {
  119. $host = substr($host, 8);
  120. } elseif (str_starts_with($host, "http://")) {
  121. $host = substr($host, 7);
  122. }
  123. $this->host = $host;
  124. $this->user = $params['user'];
  125. $this->password = $params['password'];
  126. if (isset($params['authType'])) {
  127. $this->authType = $params['authType'];
  128. }
  129. if (isset($params['secure'])) {
  130. if (is_string($params['secure'])) {
  131. $this->secure = ($params['secure'] === 'true');
  132. } else {
  133. $this->secure = (bool)$params['secure'];
  134. }
  135. } else {
  136. $this->secure = false;
  137. }
  138. if ($this->secure === true) {
  139. // inject mock for testing
  140. $this->certManager = \OC::$server->getCertificateManager();
  141. }
  142. $this->root = $params['root'] ?? '/';
  143. $this->root = '/' . ltrim($this->root, '/');
  144. $this->root = rtrim($this->root, '/') . '/';
  145. } else {
  146. throw new \Exception('Invalid webdav storage configuration');
  147. }
  148. $this->logger = \OC::$server->get(LoggerInterface::class);
  149. $this->eventLogger = \OC::$server->get(IEventLogger::class);
  150. // This timeout value will be used for the download and upload of files
  151. $this->timeout = \OC::$server->get(IConfig::class)->getSystemValueInt('davstorage.request_timeout', 30);
  152. $this->mimeTypeDetector = \OC::$server->getMimeTypeDetector();
  153. }
  154. protected function init() {
  155. if ($this->ready) {
  156. return;
  157. }
  158. $this->ready = true;
  159. $settings = [
  160. 'baseUri' => $this->createBaseUri(),
  161. 'userName' => $this->user,
  162. 'password' => $this->password,
  163. ];
  164. if ($this->authType !== null) {
  165. $settings['authType'] = $this->authType;
  166. }
  167. $proxy = \OC::$server->getConfig()->getSystemValueString('proxy', '');
  168. if ($proxy !== '') {
  169. $settings['proxy'] = $proxy;
  170. }
  171. $this->client = new Client($settings);
  172. $this->client->setThrowExceptions(true);
  173. if ($this->secure === true) {
  174. $certPath = $this->certManager->getAbsoluteBundlePath();
  175. if (file_exists($certPath)) {
  176. $this->certPath = $certPath;
  177. }
  178. if ($this->certPath) {
  179. $this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
  180. }
  181. }
  182. $lastRequestStart = 0;
  183. $this->client->on('beforeRequest', function (RequestInterface $request) use (&$lastRequestStart) {
  184. $this->logger->debug("sending dav " . $request->getMethod() . " request to external storage: " . $request->getAbsoluteUrl(), ['app' => 'dav']);
  185. $lastRequestStart = microtime(true);
  186. $this->eventLogger->start('fs:storage:dav:request', "Sending dav request to external storage");
  187. });
  188. $this->client->on('afterRequest', function (RequestInterface $request) use (&$lastRequestStart) {
  189. $elapsed = microtime(true) - $lastRequestStart;
  190. $this->logger->debug("dav " . $request->getMethod() . " request to external storage: " . $request->getAbsoluteUrl() . " took " . round($elapsed * 1000, 1) . "ms", ['app' => 'dav']);
  191. $this->eventLogger->end('fs:storage:dav:request');
  192. });
  193. }
  194. /**
  195. * Clear the stat cache
  196. */
  197. public function clearStatCache() {
  198. $this->statCache->clear();
  199. }
  200. /** {@inheritdoc} */
  201. public function getId() {
  202. return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
  203. }
  204. /** {@inheritdoc} */
  205. public function createBaseUri() {
  206. $baseUri = 'http';
  207. if ($this->secure) {
  208. $baseUri .= 's';
  209. }
  210. $baseUri .= '://' . $this->host . $this->root;
  211. return $baseUri;
  212. }
  213. /** {@inheritdoc} */
  214. public function mkdir($path) {
  215. $this->init();
  216. $path = $this->cleanPath($path);
  217. $result = $this->simpleResponse('MKCOL', $path, null, 201);
  218. if ($result) {
  219. $this->statCache->set($path, true);
  220. }
  221. return $result;
  222. }
  223. /** {@inheritdoc} */
  224. public function rmdir($path) {
  225. $this->init();
  226. $path = $this->cleanPath($path);
  227. // FIXME: some WebDAV impl return 403 when trying to DELETE
  228. // a non-empty folder
  229. $result = $this->simpleResponse('DELETE', $path . '/', null, 204);
  230. $this->statCache->clear($path . '/');
  231. $this->statCache->remove($path);
  232. return $result;
  233. }
  234. /** {@inheritdoc} */
  235. public function opendir($path) {
  236. $this->init();
  237. $path = $this->cleanPath($path);
  238. try {
  239. $content = $this->getDirectoryContent($path);
  240. $files = [];
  241. foreach ($content as $child) {
  242. $files[] = $child['name'];
  243. }
  244. return IteratorDirectory::wrap($files);
  245. } catch (\Exception $e) {
  246. $this->convertException($e, $path);
  247. }
  248. return false;
  249. }
  250. /**
  251. * Propfind call with cache handling.
  252. *
  253. * First checks if information is cached.
  254. * If not, request it from the server then store to cache.
  255. *
  256. * @param string $path path to propfind
  257. *
  258. * @return array|boolean propfind response or false if the entry was not found
  259. *
  260. * @throws ClientHttpException
  261. */
  262. protected function propfind($path) {
  263. $path = $this->cleanPath($path);
  264. $cachedResponse = $this->statCache->get($path);
  265. // we either don't know it, or we know it exists but need more details
  266. if (is_null($cachedResponse) || $cachedResponse === true) {
  267. $this->init();
  268. try {
  269. $response = $this->client->propFind(
  270. $this->encodePath($path),
  271. self::PROPFIND_PROPS
  272. );
  273. $this->statCache->set($path, $response);
  274. } catch (ClientHttpException $e) {
  275. if ($e->getHttpStatus() === 404 || $e->getHttpStatus() === 405) {
  276. $this->statCache->clear($path . '/');
  277. $this->statCache->set($path, false);
  278. return false;
  279. }
  280. $this->convertException($e, $path);
  281. } catch (\Exception $e) {
  282. $this->convertException($e, $path);
  283. }
  284. } else {
  285. $response = $cachedResponse;
  286. }
  287. return $response;
  288. }
  289. /** {@inheritdoc} */
  290. public function filetype($path) {
  291. try {
  292. $response = $this->propfind($path);
  293. if ($response === false) {
  294. return false;
  295. }
  296. $responseType = [];
  297. if (isset($response["{DAV:}resourcetype"])) {
  298. /** @var ResourceType[] $response */
  299. $responseType = $response["{DAV:}resourcetype"]->getValue();
  300. }
  301. return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  302. } catch (\Exception $e) {
  303. $this->convertException($e, $path);
  304. }
  305. return false;
  306. }
  307. /** {@inheritdoc} */
  308. public function file_exists($path) {
  309. try {
  310. $path = $this->cleanPath($path);
  311. $cachedState = $this->statCache->get($path);
  312. if ($cachedState === false) {
  313. // we know the file doesn't exist
  314. return false;
  315. } elseif (!is_null($cachedState)) {
  316. return true;
  317. }
  318. // need to get from server
  319. return ($this->propfind($path) !== false);
  320. } catch (\Exception $e) {
  321. $this->convertException($e, $path);
  322. }
  323. return false;
  324. }
  325. /** {@inheritdoc} */
  326. public function unlink($path) {
  327. $this->init();
  328. $path = $this->cleanPath($path);
  329. $result = $this->simpleResponse('DELETE', $path, null, 204);
  330. $this->statCache->clear($path . '/');
  331. $this->statCache->remove($path);
  332. return $result;
  333. }
  334. /** {@inheritdoc} */
  335. public function fopen($path, $mode) {
  336. $this->init();
  337. $path = $this->cleanPath($path);
  338. switch ($mode) {
  339. case 'r':
  340. case 'rb':
  341. try {
  342. $response = $this->httpClientService
  343. ->newClient()
  344. ->get($this->createBaseUri() . $this->encodePath($path), [
  345. 'auth' => [$this->user, $this->password],
  346. 'stream' => true,
  347. // set download timeout for users with slow connections or large files
  348. 'timeout' => $this->timeout
  349. ]);
  350. } catch (\GuzzleHttp\Exception\ClientException $e) {
  351. if ($e->getResponse() instanceof ResponseInterface
  352. && $e->getResponse()->getStatusCode() === 404) {
  353. return false;
  354. } else {
  355. throw $e;
  356. }
  357. }
  358. if ($response->getStatusCode() !== Http::STATUS_OK) {
  359. if ($response->getStatusCode() === Http::STATUS_LOCKED) {
  360. throw new \OCP\Lock\LockedException($path);
  361. } else {
  362. \OC::$server->get(LoggerInterface::class)->error('Guzzle get returned status code ' . $response->getStatusCode(), ['app' => 'webdav client']);
  363. }
  364. }
  365. return $response->getBody();
  366. case 'w':
  367. case 'wb':
  368. case 'a':
  369. case 'ab':
  370. case 'r+':
  371. case 'w+':
  372. case 'wb+':
  373. case 'a+':
  374. case 'x':
  375. case 'x+':
  376. case 'c':
  377. case 'c+':
  378. //emulate these
  379. $tempManager = \OC::$server->getTempManager();
  380. if (strrpos($path, '.') !== false) {
  381. $ext = substr($path, strrpos($path, '.'));
  382. } else {
  383. $ext = '';
  384. }
  385. if ($this->file_exists($path)) {
  386. if (!$this->isUpdatable($path)) {
  387. return false;
  388. }
  389. if ($mode === 'w' or $mode === 'w+') {
  390. $tmpFile = $tempManager->getTemporaryFile($ext);
  391. } else {
  392. $tmpFile = $this->getCachedFile($path);
  393. }
  394. } else {
  395. if (!$this->isCreatable(dirname($path))) {
  396. return false;
  397. }
  398. $tmpFile = $tempManager->getTemporaryFile($ext);
  399. }
  400. $handle = fopen($tmpFile, $mode);
  401. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  402. $this->writeBack($tmpFile, $path);
  403. });
  404. }
  405. }
  406. /**
  407. * @param string $tmpFile
  408. */
  409. public function writeBack($tmpFile, $path) {
  410. $this->uploadFile($tmpFile, $path);
  411. unlink($tmpFile);
  412. }
  413. /** {@inheritdoc} */
  414. public function free_space($path) {
  415. $this->init();
  416. $path = $this->cleanPath($path);
  417. try {
  418. $response = $this->propfind($path);
  419. if ($response === false) {
  420. return FileInfo::SPACE_UNKNOWN;
  421. }
  422. if (isset($response['{DAV:}quota-available-bytes'])) {
  423. return Util::numericToNumber($response['{DAV:}quota-available-bytes']);
  424. } else {
  425. return FileInfo::SPACE_UNKNOWN;
  426. }
  427. } catch (\Exception $e) {
  428. return FileInfo::SPACE_UNKNOWN;
  429. }
  430. }
  431. /** {@inheritdoc} */
  432. public function touch($path, $mtime = null) {
  433. $this->init();
  434. if (is_null($mtime)) {
  435. $mtime = time();
  436. }
  437. $path = $this->cleanPath($path);
  438. // if file exists, update the mtime, else create a new empty file
  439. if ($this->file_exists($path)) {
  440. try {
  441. $this->statCache->remove($path);
  442. $this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
  443. // non-owncloud clients might not have accepted the property, need to recheck it
  444. $response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
  445. if (isset($response['{DAV:}getlastmodified'])) {
  446. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  447. if ($remoteMtime !== $mtime) {
  448. // server has not accepted the mtime
  449. return false;
  450. }
  451. }
  452. } catch (ClientHttpException $e) {
  453. if ($e->getHttpStatus() === 501) {
  454. return false;
  455. }
  456. $this->convertException($e, $path);
  457. return false;
  458. } catch (\Exception $e) {
  459. $this->convertException($e, $path);
  460. return false;
  461. }
  462. } else {
  463. $this->file_put_contents($path, '');
  464. }
  465. return true;
  466. }
  467. /**
  468. * @param string $path
  469. * @param mixed $data
  470. * @return int|float|false
  471. */
  472. public function file_put_contents($path, $data) {
  473. $path = $this->cleanPath($path);
  474. $result = parent::file_put_contents($path, $data);
  475. $this->statCache->remove($path);
  476. return $result;
  477. }
  478. /**
  479. * @param string $path
  480. * @param string $target
  481. */
  482. protected function uploadFile($path, $target) {
  483. $this->init();
  484. // invalidate
  485. $target = $this->cleanPath($target);
  486. $this->statCache->remove($target);
  487. $source = fopen($path, 'r');
  488. $this->httpClientService
  489. ->newClient()
  490. ->put($this->createBaseUri() . $this->encodePath($target), [
  491. 'body' => $source,
  492. 'auth' => [$this->user, $this->password],
  493. // set upload timeout for users with slow connections or large files
  494. 'timeout' => $this->timeout
  495. ]);
  496. $this->removeCachedFile($target);
  497. }
  498. /** {@inheritdoc} */
  499. public function rename($source, $target) {
  500. $this->init();
  501. $source = $this->cleanPath($source);
  502. $target = $this->cleanPath($target);
  503. try {
  504. // overwrite directory ?
  505. if ($this->is_dir($target)) {
  506. // needs trailing slash in destination
  507. $target = rtrim($target, '/') . '/';
  508. }
  509. $this->client->request(
  510. 'MOVE',
  511. $this->encodePath($source),
  512. null,
  513. [
  514. 'Destination' => $this->createBaseUri() . $this->encodePath($target),
  515. ]
  516. );
  517. $this->statCache->clear($source . '/');
  518. $this->statCache->clear($target . '/');
  519. $this->statCache->set($source, false);
  520. $this->statCache->set($target, true);
  521. $this->removeCachedFile($source);
  522. $this->removeCachedFile($target);
  523. return true;
  524. } catch (\Exception $e) {
  525. $this->convertException($e);
  526. }
  527. return false;
  528. }
  529. /** {@inheritdoc} */
  530. public function copy($source, $target) {
  531. $this->init();
  532. $source = $this->cleanPath($source);
  533. $target = $this->cleanPath($target);
  534. try {
  535. // overwrite directory ?
  536. if ($this->is_dir($target)) {
  537. // needs trailing slash in destination
  538. $target = rtrim($target, '/') . '/';
  539. }
  540. $this->client->request(
  541. 'COPY',
  542. $this->encodePath($source),
  543. null,
  544. [
  545. 'Destination' => $this->createBaseUri() . $this->encodePath($target),
  546. ]
  547. );
  548. $this->statCache->clear($target . '/');
  549. $this->statCache->set($target, true);
  550. $this->removeCachedFile($target);
  551. return true;
  552. } catch (\Exception $e) {
  553. $this->convertException($e);
  554. }
  555. return false;
  556. }
  557. public function getMetaData($path) {
  558. if (Filesystem::isFileBlacklisted($path)) {
  559. throw new ForbiddenException('Invalid path: ' . $path, false);
  560. }
  561. $response = $this->propfind($path);
  562. if (!$response) {
  563. return null;
  564. } else {
  565. return $this->getMetaFromPropfind($path, $response);
  566. }
  567. }
  568. private function getMetaFromPropfind(string $path, array $response): array {
  569. if (isset($response['{DAV:}getetag'])) {
  570. $etag = trim($response['{DAV:}getetag'], '"');
  571. if (strlen($etag) > 40) {
  572. $etag = md5($etag);
  573. }
  574. } else {
  575. $etag = parent::getETag($path);
  576. }
  577. $responseType = [];
  578. if (isset($response["{DAV:}resourcetype"])) {
  579. /** @var ResourceType[] $response */
  580. $responseType = $response["{DAV:}resourcetype"]->getValue();
  581. }
  582. $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  583. if ($type === 'dir') {
  584. $mimeType = 'httpd/unix-directory';
  585. } elseif (isset($response['{DAV:}getcontenttype'])) {
  586. $mimeType = $response['{DAV:}getcontenttype'];
  587. } else {
  588. $mimeType = $this->mimeTypeDetector->detectPath($path);
  589. }
  590. if (isset($response['{http://owncloud.org/ns}permissions'])) {
  591. $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  592. } elseif ($type === 'dir') {
  593. $permissions = Constants::PERMISSION_ALL;
  594. } else {
  595. $permissions = Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  596. }
  597. $mtime = isset($response['{DAV:}getlastmodified']) ? strtotime($response['{DAV:}getlastmodified']) : null;
  598. if ($type === 'dir') {
  599. $size = -1;
  600. } else {
  601. $size = Util::numericToNumber($response['{DAV:}getcontentlength'] ?? 0);
  602. }
  603. return [
  604. 'name' => basename($path),
  605. 'mtime' => $mtime,
  606. 'storage_mtime' => $mtime,
  607. 'size' => $size,
  608. 'permissions' => $permissions,
  609. 'etag' => $etag,
  610. 'mimetype' => $mimeType,
  611. ];
  612. }
  613. /** {@inheritdoc} */
  614. public function stat($path) {
  615. $meta = $this->getMetaData($path);
  616. if (!$meta) {
  617. return false;
  618. } else {
  619. return $meta;
  620. }
  621. }
  622. /** {@inheritdoc} */
  623. public function getMimeType($path) {
  624. $meta = $this->getMetaData($path);
  625. if ($meta) {
  626. return $meta['mimetype'];
  627. } else {
  628. return false;
  629. }
  630. }
  631. /**
  632. * @param string $path
  633. * @return string
  634. */
  635. public function cleanPath($path) {
  636. if ($path === '') {
  637. return $path;
  638. }
  639. $path = Filesystem::normalizePath($path);
  640. // remove leading slash
  641. return substr($path, 1);
  642. }
  643. /**
  644. * URL encodes the given path but keeps the slashes
  645. *
  646. * @param string $path to encode
  647. * @return string encoded path
  648. */
  649. protected function encodePath($path) {
  650. // slashes need to stay
  651. return str_replace('%2F', '/', rawurlencode($path));
  652. }
  653. /**
  654. * @param string $method
  655. * @param string $path
  656. * @param string|resource|null $body
  657. * @param int $expected
  658. * @return bool
  659. * @throws StorageInvalidException
  660. * @throws StorageNotAvailableException
  661. */
  662. protected function simpleResponse($method, $path, $body, $expected) {
  663. $path = $this->cleanPath($path);
  664. try {
  665. $response = $this->client->request($method, $this->encodePath($path), $body);
  666. return $response['statusCode'] == $expected;
  667. } catch (ClientHttpException $e) {
  668. if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
  669. $this->statCache->clear($path . '/');
  670. $this->statCache->set($path, false);
  671. return false;
  672. }
  673. $this->convertException($e, $path);
  674. } catch (\Exception $e) {
  675. $this->convertException($e, $path);
  676. }
  677. return false;
  678. }
  679. /**
  680. * check if curl is installed
  681. */
  682. public static function checkDependencies() {
  683. return true;
  684. }
  685. /** {@inheritdoc} */
  686. public function isUpdatable($path) {
  687. return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
  688. }
  689. /** {@inheritdoc} */
  690. public function isCreatable($path) {
  691. return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
  692. }
  693. /** {@inheritdoc} */
  694. public function isSharable($path) {
  695. return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
  696. }
  697. /** {@inheritdoc} */
  698. public function isDeletable($path) {
  699. return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
  700. }
  701. /** {@inheritdoc} */
  702. public function getPermissions($path) {
  703. $stat = $this->getMetaData($path);
  704. if ($stat) {
  705. return $stat['permissions'];
  706. } else {
  707. return 0;
  708. }
  709. }
  710. /** {@inheritdoc} */
  711. public function getETag($path) {
  712. $meta = $this->getMetaData($path);
  713. if ($meta) {
  714. return $meta['etag'];
  715. } else {
  716. return null;
  717. }
  718. }
  719. /**
  720. * @param string $permissionsString
  721. * @return int
  722. */
  723. protected function parsePermissions($permissionsString) {
  724. $permissions = Constants::PERMISSION_READ;
  725. if (str_contains($permissionsString, 'R')) {
  726. $permissions |= Constants::PERMISSION_SHARE;
  727. }
  728. if (str_contains($permissionsString, 'D')) {
  729. $permissions |= Constants::PERMISSION_DELETE;
  730. }
  731. if (str_contains($permissionsString, 'W')) {
  732. $permissions |= Constants::PERMISSION_UPDATE;
  733. }
  734. if (str_contains($permissionsString, 'CK')) {
  735. $permissions |= Constants::PERMISSION_CREATE;
  736. $permissions |= Constants::PERMISSION_UPDATE;
  737. }
  738. return $permissions;
  739. }
  740. /**
  741. * check if a file or folder has been updated since $time
  742. *
  743. * @param string $path
  744. * @param int $time
  745. * @throws \OCP\Files\StorageNotAvailableException
  746. * @return bool
  747. */
  748. public function hasUpdated($path, $time) {
  749. $this->init();
  750. $path = $this->cleanPath($path);
  751. try {
  752. // force refresh for $path
  753. $this->statCache->remove($path);
  754. $response = $this->propfind($path);
  755. if ($response === false) {
  756. if ($path === '') {
  757. // if root is gone it means the storage is not available
  758. throw new StorageNotAvailableException('root is gone');
  759. }
  760. return false;
  761. }
  762. if (isset($response['{DAV:}getetag'])) {
  763. $cachedData = $this->getCache()->get($path);
  764. $etag = trim($response['{DAV:}getetag'], '"');
  765. if (($cachedData === false) || (!empty($etag) && ($cachedData['etag'] !== $etag))) {
  766. return true;
  767. } elseif (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
  768. $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
  769. return $sharePermissions !== $cachedData['permissions'];
  770. } elseif (isset($response['{http://owncloud.org/ns}permissions'])) {
  771. $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  772. return $permissions !== $cachedData['permissions'];
  773. } else {
  774. return false;
  775. }
  776. } elseif (isset($response['{DAV:}getlastmodified'])) {
  777. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  778. return $remoteMtime > $time;
  779. } else {
  780. // neither `getetag` nor `getlastmodified` is set
  781. return false;
  782. }
  783. } catch (ClientHttpException $e) {
  784. if ($e->getHttpStatus() === 405) {
  785. if ($path === '') {
  786. // if root is gone it means the storage is not available
  787. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  788. }
  789. return false;
  790. }
  791. $this->convertException($e, $path);
  792. return false;
  793. } catch (\Exception $e) {
  794. $this->convertException($e, $path);
  795. return false;
  796. }
  797. }
  798. /**
  799. * Interpret the given exception and decide whether it is due to an
  800. * unavailable storage, invalid storage or other.
  801. * This will either throw StorageInvalidException, StorageNotAvailableException
  802. * or do nothing.
  803. *
  804. * @param Exception $e sabre exception
  805. * @param string $path optional path from the operation
  806. *
  807. * @throws StorageInvalidException if the storage is invalid, for example
  808. * when the authentication expired or is invalid
  809. * @throws StorageNotAvailableException if the storage is not available,
  810. * which might be temporary
  811. * @throws ForbiddenException if the action is not allowed
  812. */
  813. protected function convertException(Exception $e, $path = '') {
  814. \OC::$server->get(LoggerInterface::class)->debug($e->getMessage(), ['app' => 'files_external', 'exception' => $e]);
  815. if ($e instanceof ClientHttpException) {
  816. if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
  817. throw new \OCP\Lock\LockedException($path);
  818. }
  819. if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
  820. // either password was changed or was invalid all along
  821. throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
  822. } elseif ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
  823. // ignore exception for MethodNotAllowed, false will be returned
  824. return;
  825. } elseif ($e->getHttpStatus() === Http::STATUS_FORBIDDEN) {
  826. // The operation is forbidden. Fail somewhat gracefully
  827. throw new ForbiddenException(get_class($e) . ':' . $e->getMessage(), false);
  828. }
  829. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  830. } elseif ($e instanceof ClientException) {
  831. // connection timeout or refused, server could be temporarily down
  832. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  833. } elseif ($e instanceof \InvalidArgumentException) {
  834. // parse error because the server returned HTML instead of XML,
  835. // possibly temporarily down
  836. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  837. } elseif (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
  838. // rethrow
  839. throw $e;
  840. }
  841. // TODO: only log for now, but in the future need to wrap/rethrow exception
  842. }
  843. public function getDirectoryContent($directory): \Traversable {
  844. $this->init();
  845. $directory = $this->cleanPath($directory);
  846. try {
  847. $responses = $this->client->propFind(
  848. $this->encodePath($directory),
  849. self::PROPFIND_PROPS,
  850. 1
  851. );
  852. array_shift($responses); //the first entry is the current directory
  853. if (!$this->statCache->hasKey($directory)) {
  854. $this->statCache->set($directory, true);
  855. }
  856. foreach ($responses as $file => $response) {
  857. $file = rawurldecode($file);
  858. $file = substr($file, strlen($this->root));
  859. $file = $this->cleanPath($file);
  860. $this->statCache->set($file, $response);
  861. yield $this->getMetaFromPropfind($file, $response);
  862. }
  863. } catch (\Exception $e) {
  864. $this->convertException($e, $directory);
  865. }
  866. }
  867. }