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.

DAV.php 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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 ($response === false) {
  446. return false;
  447. }
  448. if (isset($response['{DAV:}getlastmodified'])) {
  449. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  450. if ($remoteMtime !== $mtime) {
  451. // server has not accepted the mtime
  452. return false;
  453. }
  454. }
  455. } catch (ClientHttpException $e) {
  456. if ($e->getHttpStatus() === 501) {
  457. return false;
  458. }
  459. $this->convertException($e, $path);
  460. return false;
  461. } catch (\Exception $e) {
  462. $this->convertException($e, $path);
  463. return false;
  464. }
  465. } else {
  466. $this->file_put_contents($path, '');
  467. }
  468. return true;
  469. }
  470. /**
  471. * @param string $path
  472. * @param mixed $data
  473. * @return int|float|false
  474. */
  475. public function file_put_contents($path, $data) {
  476. $path = $this->cleanPath($path);
  477. $result = parent::file_put_contents($path, $data);
  478. $this->statCache->remove($path);
  479. return $result;
  480. }
  481. /**
  482. * @param string $path
  483. * @param string $target
  484. */
  485. protected function uploadFile($path, $target) {
  486. $this->init();
  487. // invalidate
  488. $target = $this->cleanPath($target);
  489. $this->statCache->remove($target);
  490. $source = fopen($path, 'r');
  491. $this->httpClientService
  492. ->newClient()
  493. ->put($this->createBaseUri() . $this->encodePath($target), [
  494. 'body' => $source,
  495. 'auth' => [$this->user, $this->password],
  496. // set upload timeout for users with slow connections or large files
  497. 'timeout' => $this->timeout
  498. ]);
  499. $this->removeCachedFile($target);
  500. }
  501. /** {@inheritdoc} */
  502. public function rename($source, $target) {
  503. $this->init();
  504. $source = $this->cleanPath($source);
  505. $target = $this->cleanPath($target);
  506. try {
  507. // overwrite directory ?
  508. if ($this->is_dir($target)) {
  509. // needs trailing slash in destination
  510. $target = rtrim($target, '/') . '/';
  511. }
  512. $this->client->request(
  513. 'MOVE',
  514. $this->encodePath($source),
  515. null,
  516. [
  517. 'Destination' => $this->createBaseUri() . $this->encodePath($target),
  518. ]
  519. );
  520. $this->statCache->clear($source . '/');
  521. $this->statCache->clear($target . '/');
  522. $this->statCache->set($source, false);
  523. $this->statCache->set($target, true);
  524. $this->removeCachedFile($source);
  525. $this->removeCachedFile($target);
  526. return true;
  527. } catch (\Exception $e) {
  528. $this->convertException($e);
  529. }
  530. return false;
  531. }
  532. /** {@inheritdoc} */
  533. public function copy($source, $target) {
  534. $this->init();
  535. $source = $this->cleanPath($source);
  536. $target = $this->cleanPath($target);
  537. try {
  538. // overwrite directory ?
  539. if ($this->is_dir($target)) {
  540. // needs trailing slash in destination
  541. $target = rtrim($target, '/') . '/';
  542. }
  543. $this->client->request(
  544. 'COPY',
  545. $this->encodePath($source),
  546. null,
  547. [
  548. 'Destination' => $this->createBaseUri() . $this->encodePath($target),
  549. ]
  550. );
  551. $this->statCache->clear($target . '/');
  552. $this->statCache->set($target, true);
  553. $this->removeCachedFile($target);
  554. return true;
  555. } catch (\Exception $e) {
  556. $this->convertException($e);
  557. }
  558. return false;
  559. }
  560. public function getMetaData($path) {
  561. if (Filesystem::isFileBlacklisted($path)) {
  562. throw new ForbiddenException('Invalid path: ' . $path, false);
  563. }
  564. $response = $this->propfind($path);
  565. if (!$response) {
  566. return null;
  567. } else {
  568. return $this->getMetaFromPropfind($path, $response);
  569. }
  570. }
  571. private function getMetaFromPropfind(string $path, array $response): array {
  572. if (isset($response['{DAV:}getetag'])) {
  573. $etag = trim($response['{DAV:}getetag'], '"');
  574. if (strlen($etag) > 40) {
  575. $etag = md5($etag);
  576. }
  577. } else {
  578. $etag = parent::getETag($path);
  579. }
  580. $responseType = [];
  581. if (isset($response["{DAV:}resourcetype"])) {
  582. /** @var ResourceType[] $response */
  583. $responseType = $response["{DAV:}resourcetype"]->getValue();
  584. }
  585. $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
  586. if ($type === 'dir') {
  587. $mimeType = 'httpd/unix-directory';
  588. } elseif (isset($response['{DAV:}getcontenttype'])) {
  589. $mimeType = $response['{DAV:}getcontenttype'];
  590. } else {
  591. $mimeType = $this->mimeTypeDetector->detectPath($path);
  592. }
  593. if (isset($response['{http://owncloud.org/ns}permissions'])) {
  594. $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  595. } elseif ($type === 'dir') {
  596. $permissions = Constants::PERMISSION_ALL;
  597. } else {
  598. $permissions = Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  599. }
  600. $mtime = isset($response['{DAV:}getlastmodified']) ? strtotime($response['{DAV:}getlastmodified']) : null;
  601. if ($type === 'dir') {
  602. $size = -1;
  603. } else {
  604. $size = Util::numericToNumber($response['{DAV:}getcontentlength'] ?? 0);
  605. }
  606. return [
  607. 'name' => basename($path),
  608. 'mtime' => $mtime,
  609. 'storage_mtime' => $mtime,
  610. 'size' => $size,
  611. 'permissions' => $permissions,
  612. 'etag' => $etag,
  613. 'mimetype' => $mimeType,
  614. ];
  615. }
  616. /** {@inheritdoc} */
  617. public function stat($path) {
  618. $meta = $this->getMetaData($path);
  619. if (!$meta) {
  620. return false;
  621. } else {
  622. return $meta;
  623. }
  624. }
  625. /** {@inheritdoc} */
  626. public function getMimeType($path) {
  627. $meta = $this->getMetaData($path);
  628. if ($meta) {
  629. return $meta['mimetype'];
  630. } else {
  631. return false;
  632. }
  633. }
  634. /**
  635. * @param string $path
  636. * @return string
  637. */
  638. public function cleanPath($path) {
  639. if ($path === '') {
  640. return $path;
  641. }
  642. $path = Filesystem::normalizePath($path);
  643. // remove leading slash
  644. return substr($path, 1);
  645. }
  646. /**
  647. * URL encodes the given path but keeps the slashes
  648. *
  649. * @param string $path to encode
  650. * @return string encoded path
  651. */
  652. protected function encodePath($path) {
  653. // slashes need to stay
  654. return str_replace('%2F', '/', rawurlencode($path));
  655. }
  656. /**
  657. * @param string $method
  658. * @param string $path
  659. * @param string|resource|null $body
  660. * @param int $expected
  661. * @return bool
  662. * @throws StorageInvalidException
  663. * @throws StorageNotAvailableException
  664. */
  665. protected function simpleResponse($method, $path, $body, $expected) {
  666. $path = $this->cleanPath($path);
  667. try {
  668. $response = $this->client->request($method, $this->encodePath($path), $body);
  669. return $response['statusCode'] == $expected;
  670. } catch (ClientHttpException $e) {
  671. if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
  672. $this->statCache->clear($path . '/');
  673. $this->statCache->set($path, false);
  674. return false;
  675. }
  676. $this->convertException($e, $path);
  677. } catch (\Exception $e) {
  678. $this->convertException($e, $path);
  679. }
  680. return false;
  681. }
  682. /**
  683. * check if curl is installed
  684. */
  685. public static function checkDependencies() {
  686. return true;
  687. }
  688. /** {@inheritdoc} */
  689. public function isUpdatable($path) {
  690. return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
  691. }
  692. /** {@inheritdoc} */
  693. public function isCreatable($path) {
  694. return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
  695. }
  696. /** {@inheritdoc} */
  697. public function isSharable($path) {
  698. return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
  699. }
  700. /** {@inheritdoc} */
  701. public function isDeletable($path) {
  702. return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
  703. }
  704. /** {@inheritdoc} */
  705. public function getPermissions($path) {
  706. $stat = $this->getMetaData($path);
  707. if ($stat) {
  708. return $stat['permissions'];
  709. } else {
  710. return 0;
  711. }
  712. }
  713. /** {@inheritdoc} */
  714. public function getETag($path) {
  715. $meta = $this->getMetaData($path);
  716. if ($meta) {
  717. return $meta['etag'];
  718. } else {
  719. return null;
  720. }
  721. }
  722. /**
  723. * @param string $permissionsString
  724. * @return int
  725. */
  726. protected function parsePermissions($permissionsString) {
  727. $permissions = Constants::PERMISSION_READ;
  728. if (str_contains($permissionsString, 'R')) {
  729. $permissions |= Constants::PERMISSION_SHARE;
  730. }
  731. if (str_contains($permissionsString, 'D')) {
  732. $permissions |= Constants::PERMISSION_DELETE;
  733. }
  734. if (str_contains($permissionsString, 'W')) {
  735. $permissions |= Constants::PERMISSION_UPDATE;
  736. }
  737. if (str_contains($permissionsString, 'CK')) {
  738. $permissions |= Constants::PERMISSION_CREATE;
  739. $permissions |= Constants::PERMISSION_UPDATE;
  740. }
  741. return $permissions;
  742. }
  743. /**
  744. * check if a file or folder has been updated since $time
  745. *
  746. * @param string $path
  747. * @param int $time
  748. * @throws \OCP\Files\StorageNotAvailableException
  749. * @return bool
  750. */
  751. public function hasUpdated($path, $time) {
  752. $this->init();
  753. $path = $this->cleanPath($path);
  754. try {
  755. // force refresh for $path
  756. $this->statCache->remove($path);
  757. $response = $this->propfind($path);
  758. if ($response === false) {
  759. if ($path === '') {
  760. // if root is gone it means the storage is not available
  761. throw new StorageNotAvailableException('root is gone');
  762. }
  763. return false;
  764. }
  765. if (isset($response['{DAV:}getetag'])) {
  766. $cachedData = $this->getCache()->get($path);
  767. $etag = trim($response['{DAV:}getetag'], '"');
  768. if (($cachedData === false) || (!empty($etag) && ($cachedData['etag'] !== $etag))) {
  769. return true;
  770. } elseif (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
  771. $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
  772. return $sharePermissions !== $cachedData['permissions'];
  773. } elseif (isset($response['{http://owncloud.org/ns}permissions'])) {
  774. $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
  775. return $permissions !== $cachedData['permissions'];
  776. } else {
  777. return false;
  778. }
  779. } elseif (isset($response['{DAV:}getlastmodified'])) {
  780. $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
  781. return $remoteMtime > $time;
  782. } else {
  783. // neither `getetag` nor `getlastmodified` is set
  784. return false;
  785. }
  786. } catch (ClientHttpException $e) {
  787. if ($e->getHttpStatus() === 405) {
  788. if ($path === '') {
  789. // if root is gone it means the storage is not available
  790. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  791. }
  792. return false;
  793. }
  794. $this->convertException($e, $path);
  795. return false;
  796. } catch (\Exception $e) {
  797. $this->convertException($e, $path);
  798. return false;
  799. }
  800. }
  801. /**
  802. * Interpret the given exception and decide whether it is due to an
  803. * unavailable storage, invalid storage or other.
  804. * This will either throw StorageInvalidException, StorageNotAvailableException
  805. * or do nothing.
  806. *
  807. * @param Exception $e sabre exception
  808. * @param string $path optional path from the operation
  809. *
  810. * @throws StorageInvalidException if the storage is invalid, for example
  811. * when the authentication expired or is invalid
  812. * @throws StorageNotAvailableException if the storage is not available,
  813. * which might be temporary
  814. * @throws ForbiddenException if the action is not allowed
  815. */
  816. protected function convertException(Exception $e, $path = '') {
  817. \OC::$server->get(LoggerInterface::class)->debug($e->getMessage(), ['app' => 'files_external', 'exception' => $e]);
  818. if ($e instanceof ClientHttpException) {
  819. if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
  820. throw new \OCP\Lock\LockedException($path);
  821. }
  822. if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
  823. // either password was changed or was invalid all along
  824. throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
  825. } elseif ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
  826. // ignore exception for MethodNotAllowed, false will be returned
  827. return;
  828. } elseif ($e->getHttpStatus() === Http::STATUS_FORBIDDEN) {
  829. // The operation is forbidden. Fail somewhat gracefully
  830. throw new ForbiddenException(get_class($e) . ':' . $e->getMessage(), false);
  831. }
  832. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  833. } elseif ($e instanceof ClientException) {
  834. // connection timeout or refused, server could be temporarily down
  835. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  836. } elseif ($e instanceof \InvalidArgumentException) {
  837. // parse error because the server returned HTML instead of XML,
  838. // possibly temporarily down
  839. throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
  840. } elseif (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
  841. // rethrow
  842. throw $e;
  843. }
  844. // TODO: only log for now, but in the future need to wrap/rethrow exception
  845. }
  846. public function getDirectoryContent($directory): \Traversable {
  847. $this->init();
  848. $directory = $this->cleanPath($directory);
  849. try {
  850. $responses = $this->client->propFind(
  851. $this->encodePath($directory),
  852. self::PROPFIND_PROPS,
  853. 1
  854. );
  855. if ($responses === false) {
  856. return;
  857. }
  858. array_shift($responses); //the first entry is the current directory
  859. if (!$this->statCache->hasKey($directory)) {
  860. $this->statCache->set($directory, true);
  861. }
  862. foreach ($responses as $file => $response) {
  863. $file = urldecode($file);
  864. $file = substr($file, strlen($this->root));
  865. $file = $this->cleanPath($file);
  866. $this->statCache->set($file, $response);
  867. yield $this->getMetaFromPropfind($file, $response);
  868. }
  869. } catch (\Exception $e) {
  870. $this->convertException($e, $directory);
  871. }
  872. }
  873. }