StoragesService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Jesús Macias <jmacias@solidgear.es>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Robin McCorkell <robin@mccorkell.me.uk>
  10. * @author Stefan Weil <sw@weilnetz.de>
  11. * @author Vincent Petry <pvince81@owncloud.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Files_External\Service;
  29. use \OC\Files\Filesystem;
  30. use OCA\Files_External\Lib\StorageConfig;
  31. use OCA\Files_External\NotFoundException;
  32. use \OCA\Files_External\Lib\Backend\Backend;
  33. use \OCA\Files_External\Lib\Auth\AuthMechanism;
  34. use OCP\Files\Config\IUserMountCache;
  35. use \OCP\Files\StorageNotAvailableException;
  36. /**
  37. * Service class to manage external storages
  38. */
  39. abstract class StoragesService {
  40. /** @var BackendService */
  41. protected $backendService;
  42. /**
  43. * @var DBConfigService
  44. */
  45. protected $dbConfig;
  46. /**
  47. * @var IUserMountCache
  48. */
  49. protected $userMountCache;
  50. /**
  51. * @param BackendService $backendService
  52. * @param DBConfigService $dbConfigService
  53. * @param IUserMountCache $userMountCache
  54. */
  55. public function __construct(BackendService $backendService, DBConfigService $dbConfigService, IUserMountCache $userMountCache) {
  56. $this->backendService = $backendService;
  57. $this->dbConfig = $dbConfigService;
  58. $this->userMountCache = $userMountCache;
  59. }
  60. protected function readDBConfig() {
  61. return $this->dbConfig->getAdminMounts();
  62. }
  63. protected function getStorageConfigFromDBMount(array $mount) {
  64. $applicableUsers = array_filter($mount['applicable'], function ($applicable) {
  65. return $applicable['type'] === DBConfigService::APPLICABLE_TYPE_USER;
  66. });
  67. $applicableUsers = array_map(function ($applicable) {
  68. return $applicable['value'];
  69. }, $applicableUsers);
  70. $applicableGroups = array_filter($mount['applicable'], function ($applicable) {
  71. return $applicable['type'] === DBConfigService::APPLICABLE_TYPE_GROUP;
  72. });
  73. $applicableGroups = array_map(function ($applicable) {
  74. return $applicable['value'];
  75. }, $applicableGroups);
  76. try {
  77. $config = $this->createStorage(
  78. $mount['mount_point'],
  79. $mount['storage_backend'],
  80. $mount['auth_backend'],
  81. $mount['config'],
  82. $mount['options'],
  83. array_values($applicableUsers),
  84. array_values($applicableGroups),
  85. $mount['priority']
  86. );
  87. $config->setType($mount['type']);
  88. $config->setId((int)$mount['mount_id']);
  89. return $config;
  90. } catch (\UnexpectedValueException $e) {
  91. // don't die if a storage backend doesn't exist
  92. \OCP\Util::writeLog(
  93. 'files_external',
  94. 'Could not load storage: "' . $e->getMessage() . '"',
  95. \OCP\Util::ERROR
  96. );
  97. return null;
  98. } catch (\InvalidArgumentException $e) {
  99. \OCP\Util::writeLog(
  100. 'files_external',
  101. 'Could not load storage: "' . $e->getMessage() . '"',
  102. \OCP\Util::ERROR
  103. );
  104. return null;
  105. }
  106. }
  107. /**
  108. * Read the external storages config
  109. *
  110. * @return array map of storage id to storage config
  111. */
  112. protected function readConfig() {
  113. $mounts = $this->readDBConfig();
  114. $configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
  115. $configs = array_filter($configs, function ($config) {
  116. return $config instanceof StorageConfig;
  117. });
  118. $keys = array_map(function (StorageConfig $config) {
  119. return $config->getId();
  120. }, $configs);
  121. return array_combine($keys, $configs);
  122. }
  123. /**
  124. * Get a storage with status
  125. *
  126. * @param int $id storage id
  127. *
  128. * @return StorageConfig
  129. * @throws NotFoundException if the storage with the given id was not found
  130. */
  131. public function getStorage($id) {
  132. $mount = $this->dbConfig->getMountById($id);
  133. if (!is_array($mount)) {
  134. throw new NotFoundException('Storage with id "' . $id . '" not found');
  135. }
  136. $config = $this->getStorageConfigFromDBMount($mount);
  137. if ($this->isApplicable($config)) {
  138. return $config;
  139. } else {
  140. throw new NotFoundException('Storage with id "' . $id . '" not found');
  141. }
  142. }
  143. /**
  144. * Check whether this storage service should provide access to a storage
  145. *
  146. * @param StorageConfig $config
  147. * @return bool
  148. */
  149. abstract protected function isApplicable(StorageConfig $config);
  150. /**
  151. * Gets all storages, valid or not
  152. *
  153. * @return StorageConfig[] array of storage configs
  154. */
  155. public function getAllStorages() {
  156. return $this->readConfig();
  157. }
  158. /**
  159. * Gets all valid storages
  160. *
  161. * @return StorageConfig[]
  162. */
  163. public function getStorages() {
  164. return array_filter($this->getAllStorages(), [$this, 'validateStorage']);
  165. }
  166. /**
  167. * Validate storage
  168. * FIXME: De-duplicate with StoragesController::validate()
  169. *
  170. * @param StorageConfig $storage
  171. * @return bool
  172. */
  173. protected function validateStorage(StorageConfig $storage) {
  174. /** @var Backend */
  175. $backend = $storage->getBackend();
  176. /** @var AuthMechanism */
  177. $authMechanism = $storage->getAuthMechanism();
  178. if (!$backend->isVisibleFor($this->getVisibilityType())) {
  179. // not permitted to use backend
  180. return false;
  181. }
  182. if (!$authMechanism->isVisibleFor($this->getVisibilityType())) {
  183. // not permitted to use auth mechanism
  184. return false;
  185. }
  186. return true;
  187. }
  188. /**
  189. * Get the visibility type for this controller, used in validation
  190. *
  191. * @return string BackendService::VISIBILITY_* constants
  192. */
  193. abstract public function getVisibilityType();
  194. /**
  195. * @return integer
  196. */
  197. protected function getType() {
  198. return DBConfigService::MOUNT_TYPE_ADMIN;
  199. }
  200. /**
  201. * Add new storage to the configuration
  202. *
  203. * @param StorageConfig $newStorage storage attributes
  204. *
  205. * @return StorageConfig storage config, with added id
  206. */
  207. public function addStorage(StorageConfig $newStorage) {
  208. $allStorages = $this->readConfig();
  209. $configId = $this->dbConfig->addMount(
  210. $newStorage->getMountPoint(),
  211. $newStorage->getBackend()->getIdentifier(),
  212. $newStorage->getAuthMechanism()->getIdentifier(),
  213. $newStorage->getPriority(),
  214. $this->getType()
  215. );
  216. $newStorage->setId($configId);
  217. foreach ($newStorage->getApplicableUsers() as $user) {
  218. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_USER, $user);
  219. }
  220. foreach ($newStorage->getApplicableGroups() as $group) {
  221. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  222. }
  223. foreach ($newStorage->getBackendOptions() as $key => $value) {
  224. $this->dbConfig->setConfig($configId, $key, $value);
  225. }
  226. foreach ($newStorage->getMountOptions() as $key => $value) {
  227. $this->dbConfig->setOption($configId, $key, $value);
  228. }
  229. if (count($newStorage->getApplicableUsers()) === 0 && count($newStorage->getApplicableGroups()) === 0) {
  230. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  231. }
  232. // add new storage
  233. $allStorages[$configId] = $newStorage;
  234. $this->triggerHooks($newStorage, Filesystem::signal_create_mount);
  235. $newStorage->setStatus(StorageNotAvailableException::STATUS_SUCCESS);
  236. return $newStorage;
  237. }
  238. /**
  239. * Create a storage from its parameters
  240. *
  241. * @param string $mountPoint storage mount point
  242. * @param string $backendIdentifier backend identifier
  243. * @param string $authMechanismIdentifier authentication mechanism identifier
  244. * @param array $backendOptions backend-specific options
  245. * @param array|null $mountOptions mount-specific options
  246. * @param array|null $applicableUsers users for which to mount the storage
  247. * @param array|null $applicableGroups groups for which to mount the storage
  248. * @param int|null $priority priority
  249. *
  250. * @return StorageConfig
  251. */
  252. public function createStorage(
  253. $mountPoint,
  254. $backendIdentifier,
  255. $authMechanismIdentifier,
  256. $backendOptions,
  257. $mountOptions = null,
  258. $applicableUsers = null,
  259. $applicableGroups = null,
  260. $priority = null
  261. ) {
  262. $backend = $this->backendService->getBackend($backendIdentifier);
  263. if (!$backend) {
  264. throw new \InvalidArgumentException('Unable to get backend for ' . $backendIdentifier);
  265. }
  266. $authMechanism = $this->backendService->getAuthMechanism($authMechanismIdentifier);
  267. if (!$authMechanism) {
  268. throw new \InvalidArgumentException('Unable to get authentication mechanism for ' . $authMechanismIdentifier);
  269. }
  270. $newStorage = new StorageConfig();
  271. $newStorage->setMountPoint($mountPoint);
  272. $newStorage->setBackend($backend);
  273. $newStorage->setAuthMechanism($authMechanism);
  274. $newStorage->setBackendOptions($backendOptions);
  275. if (isset($mountOptions)) {
  276. $newStorage->setMountOptions($mountOptions);
  277. }
  278. if (isset($applicableUsers)) {
  279. $newStorage->setApplicableUsers($applicableUsers);
  280. }
  281. if (isset($applicableGroups)) {
  282. $newStorage->setApplicableGroups($applicableGroups);
  283. }
  284. if (isset($priority)) {
  285. $newStorage->setPriority($priority);
  286. }
  287. return $newStorage;
  288. }
  289. /**
  290. * Triggers the given hook signal for all the applicables given
  291. *
  292. * @param string $signal signal
  293. * @param string $mountPoint hook mount pount param
  294. * @param string $mountType hook mount type param
  295. * @param array $applicableArray array of applicable users/groups for which to trigger the hook
  296. */
  297. protected function triggerApplicableHooks($signal, $mountPoint, $mountType, $applicableArray) {
  298. foreach ($applicableArray as $applicable) {
  299. \OCP\Util::emitHook(
  300. Filesystem::CLASSNAME,
  301. $signal,
  302. [
  303. Filesystem::signal_param_path => $mountPoint,
  304. Filesystem::signal_param_mount_type => $mountType,
  305. Filesystem::signal_param_users => $applicable,
  306. ]
  307. );
  308. }
  309. }
  310. /**
  311. * Triggers $signal for all applicable users of the given
  312. * storage
  313. *
  314. * @param StorageConfig $storage storage data
  315. * @param string $signal signal to trigger
  316. */
  317. abstract protected function triggerHooks(StorageConfig $storage, $signal);
  318. /**
  319. * Triggers signal_create_mount or signal_delete_mount to
  320. * accommodate for additions/deletions in applicableUsers
  321. * and applicableGroups fields.
  322. *
  323. * @param StorageConfig $oldStorage old storage data
  324. * @param StorageConfig $newStorage new storage data
  325. */
  326. abstract protected function triggerChangeHooks(StorageConfig $oldStorage, StorageConfig $newStorage);
  327. /**
  328. * Update storage to the configuration
  329. *
  330. * @param StorageConfig $updatedStorage storage attributes
  331. *
  332. * @return StorageConfig storage config
  333. * @throws NotFoundException if the given storage does not exist in the config
  334. */
  335. public function updateStorage(StorageConfig $updatedStorage) {
  336. $id = $updatedStorage->getId();
  337. $existingMount = $this->dbConfig->getMountById($id);
  338. if (!is_array($existingMount)) {
  339. throw new NotFoundException('Storage with id "' . $id . '" not found while updating storage');
  340. }
  341. $oldStorage = $this->getStorageConfigFromDBMount($existingMount);
  342. $removedUsers = array_diff($oldStorage->getApplicableUsers(), $updatedStorage->getApplicableUsers());
  343. $removedGroups = array_diff($oldStorage->getApplicableGroups(), $updatedStorage->getApplicableGroups());
  344. $addedUsers = array_diff($updatedStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());
  345. $addedGroups = array_diff($updatedStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());
  346. $oldUserCount = count($oldStorage->getApplicableUsers());
  347. $oldGroupCount = count($oldStorage->getApplicableGroups());
  348. $newUserCount = count($updatedStorage->getApplicableUsers());
  349. $newGroupCount = count($updatedStorage->getApplicableGroups());
  350. $wasGlobal = ($oldUserCount + $oldGroupCount) === 0;
  351. $isGlobal = ($newUserCount + $newGroupCount) === 0;
  352. foreach ($removedUsers as $user) {
  353. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);
  354. }
  355. foreach ($removedGroups as $group) {
  356. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  357. }
  358. foreach ($addedUsers as $user) {
  359. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);
  360. }
  361. foreach ($addedGroups as $group) {
  362. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  363. }
  364. if ($wasGlobal && !$isGlobal) {
  365. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  366. } else if (!$wasGlobal && $isGlobal) {
  367. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  368. }
  369. $changedConfig = array_diff_assoc($updatedStorage->getBackendOptions(), $oldStorage->getBackendOptions());
  370. $changedOptions = array_diff_assoc($updatedStorage->getMountOptions(), $oldStorage->getMountOptions());
  371. foreach ($changedConfig as $key => $value) {
  372. $this->dbConfig->setConfig($id, $key, $value);
  373. }
  374. foreach ($changedOptions as $key => $value) {
  375. $this->dbConfig->setOption($id, $key, $value);
  376. }
  377. if ($updatedStorage->getMountPoint() !== $oldStorage->getMountPoint()) {
  378. $this->dbConfig->setMountPoint($id, $updatedStorage->getMountPoint());
  379. }
  380. if ($updatedStorage->getAuthMechanism()->getIdentifier() !== $oldStorage->getAuthMechanism()->getIdentifier()) {
  381. $this->dbConfig->setAuthBackend($id, $updatedStorage->getAuthMechanism()->getIdentifier());
  382. }
  383. $this->triggerChangeHooks($oldStorage, $updatedStorage);
  384. if (($wasGlobal && !$isGlobal) || count($removedGroups) > 0) { // to expensive to properly handle these on the fly
  385. $this->userMountCache->remoteStorageMounts($this->getStorageId($updatedStorage));
  386. } else {
  387. $storageId = $this->getStorageId($updatedStorage);
  388. foreach ($removedUsers as $userId) {
  389. $this->userMountCache->removeUserStorageMount($storageId, $userId);
  390. }
  391. }
  392. return $this->getStorage($id);
  393. }
  394. /**
  395. * Delete the storage with the given id.
  396. *
  397. * @param int $id storage id
  398. *
  399. * @throws NotFoundException if no storage was found with the given id
  400. */
  401. public function removeStorage($id) {
  402. $existingMount = $this->dbConfig->getMountById($id);
  403. if (!is_array($existingMount)) {
  404. throw new NotFoundException('Storage with id "' . $id . '" not found');
  405. }
  406. $this->dbConfig->removeMount($id);
  407. $deletedStorage = $this->getStorageConfigFromDBMount($existingMount);
  408. $this->triggerHooks($deletedStorage, Filesystem::signal_delete_mount);
  409. // delete oc_storages entries and oc_filecache
  410. try {
  411. $rustyStorageId = $this->getRustyStorageIdFromConfig($deletedStorage);
  412. \OC\Files\Cache\Storage::remove($rustyStorageId);
  413. } catch (\Exception $e) {
  414. // can happen either for invalid configs where the storage could not
  415. // be instantiated or whenever $user vars where used, in which case
  416. // the storage id could not be computed
  417. \OCP\Util::writeLog(
  418. 'files_external',
  419. 'Exception: "' . $e->getMessage() . '"',
  420. \OCP\Util::ERROR
  421. );
  422. }
  423. }
  424. /**
  425. * Returns the rusty storage id from oc_storages from the given storage config.
  426. *
  427. * @param StorageConfig $storageConfig
  428. * @return string rusty storage id
  429. */
  430. private function getRustyStorageIdFromConfig(StorageConfig $storageConfig) {
  431. // if any of the storage options contains $user, it is not possible
  432. // to compute the possible storage id as we don't know which users
  433. // mounted it already (and we certainly don't want to iterate over ALL users)
  434. foreach ($storageConfig->getBackendOptions() as $value) {
  435. if (strpos($value, '$user') !== false) {
  436. throw new \Exception('Cannot compute storage id for deletion due to $user vars in the configuration');
  437. }
  438. }
  439. // note: similar to ConfigAdapter->prepateStorageConfig()
  440. $storageConfig->getAuthMechanism()->manipulateStorageConfig($storageConfig);
  441. $storageConfig->getBackend()->manipulateStorageConfig($storageConfig);
  442. $class = $storageConfig->getBackend()->getStorageClass();
  443. $storageImpl = new $class($storageConfig->getBackendOptions());
  444. return $storageImpl->getId();
  445. }
  446. /**
  447. * Construct the storage implementation
  448. *
  449. * @param StorageConfig $storageConfig
  450. * @return int
  451. */
  452. private function getStorageId(StorageConfig $storageConfig) {
  453. try {
  454. $class = $storageConfig->getBackend()->getStorageClass();
  455. /** @var \OC\Files\Storage\Storage $storage */
  456. $storage = new $class($storageConfig->getBackendOptions());
  457. // auth mechanism should fire first
  458. $storage = $storageConfig->getBackend()->wrapStorage($storage);
  459. $storage = $storageConfig->getAuthMechanism()->wrapStorage($storage);
  460. return $storage->getStorageCache()->getNumericId();
  461. } catch (\Exception $e) {
  462. return -1;
  463. }
  464. }
  465. }