1
0

MountConfig.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_External;
  8. use OC\Files\Storage\Common;
  9. use OCA\Files_External\Config\IConfigHandler;
  10. use OCA\Files_External\Config\UserContext;
  11. use OCA\Files_External\Lib\Backend\Backend;
  12. use OCA\Files_External\Service\BackendService;
  13. use OCA\Files_External\Service\GlobalStoragesService;
  14. use OCA\Files_External\Service\UserGlobalStoragesService;
  15. use OCA\Files_External\Service\UserStoragesService;
  16. use OCP\AppFramework\QueryException;
  17. use OCP\Files\StorageNotAvailableException;
  18. use OCP\IL10N;
  19. use OCP\Util;
  20. use phpseclib\Crypt\AES;
  21. use Psr\Log\LoggerInterface;
  22. /**
  23. * Class to configure mount.json globally and for users
  24. */
  25. class MountConfig {
  26. // TODO: make this class non-static and give it a proper namespace
  27. public const MOUNT_TYPE_GLOBAL = 'global';
  28. public const MOUNT_TYPE_GROUP = 'group';
  29. public const MOUNT_TYPE_USER = 'user';
  30. public const MOUNT_TYPE_PERSONAL = 'personal';
  31. // whether to skip backend test (for unit tests, as this static class is not mockable)
  32. public static $skipTest = false;
  33. public function __construct(
  34. private UserGlobalStoragesService $userGlobalStorageService,
  35. private UserStoragesService $userStorageService,
  36. private GlobalStoragesService $globalStorageService,
  37. ) {
  38. }
  39. /**
  40. * @param mixed $input
  41. * @param string|null $userId
  42. * @return mixed
  43. * @throws QueryException
  44. * @since 16.0.0
  45. */
  46. public static function substitutePlaceholdersInConfig($input, ?string $userId = null) {
  47. /** @var BackendService $backendService */
  48. $backendService = \OC::$server->get(BackendService::class);
  49. /** @var IConfigHandler[] $handlers */
  50. $handlers = $backendService->getConfigHandlers();
  51. foreach ($handlers as $handler) {
  52. if ($handler instanceof UserContext && $userId !== null) {
  53. $handler->setUserId($userId);
  54. }
  55. $input = $handler->handle($input);
  56. }
  57. return $input;
  58. }
  59. /**
  60. * Test connecting using the given backend configuration
  61. *
  62. * @param string $class backend class name
  63. * @param array $options backend configuration options
  64. * @param boolean $isPersonal
  65. * @return int see self::STATUS_*
  66. * @throws \Exception
  67. */
  68. public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
  69. if (self::$skipTest) {
  70. return StorageNotAvailableException::STATUS_SUCCESS;
  71. }
  72. foreach ($options as $key => &$option) {
  73. if ($key === 'password') {
  74. // no replacements in passwords
  75. continue;
  76. }
  77. $option = self::substitutePlaceholdersInConfig($option);
  78. }
  79. if (class_exists($class)) {
  80. try {
  81. /** @var Common $storage */
  82. $storage = new $class($options);
  83. try {
  84. $result = $storage->test($isPersonal, $testOnly);
  85. $storage->setAvailability($result);
  86. if ($result) {
  87. return StorageNotAvailableException::STATUS_SUCCESS;
  88. }
  89. } catch (\Exception $e) {
  90. $storage->setAvailability(false);
  91. throw $e;
  92. }
  93. } catch (\Exception $exception) {
  94. \OC::$server->get(LoggerInterface::class)->error($exception->getMessage(), ['exception' => $exception, 'app' => 'files_external']);
  95. throw $exception;
  96. }
  97. }
  98. return StorageNotAvailableException::STATUS_ERROR;
  99. }
  100. /**
  101. * Get backend dependency message
  102. * TODO: move into AppFramework along with templates
  103. *
  104. * @param Backend[] $backends
  105. */
  106. public static function dependencyMessage(array $backends): string {
  107. $l = Util::getL10N('files_external');
  108. $message = '';
  109. $dependencyGroups = [];
  110. foreach ($backends as $backend) {
  111. foreach ($backend->checkDependencies() as $dependency) {
  112. $dependencyMessage = $dependency->getMessage();
  113. if ($dependencyMessage !== null) {
  114. $message .= '<p>' . $dependencyMessage . '</p>';
  115. } else {
  116. $dependencyGroups[$dependency->getDependency()][] = $backend;
  117. }
  118. }
  119. }
  120. foreach ($dependencyGroups as $module => $dependants) {
  121. $backends = implode(', ', array_map(function (Backend $backend): string {
  122. return '"' . $backend->getText() . '"';
  123. }, $dependants));
  124. $message .= '<p>' . MountConfig::getSingleDependencyMessage($l, $module, $backends) . '</p>';
  125. }
  126. return $message;
  127. }
  128. /**
  129. * Returns a dependency missing message
  130. */
  131. private static function getSingleDependencyMessage(IL10N $l, string $module, string $backend): string {
  132. switch (strtolower($module)) {
  133. case 'curl':
  134. return $l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
  135. case 'ftp':
  136. return $l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
  137. default:
  138. return $l->t('"%1$s" is not installed. Mounting of %2$s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
  139. }
  140. }
  141. /**
  142. * Encrypt passwords in the given config options
  143. *
  144. * @param array $options mount options
  145. * @return array updated options
  146. */
  147. public static function encryptPasswords($options) {
  148. if (isset($options['password'])) {
  149. $options['password_encrypted'] = self::encryptPassword($options['password']);
  150. // do not unset the password, we want to keep the keys order
  151. // on load... because that's how the UI currently works
  152. $options['password'] = '';
  153. }
  154. return $options;
  155. }
  156. /**
  157. * Decrypt passwords in the given config options
  158. *
  159. * @param array $options mount options
  160. * @return array updated options
  161. */
  162. public static function decryptPasswords($options) {
  163. // note: legacy options might still have the unencrypted password in the "password" field
  164. if (isset($options['password_encrypted'])) {
  165. $options['password'] = self::decryptPassword($options['password_encrypted']);
  166. unset($options['password_encrypted']);
  167. }
  168. return $options;
  169. }
  170. /**
  171. * Encrypt a single password
  172. *
  173. * @param string $password plain text password
  174. * @return string encrypted password
  175. */
  176. private static function encryptPassword($password) {
  177. $cipher = self::getCipher();
  178. $iv = \OC::$server->getSecureRandom()->generate(16);
  179. $cipher->setIV($iv);
  180. return base64_encode($iv . $cipher->encrypt($password));
  181. }
  182. /**
  183. * Decrypts a single password
  184. *
  185. * @param string $encryptedPassword encrypted password
  186. * @return string plain text password
  187. */
  188. private static function decryptPassword($encryptedPassword) {
  189. $cipher = self::getCipher();
  190. $binaryPassword = base64_decode($encryptedPassword);
  191. $iv = substr($binaryPassword, 0, 16);
  192. $cipher->setIV($iv);
  193. $binaryPassword = substr($binaryPassword, 16);
  194. return $cipher->decrypt($binaryPassword);
  195. }
  196. /**
  197. * Returns the encryption cipher
  198. *
  199. * @return AES
  200. */
  201. private static function getCipher() {
  202. $cipher = new AES(AES::MODE_CBC);
  203. $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
  204. return $cipher;
  205. }
  206. /**
  207. * Computes a hash based on the given configuration.
  208. * This is mostly used to find out whether configurations
  209. * are the same.
  210. *
  211. * @param array $config
  212. * @return string
  213. */
  214. public static function makeConfigHash($config) {
  215. $data = json_encode(
  216. [
  217. 'c' => $config['backend'],
  218. 'a' => $config['authMechanism'],
  219. 'm' => $config['mountpoint'],
  220. 'o' => $config['options'],
  221. 'p' => $config['priority'] ?? -1,
  222. 'mo' => $config['mountOptions'] ?? [],
  223. ]
  224. );
  225. return hash('md5', $data);
  226. }
  227. }