MySQL.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Hemanth Kumar Veeranki <hems.india1997@gmail.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Michael Göhler <somebody.here@gmx.de>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <vincent@nextcloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Setup;
  31. use Doctrine\DBAL\Platforms\MySQL80Platform;
  32. use OC\DB\ConnectionAdapter;
  33. use OC\DB\MySqlTools;
  34. use OCP\IDBConnection;
  35. use OCP\Security\ISecureRandom;
  36. class MySQL extends AbstractDatabase {
  37. public $dbprettyname = 'MySQL/MariaDB';
  38. public function setupDatabase($username) {
  39. //check if the database user has admin right
  40. $connection = $this->connect(['dbname' => null]);
  41. // detect mb4
  42. $tools = new MySqlTools();
  43. if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
  44. $this->config->setValue('mysql.utf8mb4', true);
  45. $connection = $this->connect(['dbname' => null]);
  46. }
  47. if ($this->tryCreateDbUser) {
  48. $this->createSpecificUser($username, new ConnectionAdapter($connection));
  49. }
  50. $this->config->setValues([
  51. 'dbuser' => $this->dbUser,
  52. 'dbpassword' => $this->dbPassword,
  53. ]);
  54. //create the database
  55. $this->createDatabase($connection);
  56. //fill the database if needed
  57. $query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
  58. $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
  59. $connection->close();
  60. $connection = $this->connect();
  61. try {
  62. $connection->connect();
  63. } catch (\Exception $e) {
  64. $this->logger->error($e->getMessage(), [
  65. 'exception' => $e,
  66. ]);
  67. throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
  68. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  69. }
  70. }
  71. /**
  72. * @param \OC\DB\Connection $connection
  73. */
  74. private function createDatabase($connection) {
  75. try {
  76. $name = $this->dbName;
  77. $user = $this->dbUser;
  78. //we can't use OC_DB functions here because we need to connect as the administrative user.
  79. $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
  80. $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE {$characterSet}_bin;";
  81. $connection->executeUpdate($query);
  82. } catch (\Exception $ex) {
  83. $this->logger->error('Database creation failed.', [
  84. 'exception' => $ex,
  85. 'app' => 'mysql.setup',
  86. ]);
  87. return;
  88. }
  89. try {
  90. //this query will fail if there aren't the right permissions, ignore the error
  91. $query = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `$name` . * TO '$user'";
  92. $connection->executeUpdate($query);
  93. } catch (\Exception $ex) {
  94. $this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges.', [
  95. 'exception' => $ex,
  96. 'app' => 'mysql.setup',
  97. ]);
  98. }
  99. }
  100. /**
  101. * @param IDBConnection $connection
  102. * @throws \OC\DatabaseSetupException
  103. */
  104. private function createDBUser($connection) {
  105. try {
  106. $name = $this->dbUser;
  107. $password = $this->dbPassword;
  108. // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
  109. // the anonymous user would take precedence when there is one.
  110. if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
  111. $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
  112. $connection->executeUpdate($query);
  113. $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
  114. $connection->executeUpdate($query);
  115. } else {
  116. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  117. $connection->executeUpdate($query);
  118. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  119. $connection->executeUpdate($query);
  120. }
  121. } catch (\Exception $ex) {
  122. $this->logger->error('Database user creation failed.', [
  123. 'exception' => $ex,
  124. 'app' => 'mysql.setup',
  125. ]);
  126. throw $ex;
  127. }
  128. }
  129. /**
  130. * @param $username
  131. * @param IDBConnection $connection
  132. */
  133. private function createSpecificUser($username, $connection): void {
  134. $rootUser = $this->dbUser;
  135. $rootPassword = $this->dbPassword;
  136. //create a random password so we don't need to store the admin password in the config file
  137. $saveSymbols = str_replace(['\"', '\\', '\'', '`'], '', ISecureRandom::CHAR_SYMBOLS);
  138. $password = $this->random->generate(22, ISecureRandom::CHAR_ALPHANUMERIC . $saveSymbols)
  139. . $this->random->generate(2, ISecureRandom::CHAR_UPPER)
  140. . $this->random->generate(2, ISecureRandom::CHAR_LOWER)
  141. . $this->random->generate(2, ISecureRandom::CHAR_DIGITS)
  142. . $this->random->generate(2, $saveSymbols);
  143. $this->dbPassword = str_shuffle($password);
  144. try {
  145. //user already specified in config
  146. $oldUser = $this->config->getValue('dbuser', false);
  147. //we don't have a dbuser specified in config
  148. if ($this->dbUser !== $oldUser) {
  149. //add prefix to the admin username to prevent collisions
  150. $adminUser = substr('oc_' . $username, 0, 16);
  151. $i = 1;
  152. while (true) {
  153. //this should be enough to check for admin rights in mysql
  154. $query = 'SELECT user FROM mysql.user WHERE user=?';
  155. $result = $connection->executeQuery($query, [$adminUser]);
  156. //current dbuser has admin rights
  157. $data = $result->fetchAll();
  158. $result->closeCursor();
  159. //new dbuser does not exist
  160. if (count($data) === 0) {
  161. //use the admin login data for the new database user
  162. $this->dbUser = $adminUser;
  163. $this->createDBUser($connection);
  164. break;
  165. } else {
  166. //repeat with different username
  167. $length = strlen((string)$i);
  168. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  169. $i++;
  170. }
  171. }
  172. } else {
  173. // Reuse existing password if a database config is already present
  174. $this->dbPassword = $rootPassword;
  175. }
  176. } catch (\Exception $ex) {
  177. $this->logger->info('Can not create a new MySQL user, will continue with the provided user.', [
  178. 'exception' => $ex,
  179. 'app' => 'mysql.setup',
  180. ]);
  181. // Restore the original credentials
  182. $this->dbUser = $rootUser;
  183. $this->dbPassword = $rootPassword;
  184. }
  185. }
  186. }