MySQL.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 OC\DB\ConnectionAdapter;
  32. use OC\DB\MySqlTools;
  33. use OCP\IDBConnection;
  34. use Doctrine\DBAL\Platforms\MySQL80Platform;
  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. $this->createSpecificUser($username, new ConnectionAdapter($connection));
  48. //create the database
  49. $this->createDatabase($connection);
  50. //fill the database if needed
  51. $query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
  52. $connection->executeQuery($query, [$this->dbName, $this->tablePrefix.'users']);
  53. $connection->close();
  54. $connection = $this->connect();
  55. try {
  56. $connection->connect();
  57. } catch (\Exception $e) {
  58. $this->logger->error($e->getMessage(), [
  59. 'exception' => $e,
  60. ]);
  61. throw new \OC\DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'),
  62. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  63. }
  64. }
  65. /**
  66. * @param \OC\DB\Connection $connection
  67. */
  68. private function createDatabase($connection) {
  69. try {
  70. $name = $this->dbName;
  71. $user = $this->dbUser;
  72. //we can't use OC_DB functions here because we need to connect as the administrative user.
  73. $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
  74. $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE {$characterSet}_bin;";
  75. $connection->executeUpdate($query);
  76. } catch (\Exception $ex) {
  77. $this->logger->error('Database creation failed.', [
  78. 'exception' => $ex,
  79. 'app' => 'mysql.setup',
  80. ]);
  81. return;
  82. }
  83. try {
  84. //this query will fail if there aren't the right permissions, ignore the error
  85. $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'";
  86. $connection->executeUpdate($query);
  87. } catch (\Exception $ex) {
  88. $this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges.', [
  89. 'exception' => $ex,
  90. 'app' => 'mysql.setup',
  91. ]);
  92. }
  93. }
  94. /**
  95. * @param IDBConnection $connection
  96. * @throws \OC\DatabaseSetupException
  97. */
  98. private function createDBUser($connection) {
  99. try {
  100. $name = $this->dbUser;
  101. $password = $this->dbPassword;
  102. // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
  103. // the anonymous user would take precedence when there is one.
  104. if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
  105. $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
  106. $connection->executeUpdate($query);
  107. $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
  108. $connection->executeUpdate($query);
  109. } else {
  110. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  111. $connection->executeUpdate($query);
  112. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  113. $connection->executeUpdate($query);
  114. }
  115. } catch (\Exception $ex) {
  116. $this->logger->error('Database user creation failed.', [
  117. 'exception' => $ex,
  118. 'app' => 'mysql.setup',
  119. ]);
  120. throw $ex;
  121. }
  122. }
  123. /**
  124. * @param $username
  125. * @param IDBConnection $connection
  126. */
  127. private function createSpecificUser($username, $connection): void {
  128. $rootUser = $this->dbUser;
  129. $rootPassword = $this->dbPassword;
  130. //create a random password so we don't need to store the admin password in the config file
  131. $saveSymbols = str_replace(['\"', '\\', '\'', '`'], '', ISecureRandom::CHAR_SYMBOLS);
  132. $password = $this->random->generate(22, ISecureRandom::CHAR_ALPHANUMERIC . $saveSymbols)
  133. . $this->random->generate(2, ISecureRandom::CHAR_UPPER)
  134. . $this->random->generate(2, ISecureRandom::CHAR_LOWER)
  135. . $this->random->generate(2, ISecureRandom::CHAR_DIGITS)
  136. . $this->random->generate(2, $saveSymbols)
  137. ;
  138. $this->dbPassword = str_shuffle($password);
  139. try {
  140. //user already specified in config
  141. $oldUser = $this->config->getValue('dbuser', false);
  142. //we don't have a dbuser specified in config
  143. if ($this->dbUser !== $oldUser) {
  144. //add prefix to the admin username to prevent collisions
  145. $adminUser = substr('oc_' . $username, 0, 16);
  146. $i = 1;
  147. while (true) {
  148. //this should be enough to check for admin rights in mysql
  149. $query = 'SELECT user FROM mysql.user WHERE user=?';
  150. $result = $connection->executeQuery($query, [$adminUser]);
  151. //current dbuser has admin rights
  152. $data = $result->fetchAll();
  153. $result->closeCursor();
  154. //new dbuser does not exist
  155. if (count($data) === 0) {
  156. //use the admin login data for the new database user
  157. $this->dbUser = $adminUser;
  158. $this->createDBUser($connection);
  159. break;
  160. } else {
  161. //repeat with different username
  162. $length = strlen((string)$i);
  163. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  164. $i++;
  165. }
  166. }
  167. } else {
  168. // Reuse existing password if a database config is already present
  169. $this->dbPassword = $rootPassword;
  170. }
  171. } catch (\Exception $ex) {
  172. $this->logger->info('Can not create a new MySQL user, will continue with the provided user.', [
  173. 'exception' => $ex,
  174. 'app' => 'mysql.setup',
  175. ]);
  176. // Restore the original credentials
  177. $this->dbUser = $rootUser;
  178. $this->dbPassword = $rootPassword;
  179. }
  180. $this->config->setValues([
  181. 'dbuser' => $this->dbUser,
  182. 'dbpassword' => $this->dbPassword,
  183. ]);
  184. }
  185. }