MountConfig.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Frank Karlitschek <frank@karlitschek.de>
  11. * @author Jesús Macias <jmacias@solidgear.es>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Robin McCorkell <robin@mccorkell.me.uk>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Vincent Petry <vincent@nextcloud.com>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OCA\Files_External;
  41. use OCA\Files_External\Config\IConfigHandler;
  42. use OCA\Files_External\Config\UserContext;
  43. use OCA\Files_External\Lib\Backend\Backend;
  44. use OCA\Files_External\Service\BackendService;
  45. use OCA\Files_External\Service\GlobalStoragesService;
  46. use OCA\Files_External\Service\UserGlobalStoragesService;
  47. use OCA\Files_External\Service\UserStoragesService;
  48. use OCP\Files\StorageNotAvailableException;
  49. use OCP\IUser;
  50. use phpseclib\Crypt\AES;
  51. /**
  52. * Class to configure mount.json globally and for users
  53. */
  54. class MountConfig {
  55. // TODO: make this class non-static and give it a proper namespace
  56. public const MOUNT_TYPE_GLOBAL = 'global';
  57. public const MOUNT_TYPE_GROUP = 'group';
  58. public const MOUNT_TYPE_USER = 'user';
  59. public const MOUNT_TYPE_PERSONAL = 'personal';
  60. // whether to skip backend test (for unit tests, as this static class is not mockable)
  61. public static $skipTest = false;
  62. /** @var UserGlobalStoragesService */
  63. private $userGlobalStorageService;
  64. /** @var UserStoragesService */
  65. private $userStorageService;
  66. /** @var GlobalStoragesService */
  67. private $globalStorageService;
  68. public function __construct(
  69. UserGlobalStoragesService $userGlobalStorageService,
  70. UserStoragesService $userStorageService,
  71. GlobalStoragesService $globalStorageService
  72. ) {
  73. $this->userGlobalStorageService = $userGlobalStorageService;
  74. $this->userStorageService = $userStorageService;
  75. $this->globalStorageService = $globalStorageService;
  76. }
  77. /**
  78. * @param mixed $input
  79. * @param string|null $userId
  80. * @return mixed
  81. * @throws \OCP\AppFramework\QueryException
  82. * @since 16.0.0
  83. */
  84. public static function substitutePlaceholdersInConfig($input, string $userId = null) {
  85. /** @var BackendService $backendService */
  86. $backendService = \OC::$server->get(BackendService::class);
  87. /** @var IConfigHandler[] $handlers */
  88. $handlers = $backendService->getConfigHandlers();
  89. foreach ($handlers as $handler) {
  90. if ($handler instanceof UserContext && $userId !== null) {
  91. $handler->setUserId($userId);
  92. }
  93. $input = $handler->handle($input);
  94. }
  95. return $input;
  96. }
  97. /**
  98. * Test connecting using the given backend configuration
  99. *
  100. * @param string $class backend class name
  101. * @param array $options backend configuration options
  102. * @param boolean $isPersonal
  103. * @return int see self::STATUS_*
  104. * @throws \Exception
  105. */
  106. public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
  107. if (self::$skipTest) {
  108. return StorageNotAvailableException::STATUS_SUCCESS;
  109. }
  110. foreach ($options as $key => &$option) {
  111. if ($key === 'password') {
  112. // no replacements in passwords
  113. continue;
  114. }
  115. $option = self::substitutePlaceholdersInConfig($option);
  116. }
  117. if (class_exists($class)) {
  118. try {
  119. /** @var \OC\Files\Storage\Common $storage */
  120. $storage = new $class($options);
  121. try {
  122. $result = $storage->test($isPersonal, $testOnly);
  123. $storage->setAvailability($result);
  124. if ($result) {
  125. return StorageNotAvailableException::STATUS_SUCCESS;
  126. }
  127. } catch (\Exception $e) {
  128. $storage->setAvailability(false);
  129. throw $e;
  130. }
  131. } catch (\Exception $exception) {
  132. \OC::$server->getLogger()->logException($exception, ['app' => 'files_external']);
  133. throw $exception;
  134. }
  135. }
  136. return StorageNotAvailableException::STATUS_ERROR;
  137. }
  138. /**
  139. * Get backend dependency message
  140. * TODO: move into AppFramework along with templates
  141. *
  142. * @param Backend[] $backends
  143. */
  144. public static function dependencyMessage(array $backends): string {
  145. $l = \OC::$server->getL10N('files_external');
  146. $message = '';
  147. $dependencyGroups = [];
  148. foreach ($backends as $backend) {
  149. foreach ($backend->checkDependencies() as $dependency) {
  150. $dependencyMessage = $dependency->getMessage();
  151. if ($dependencyMessage !== null) {
  152. $message .= '<p>' . $dependencyMessage . '</p>';
  153. } else {
  154. $dependencyGroups[$dependency->getDependency()][] = $backend;
  155. }
  156. }
  157. }
  158. foreach ($dependencyGroups as $module => $dependants) {
  159. $backends = implode(', ', array_map(function (Backend $backend): string {
  160. return '"' . $backend->getText() . '"';
  161. }, $dependants));
  162. $message .= '<p>' . MountConfig::getSingleDependencyMessage($l, $module, $backends) . '</p>';
  163. }
  164. return $message;
  165. }
  166. /**
  167. * Returns a dependency missing message
  168. */
  169. private static function getSingleDependencyMessage(\OCP\IL10N $l, string $module, string $backend): string {
  170. switch (strtolower($module)) {
  171. case 'curl':
  172. 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]);
  173. case 'ftp':
  174. 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]);
  175. default:
  176. 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]);
  177. }
  178. }
  179. /**
  180. * Encrypt passwords in the given config options
  181. *
  182. * @param array $options mount options
  183. * @return array updated options
  184. */
  185. public static function encryptPasswords($options) {
  186. if (isset($options['password'])) {
  187. $options['password_encrypted'] = self::encryptPassword($options['password']);
  188. // do not unset the password, we want to keep the keys order
  189. // on load... because that's how the UI currently works
  190. $options['password'] = '';
  191. }
  192. return $options;
  193. }
  194. /**
  195. * Decrypt passwords in the given config options
  196. *
  197. * @param array $options mount options
  198. * @return array updated options
  199. */
  200. public static function decryptPasswords($options) {
  201. // note: legacy options might still have the unencrypted password in the "password" field
  202. if (isset($options['password_encrypted'])) {
  203. $options['password'] = self::decryptPassword($options['password_encrypted']);
  204. unset($options['password_encrypted']);
  205. }
  206. return $options;
  207. }
  208. /**
  209. * Encrypt a single password
  210. *
  211. * @param string $password plain text password
  212. * @return string encrypted password
  213. */
  214. private static function encryptPassword($password) {
  215. $cipher = self::getCipher();
  216. $iv = \OC::$server->getSecureRandom()->generate(16);
  217. $cipher->setIV($iv);
  218. return base64_encode($iv . $cipher->encrypt($password));
  219. }
  220. /**
  221. * Decrypts a single password
  222. *
  223. * @param string $encryptedPassword encrypted password
  224. * @return string plain text password
  225. */
  226. private static function decryptPassword($encryptedPassword) {
  227. $cipher = self::getCipher();
  228. $binaryPassword = base64_decode($encryptedPassword);
  229. $iv = substr($binaryPassword, 0, 16);
  230. $cipher->setIV($iv);
  231. $binaryPassword = substr($binaryPassword, 16);
  232. return $cipher->decrypt($binaryPassword);
  233. }
  234. /**
  235. * Returns the encryption cipher
  236. *
  237. * @return AES
  238. */
  239. private static function getCipher() {
  240. $cipher = new AES(AES::MODE_CBC);
  241. $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
  242. return $cipher;
  243. }
  244. /**
  245. * Computes a hash based on the given configuration.
  246. * This is mostly used to find out whether configurations
  247. * are the same.
  248. *
  249. * @param array $config
  250. * @return string
  251. */
  252. public static function makeConfigHash($config) {
  253. $data = json_encode(
  254. [
  255. 'c' => $config['backend'],
  256. 'a' => $config['authMechanism'],
  257. 'm' => $config['mountpoint'],
  258. 'o' => $config['options'],
  259. 'p' => isset($config['priority']) ? $config['priority'] : -1,
  260. 'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
  261. ]
  262. );
  263. return hash('md5', $data);
  264. }
  265. }