DAV.php 24 KB

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