Debian Codegraph @

src/main/org/h2/engine/Engine.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.engine;
7
8 import java.util.HashMap;
9 import java.util.Map;
10 import java.util.Objects;
11 import org.h2.api.ErrorCode;
12 import org.h2.command.CommandInterface;
13 import org.h2.command.dml.SetTypes;
14 import org.h2.message.DbException;
15 import org.h2.message.Trace;
16 import org.h2.security.auth.AuthenticationException;
17 import org.h2.security.auth.AuthenticationInfo;
18 import org.h2.security.auth.Authenticator;
19 import org.h2.store.fs.FileUtils;
20 import org.h2.util.DateTimeUtils;
21 import org.h2.util.MathUtils;
22 import org.h2.util.ParserUtil;
23 import org.h2.util.StringUtils;
24 import org.h2.util.ThreadDeadlockDetector;
25 import org.h2.util.TimeZoneProvider;
26 import org.h2.util.Utils;
27
28 /**
29 * The engine contains a map of all open databases.
30 * It is also responsible for opening and creating new databases.
31 * This is a singleton class.
32 */
33 public final class Engine {
34
35 private static final Map<String, DatabaseHolder> DATABASES = new HashMap<>();
36
37 private static volatile long WRONG_PASSWORD_DELAY = SysProperties.DELAY_WRONG_PASSWORD_MIN;
38
39 private static boolean JMX;
40
41 static {
42 if (SysProperties.THREAD_DEADLOCK_DETECTOR) {
43 ThreadDeadlockDetector.init();
44 }
45 }
46
47 private static SessionLocal openSession(ConnectionInfo ci, boolean ifExists, boolean forbidCreation,
48 String cipher) {
49 String name = ci.getName();
50 Database database;
51 ci.removeProperty("NO_UPGRADE", false);
52 boolean openNew = ci.getProperty("OPEN_NEW", false);
53 boolean opened = false;
54 User user = null;
55 DatabaseHolder databaseHolder;
56 if (!ci.isUnnamedInMemory()) {
57 synchronized (DATABASES) {
58 databaseHolder = DATABASES.computeIfAbsent(name, (key) -> new DatabaseHolder());
59 }
60 } else {
61 databaseHolder = new DatabaseHolder();
62 }
63 synchronized (databaseHolder) {
64 database = databaseHolder.database;
65 if (database == null || openNew) {
66 if (ci.isPersistent()) {
67 String p = ci.getProperty("MV_STORE");
68 String fileName;
69 if (p == null) {
70 fileName = name + Constants.SUFFIX_MV_FILE;
71 if (!FileUtils.exists(fileName)) {
72 throwNotFound(ifExists, forbidCreation, name);
73 fileName = name + Constants.SUFFIX_OLD_DATABASE_FILE;
74 if (FileUtils.exists(fileName)) {
75 throw DbException.getFileVersionError(fileName);
76 }
77 fileName = null;
78 }
79 } else {
80 fileName = name + Constants.SUFFIX_MV_FILE;
81 if (!FileUtils.exists(fileName)) {
82 throwNotFound(ifExists, forbidCreation, name);
83 fileName = null;
84 }
85 }
86 if (fileName != null && !FileUtils.canWrite(fileName)) {
87 ci.setProperty("ACCESS_MODE_DATA", "r");
88 }
89 } else {
90 throwNotFound(ifExists, forbidCreation, name);
91 }
92 database = new Database(ci, cipher);
93 opened = true;
94 boolean found = false;
95 for (RightOwner rightOwner : database.getAllUsersAndRoles()) {
96 if (rightOwner instanceof User) {
97 found = true;
98 break;
99 }
100 }
101 if (!found) {
102 // users is the last thing we add, so if no user is around,
103 // the database is new (or not initialized correctly)
104 user = new User(database, database.allocateObjectId(), ci.getUserName(), false);
105 user.setAdmin(true);
106 user.setUserPasswordHash(ci.getUserPasswordHash());
107 database.setMasterUser(user);
108 }
109 databaseHolder.database = database;
110 }
111 }
112
113 if (opened) {
114 // start the thread when already synchronizing on the database
115 // otherwise a deadlock can occur when the writer thread
116 // opens a new database (as in recovery testing)
117 database.opened();
118 }
119 if (database.isClosing()) {
120 return null;
121 }
122 if (user == null) {
123 if (database.validateFilePasswordHash(cipher, ci.getFilePasswordHash())) {
124 if (ci.getProperty("AUTHREALM")== null) {
125 user = database.findUser(ci.getUserName());
126 if (user != null) {
127 if (!user.validateUserPasswordHash(ci.getUserPasswordHash())) {
128 user = null;
129 }
130 }
131 } else {
132 Authenticator authenticator = database.getAuthenticator();
133 if (authenticator==null) {
134 throw DbException.get(ErrorCode.AUTHENTICATOR_NOT_AVAILABLE, name);
135 } else {
136 try {
137 AuthenticationInfo authenticationInfo=new AuthenticationInfo(ci);
138 user = database.getAuthenticator().authenticate(authenticationInfo, database);
139 } catch (AuthenticationException authenticationError) {
140 database.getTrace(Trace.DATABASE).error(authenticationError,
141 "an error occurred during authentication; user: \"" +
142 ci.getUserName() + "\"");
143 }
144 }
145 }
146 }
147 if (opened && (user == null || !user.isAdmin())) {
148 // reset - because the user is not an admin, and has no
149 // right to listen to exceptions
150 database.setEventListener(null);
151 }
152 }
153 if (user == null) {
154 DbException er = DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD);
155 database.getTrace(Trace.DATABASE).error(er, "wrong user or password; user: \"" +
156 ci.getUserName() + "\"");
157 database.removeSession(null);
158 throw er;
159 }
160 //Prevent to set _PASSWORD
161 ci.cleanAuthenticationInfo();
162 checkClustering(ci, database);
163 SessionLocal session = database.createSession(user, ci.getNetworkConnectionInfo());
164 if (session == null) {
165 // concurrently closing
166 return null;
167 }
168 if (ci.getProperty("OLD_INFORMATION_SCHEMA", false)) {
169 session.setOldInformationSchema(true);
170 }
171 if (ci.getProperty("JMX", false)) {
172 try {
173 Utils.callStaticMethod(
174 "org.h2.jmx.DatabaseInfo.registerMBean", ci, database);
175 } catch (Exception e) {
176 database.removeSession(session);
177 throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, e, "JMX");
178 }
179 JMX = true;
180 }
181 return session;
182 }
183
184 private static void throwNotFound(boolean ifExists, boolean forbidCreation, String name) {
185 if (ifExists) {
186 throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_WITH_IF_EXISTS_1, name);
187 }
188 if (forbidCreation) {
189 throw DbException.get(ErrorCode.REMOTE_DATABASE_NOT_FOUND_1, name);
190 }
191 }
192
193 /**
194 * Open a database connection with the given connection information.
195 *
196 * @param ci the connection information
197 * @return the session
198 */
199 public static SessionLocal createSession(ConnectionInfo ci) {
200 try {
201 SessionLocal session = openSession(ci);
202 validateUserAndPassword(true);
203 return session;
204 } catch (DbException e) {
205 if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
206 validateUserAndPassword(false);
207 }
208 throw e;
209 }
210 }
211
212 private static SessionLocal openSession(ConnectionInfo ci) {
213 boolean ifExists = ci.removeProperty("IFEXISTS", false);
214 boolean forbidCreation = ci.removeProperty("FORBID_CREATION", false);
215 boolean ignoreUnknownSetting = ci.removeProperty(
216 "IGNORE_UNKNOWN_SETTINGS", false);
217 String cipher = ci.removeProperty("CIPHER", null);
218 String init = ci.removeProperty("INIT", null);
219 SessionLocal session;
220 long start = System.nanoTime();
221 for (;;) {
222 session = openSession(ci, ifExists, forbidCreation, cipher);
223 if (session != null) {
224 break;
225 }
226 // we found a database that is currently closing
227 // wait a bit to avoid a busy loop (the method is synchronized)
228 if (System.nanoTime() - start > DateTimeUtils.NANOS_PER_MINUTE) {
229 throw DbException.get(ErrorCode.DATABASE_ALREADY_OPEN_1,
230 "Waited for database closing longer than 1 minute");
231 }
232 try {
233 Thread.sleep(1);
234 } catch (InterruptedException e) {
235 throw DbException.get(ErrorCode.DATABASE_CALLED_AT_SHUTDOWN);
236 }
237 }
238 synchronized (session) {
239 session.setAllowLiterals(true);
240 DbSettings defaultSettings = DbSettings.DEFAULT;
241 for (String setting : ci.getKeys()) {
242 if (defaultSettings.containsKey(setting)) {
243 // database setting are only used when opening the database
244 continue;
245 }
246 String value = ci.getProperty(setting);
247 StringBuilder builder = new StringBuilder("SET ").append(setting).append(' ');
248 if (!ParserUtil.isSimpleIdentifier(setting, false, false)) {
249 if (!setting.equalsIgnoreCase("TIME ZONE")) {
250 throw DbException.get(ErrorCode.UNSUPPORTED_SETTING_1, setting);
251 }
252 StringUtils.quoteStringSQL(builder, value);
253 } else {
254 builder.append(value);
255 }
256 try {
257 CommandInterface command = session.prepareLocal(builder.toString());
258 command.executeUpdate(null);
259 } catch (DbException e) {
260 if (e.getErrorCode() == ErrorCode.ADMIN_RIGHTS_REQUIRED) {
261 session.getTrace().error(e, "admin rights required; user: \"" +
262 ci.getUserName() + "\"");
263 } else {
264 session.getTrace().error(e, "");
265 }
266 if (!ignoreUnknownSetting) {
267 session.close();
268 throw e;
269 }
270 }
271 }
272 TimeZoneProvider timeZone = ci.getTimeZone();
273 if (timeZone != null) {
274 session.setTimeZone(timeZone);
275 }
276 if (init != null) {
277 try {
278 CommandInterface command = session.prepareLocal(init);
279 command.executeUpdate(null);
280 } catch (DbException e) {
281 if (!ignoreUnknownSetting) {
282 session.close();
283 throw e;
284 }
285 }
286 }
287 session.setAllowLiterals(false);
288 session.commit(true);
289 }
290 return session;
291 }
292
293 private static void checkClustering(ConnectionInfo ci, Database database) {
294 String clusterSession = ci.getProperty(SetTypes.CLUSTER, null);
295 if (Constants.CLUSTERING_DISABLED.equals(clusterSession)) {
296 // in this case, no checking is made
297 // (so that a connection can be made to disable/change clustering)
298 return;
299 }
300 String clusterDb = database.getCluster();
301 if (!Constants.CLUSTERING_DISABLED.equals(clusterDb)) {
302 if (!Constants.CLUSTERING_ENABLED.equals(clusterSession)) {
303 if (!Objects.equals(clusterSession, clusterDb)) {
304 if (clusterDb.equals(Constants.CLUSTERING_DISABLED)) {
305 throw DbException.get(
306 ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_ALONE);
307 }
308 throw DbException.get(
309 ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_CLUSTERED_1,
310 clusterDb);
311 }
312 }
313 }
314 }
315
316 /**
317 * Called after a database has been closed, to remove the object from the
318 * list of open databases.
319 *
320 * @param name the database name
321 */
322 static void close(String name) {
323 if (JMX) {
324 try {
325 Utils.callStaticMethod("org.h2.jmx.DatabaseInfo.unregisterMBean", name);
326 } catch (Exception e) {
327 throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, e, "JMX");
328 }
329 }
330 synchronized (DATABASES) {
331 DATABASES.remove(name);
332 }
333 }
334
335 /**
336 * This method is called after validating user name and password. If user
337 * name and password were correct, the sleep time is reset, otherwise this
338 * method waits some time (to make brute force / rainbow table attacks
339 * harder) and then throws a 'wrong user or password' exception. The delay
340 * is a bit randomized to protect against timing attacks. Also the delay
341 * doubles after each unsuccessful logins, to make brute force attacks
342 * harder.
343 *
344 * There is only one exception message both for wrong user and for
345 * wrong password, to make it harder to get the list of user names. This
346 * method must only be called from one place, so it is not possible from the
347 * stack trace to see if the user name was wrong or the password.
348 *
349 * @param correct if the user name or the password was correct
350 * @throws DbException the exception 'wrong user or password'
351 */
352 private static void validateUserAndPassword(boolean correct) {
353 int min = SysProperties.DELAY_WRONG_PASSWORD_MIN;
354 if (correct) {
355 long delay = WRONG_PASSWORD_DELAY;
356 if (delay > min && delay > 0) {
357 // the first correct password must be blocked,
358 // otherwise parallel attacks are possible
359 synchronized (Engine.class) {
360 // delay up to the last delay
361 // an attacker can't know how long it will be
362 delay = MathUtils.secureRandomInt((int) delay);
363 try {
364 Thread.sleep(delay);
365 } catch (InterruptedException e) {
366 // ignore
367 }
368 WRONG_PASSWORD_DELAY = min;
369 }
370 }
371 } else {
372 // this method is not synchronized on the Engine, so that
373 // regular successful attempts are not blocked
374 synchronized (Engine.class) {
375 long delay = WRONG_PASSWORD_DELAY;
376 int max = SysProperties.DELAY_WRONG_PASSWORD_MAX;
377 if (max <= 0) {
378 max = Integer.MAX_VALUE;
379 }
380 WRONG_PASSWORD_DELAY += WRONG_PASSWORD_DELAY;
381 if (WRONG_PASSWORD_DELAY > max || WRONG_PASSWORD_DELAY < 0) {
382 WRONG_PASSWORD_DELAY = max;
383 }
384 if (min > 0) {
385 // a bit more to protect against timing attacks
386 delay += Math.abs(MathUtils.secureRandomLong() % 100);
387 try {
388 Thread.sleep(delay);
389 } catch (InterruptedException e) {
390 // ignore
391 }
392 }
393 throw DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD);
394 }
395 }
396 }
397
398 private Engine() {
399 }
400
401 private static final class DatabaseHolder {
402
403 DatabaseHolder() {
404 }
405
406 volatile Database database;
407 }
408 }