MountConfig.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. * @return string
  144. */
  145. public static function dependencyMessage($backends) {
  146. $l = \OC::$server->getL10N('files_external');
  147. $message = '';
  148. $dependencyGroups = [];
  149. foreach ($backends as $backend) {
  150. foreach ($backend->checkDependencies() as $dependency) {
  151. if ($message = $dependency->getMessage()) {
  152. $message .= '<p>' . $message . '</p>';
  153. } else {
  154. $dependencyGroups[$dependency->getDependency()][] = $backend;
  155. }
  156. }
  157. }
  158. foreach ($dependencyGroups as $module => $dependants) {
  159. $backends = implode(', ', array_map(function ($backend) {
  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. * @param \OCP\IL10N $l
  170. * @param string $module
  171. * @param string $backend
  172. * @return string
  173. */
  174. private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
  175. switch (strtolower($module)) {
  176. case 'curl':
  177. 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]);
  178. case 'ftp':
  179. 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]);
  180. default:
  181. 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]);
  182. }
  183. }
  184. /**
  185. * Encrypt passwords in the given config options
  186. *
  187. * @param array $options mount options
  188. * @return array updated options
  189. */
  190. public static function encryptPasswords($options) {
  191. if (isset($options['password'])) {
  192. $options['password_encrypted'] = self::encryptPassword($options['password']);
  193. // do not unset the password, we want to keep the keys order
  194. // on load... because that's how the UI currently works
  195. $options['password'] = '';
  196. }
  197. return $options;
  198. }
  199. /**
  200. * Decrypt passwords in the given config options
  201. *
  202. * @param array $options mount options
  203. * @return array updated options
  204. */
  205. public static function decryptPasswords($options) {
  206. // note: legacy options might still have the unencrypted password in the "password" field
  207. if (isset($options['password_encrypted'])) {
  208. $options['password'] = self::decryptPassword($options['password_encrypted']);
  209. unset($options['password_encrypted']);
  210. }
  211. return $options;
  212. }
  213. /**
  214. * Encrypt a single password
  215. *
  216. * @param string $password plain text password
  217. * @return string encrypted password
  218. */
  219. private static function encryptPassword($password) {
  220. $cipher = self::getCipher();
  221. $iv = \OC::$server->getSecureRandom()->generate(16);
  222. $cipher->setIV($iv);
  223. return base64_encode($iv . $cipher->encrypt($password));
  224. }
  225. /**
  226. * Decrypts a single password
  227. *
  228. * @param string $encryptedPassword encrypted password
  229. * @return string plain text password
  230. */
  231. private static function decryptPassword($encryptedPassword) {
  232. $cipher = self::getCipher();
  233. $binaryPassword = base64_decode($encryptedPassword);
  234. $iv = substr($binaryPassword, 0, 16);
  235. $cipher->setIV($iv);
  236. $binaryPassword = substr($binaryPassword, 16);
  237. return $cipher->decrypt($binaryPassword);
  238. }
  239. /**
  240. * Returns the encryption cipher
  241. *
  242. * @return AES
  243. */
  244. private static function getCipher() {
  245. $cipher = new AES(AES::MODE_CBC);
  246. $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
  247. return $cipher;
  248. }
  249. /**
  250. * Computes a hash based on the given configuration.
  251. * This is mostly used to find out whether configurations
  252. * are the same.
  253. *
  254. * @param array $config
  255. * @return string
  256. */
  257. public static function makeConfigHash($config) {
  258. $data = json_encode(
  259. [
  260. 'c' => $config['backend'],
  261. 'a' => $config['authMechanism'],
  262. 'm' => $config['mountpoint'],
  263. 'o' => $config['options'],
  264. 'p' => isset($config['priority']) ? $config['priority'] : -1,
  265. 'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
  266. ]
  267. );
  268. return hash('md5', $data);
  269. }
  270. }