Debian Codegraph @

src/main/org/h2/engine/ConnectionInfo.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.io.File;
9 import java.io.IOException;
10 import java.util.Arrays;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.Properties;
14
15 import org.h2.api.ErrorCode;
16 import org.h2.command.dml.SetTypes;
17 import org.h2.message.DbException;
18 import org.h2.security.SHA256;
19 import org.h2.store.fs.FileUtils;
20 import org.h2.store.fs.encrypt.FilePathEncrypt;
21 import org.h2.store.fs.rec.FilePathRec;
22 import org.h2.util.IOUtils;
23 import org.h2.util.NetworkConnectionInfo;
24 import org.h2.util.SortedProperties;
25 import org.h2.util.StringUtils;
26 import org.h2.util.TimeZoneProvider;
27 import org.h2.util.Utils;
28
29 /**
30 * Encapsulates the connection settings, including user name and password.
31 */
32 public class ConnectionInfo implements Cloneable {
33
34 private static final HashSet<String> KNOWN_SETTINGS;
35
36 private static final HashSet<String> IGNORED_BY_PARSER;
37
38 private Properties prop = new Properties();
39 private String originalURL;
40 private String url;
41 private String user;
42 private byte[] filePasswordHash;
43 private byte[] fileEncryptionKey;
44 private byte[] userPasswordHash;
45
46 private TimeZoneProvider timeZone;
47
48 /**
49 * The database name
50 */
51 private String name;
52 private String nameNormalized;
53 private boolean remote;
54 private boolean ssl;
55 private boolean persistent;
56 private boolean unnamed;
57
58 private NetworkConnectionInfo networkConnectionInfo;
59
60 /**
61 * Create a connection info object.
62 *
63 * @param name the database name (including tags), but without the
64 * "jdbc:h2:" prefix
65 */
66 public ConnectionInfo(String name) {
67 this.name = name;
68 this.url = Constants.START_URL + name;
69 parseName();
70 }
71
72 /**
73 * Create a connection info object.
74 *
75 * @param u the database URL (must start with jdbc:h2:)
76 * @param info the connection properties or {@code null}
77 * @param user the user name or {@code null}
78 * @param password
79 * the password as {@code String} or {@code char[]}, or
80 * {@code null}
81 */
82 public ConnectionInfo(String u, Properties info, String user, Object password) {
83 u = remapURL(u);
84 originalURL = url = u;
85 if (!u.startsWith(Constants.START_URL)) {
86 throw getFormatException();
87 }
88 if (info != null) {
89 readProperties(info);
90 }
91 if (user != null) {
92 prop.put("USER", user);
93 }
94 if (password != null) {
95 prop.put("PASSWORD", password);
96 }
97 readSettingsFromURL();
98 Object timeZoneName = prop.remove("TIME ZONE");
99 if (timeZoneName != null) {
100 timeZone = TimeZoneProvider.ofId(timeZoneName.toString());
101 }
102 setUserName(removeProperty("USER", ""));
103 name = url.substring(Constants.START_URL.length());
104 parseName();
105 convertPasswords();
106 String recoverTest = removeProperty("RECOVER_TEST", null);
107 if (recoverTest != null) {
108 FilePathRec.register();
109 try {
110 Utils.callStaticMethod("org.h2.store.RecoverTester.init", recoverTest);
111 } catch (Exception e) {
112 throw DbException.convert(e);
113 }
114 name = "rec:" + name;
115 }
116 }
117
118 static {
119 String[] commonSettings = { //
120 "ACCESS_MODE_DATA", "AUTO_RECONNECT", "AUTO_SERVER", "AUTO_SERVER_PORT", //
121 "CACHE_TYPE", //
122 "FILE_LOCK", //
123 "JMX", //
124 "NETWORK_TIMEOUT", //
125 "OLD_INFORMATION_SCHEMA", "OPEN_NEW", //
126 "PAGE_SIZE", //
127 "RECOVER", //
128 };
129 String[] settings = { //
130 "AUTHREALM", "AUTHZPWD", "AUTOCOMMIT", //
131 "CIPHER", "CREATE", //
132 "FORBID_CREATION", //
133 "IGNORE_UNKNOWN_SETTINGS", "IFEXISTS", "INIT", //
134 "NO_UPGRADE", //
135 "PASSWORD", "PASSWORD_HASH", //
136 "RECOVER_TEST", //
137 "USER" //
138 };
139 HashSet<String> set = new HashSet<>(128);
140 set.addAll(SetTypes.getTypes());
141 for (String setting : commonSettings) {
142 if (!set.add(setting)) {
143 throw DbException.getInternalError(setting);
144 }
145 }
146 for (String setting : settings) {
147 if (!set.add(setting)) {
148 throw DbException.getInternalError(setting);
149 }
150 }
151 KNOWN_SETTINGS = set;
152 settings = new String[] { //
153 "ASSERT", //
154 "BINARY_COLLATION", //
155 "DB_CLOSE_ON_EXIT", //
156 "PAGE_STORE", //
157 "UUID_COLLATION", //
158 };
159 set = new HashSet<>(32);
160 for (String setting : commonSettings) {
161 set.add(setting);
162 }
163 for (String setting : settings) {
164 set.add(setting);
165 }
166 IGNORED_BY_PARSER = set;
167 }
168
169 private static boolean isKnownSetting(String s) {
170 return KNOWN_SETTINGS.contains(s);
171 }
172
173 /**
174 * Returns whether setting with the specified name should be ignored by
175 * parser.
176 *
177 * @param name
178 * the name of the setting
179 * @return whether setting with the specified name should be ignored by
180 * parser
181 */
182 public static boolean isIgnoredByParser(String name) {
183 return IGNORED_BY_PARSER.contains(name);
184 }
185
186 @Override
187 public ConnectionInfo clone() throws CloneNotSupportedException {
188 ConnectionInfo clone = (ConnectionInfo) super.clone();
189 clone.prop = (Properties) prop.clone();
190 clone.filePasswordHash = Utils.cloneByteArray(filePasswordHash);
191 clone.fileEncryptionKey = Utils.cloneByteArray(fileEncryptionKey);
192 clone.userPasswordHash = Utils.cloneByteArray(userPasswordHash);
193 return clone;
194 }
195
196 private void parseName() {
197 if (".".equals(name)) {
198 name = "mem:";
199 }
200 if (name.startsWith("tcp:")) {
201 remote = true;
202 name = name.substring("tcp:".length());
203 } else if (name.startsWith("ssl:")) {
204 remote = true;
205 ssl = true;
206 name = name.substring("ssl:".length());
207 } else if (name.startsWith("mem:")) {
208 persistent = false;
209 if ("mem:".equals(name)) {
210 unnamed = true;
211 }
212 } else if (name.startsWith("file:")) {
213 name = name.substring("file:".length());
214 persistent = true;
215 } else {
216 persistent = true;
217 }
218 if (persistent && !remote) {
219 name = IOUtils.nameSeparatorsToNative(name);
220 }
221 }
222
223 /**
224 * Set the base directory of persistent databases, unless the database is in
225 * the user home folder (~).
226 *
227 * @param dir the new base directory
228 */
229 public void setBaseDir(String dir) {
230 if (persistent) {
231 String absDir = FileUtils.unwrap(FileUtils.toRealPath(dir));
232 boolean absolute = FileUtils.isAbsolute(name);
233 String n;
234 String prefix = null;
235 if (dir.endsWith(File.separator)) {
236 dir = dir.substring(0, dir.length() - 1);
237 }
238 if (absolute) {
239 n = name;
240 } else {
241 n = FileUtils.unwrap(name);
242 prefix = name.substring(0, name.length() - n.length());
243 n = dir + File.separatorChar + n;
244 }
245 String normalizedName = FileUtils.unwrap(FileUtils.toRealPath(n));
246 if (normalizedName.equals(absDir) || !normalizedName.startsWith(absDir)) {
247 // database name matches the baseDir or
248 // database name is clearly outside of the baseDir
249 throw DbException.get(ErrorCode.IO_EXCEPTION_1, normalizedName + " outside " +
250 absDir);
251 }
252 if (absDir.endsWith("/") || absDir.endsWith("\\")) {
253 // no further checks are needed for C:/ and similar
254 } else if (normalizedName.charAt(absDir.length()) != '/') {
255 // database must be within the directory
256 // (with baseDir=/test, the database name must not be
257 // /test2/x and not /test2)
258 throw DbException.get(ErrorCode.IO_EXCEPTION_1, normalizedName + " outside " +
259 absDir);
260 }
261 if (!absolute) {
262 name = prefix + dir + File.separatorChar + FileUtils.unwrap(name);
263 }
264 }
265 }
266
267 /**
268 * Check if this is a remote connection.
269 *
270 * @return true if it is
271 */
272 public boolean isRemote() {
273 return remote;
274 }
275
276 /**
277 * Check if the referenced database is persistent.
278 *
279 * @return true if it is
280 */
281 public boolean isPersistent() {
282 return persistent;
283 }
284
285 /**
286 * Check if the referenced database is an unnamed in-memory database.
287 *
288 * @return true if it is
289 */
290 boolean isUnnamedInMemory() {
291 return unnamed;
292 }
293
294 private void readProperties(Properties info) {
295 Object[] list = info.keySet().toArray();
296 DbSettings s = null;
297 for (Object k : list) {
298 String key = StringUtils.toUpperEnglish(k.toString());
299 if (prop.containsKey(key)) {
300 throw DbException.get(ErrorCode.DUPLICATE_PROPERTY_1, key);
301 }
302 Object value = info.get(k);
303 if (isKnownSetting(key)) {
304 prop.put(key, value);
305 } else {
306 if (s == null) {
307 s = getDbSettings();
308 }
309 if (s.containsKey(key)) {
310 prop.put(key, value);
311 }
312 }
313 }
314 }
315
316 private void readSettingsFromURL() {
317 DbSettings defaultSettings = DbSettings.DEFAULT;
318 int idx = url.indexOf(';');
319 if (idx >= 0) {
320 String settings = url.substring(idx + 1);
321 url = url.substring(0, idx);
322 String unknownSetting = null;
323 String[] list = StringUtils.arraySplit(settings, ';', false);
324 for (String setting : list) {
325 if (setting.isEmpty()) {
326 continue;
327 }
328 int equal = setting.indexOf('=');
329 if (equal < 0) {
330 throw getFormatException();
331 }
332 String value = setting.substring(equal + 1);
333 String key = setting.substring(0, equal);
334 key = StringUtils.toUpperEnglish(key);
335 if (isKnownSetting(key) || defaultSettings.containsKey(key)) {
336 String old = prop.getProperty(key);
337 if (old != null && !old.equals(value)) {
338 throw DbException.get(ErrorCode.DUPLICATE_PROPERTY_1, key);
339 }
340 prop.setProperty(key, value);
341 } else {
342 unknownSetting = key;
343 }
344 }
345 if (unknownSetting != null //
346 && !Utils.parseBoolean(prop.getProperty("IGNORE_UNKNOWN_SETTINGS"), false, false)) {
347 throw DbException.get(ErrorCode.UNSUPPORTED_SETTING_1, unknownSetting);
348 }
349 }
350 }
351
352 private void preservePasswordForAuthentication(Object password) {
353 if ((!isRemote() || isSSL()) && prop.containsKey("AUTHREALM") && password!=null) {
354 prop.put("AUTHZPWD",password instanceof char[] ? new String((char[])password) : password);
355 }
356 }
357
358 private char[] removePassword() {
359 Object p = prop.remove("PASSWORD");
360 preservePasswordForAuthentication(p);
361 if (p == null) {
362 return new char[0];
363 } else if (p instanceof char[]) {
364 return (char[]) p;
365 } else {
366 return p.toString().toCharArray();
367 }
368 }
369
370 /**
371 * Split the password property into file password and user password if
372 * necessary, and convert them to the internal hash format.
373 */
374 private void convertPasswords() {
375 char[] password = removePassword();
376 boolean passwordHash = removeProperty("PASSWORD_HASH", false);
377 if (getProperty("CIPHER", null) != null) {
378 // split password into (filePassword+' '+userPassword)
379 int space = -1;
380 for (int i = 0, len = password.length; i < len; i++) {
381 if (password[i] == ' ') {
382 space = i;
383 break;
384 }
385 }
386 if (space < 0) {
387 throw DbException.get(ErrorCode.WRONG_PASSWORD_FORMAT);
388 }
389 char[] np = Arrays.copyOfRange(password, space + 1, password.length);
390 char[] filePassword = Arrays.copyOf(password, space);
391 Arrays.fill(password, (char) 0);
392 password = np;
393 fileEncryptionKey = FilePathEncrypt.getPasswordBytes(filePassword);
394 filePasswordHash = hashPassword(passwordHash, "file", filePassword);
395 }
396 userPasswordHash = hashPassword(passwordHash, user, password);
397 }
398
399 private static byte[] hashPassword(boolean passwordHash, String userName,
400 char[] password) {
401 if (passwordHash) {
402 return StringUtils.convertHexToBytes(new String(password));
403 }
404 if (userName.isEmpty() && password.length == 0) {
405 return new byte[0];
406 }
407 return SHA256.getKeyPasswordHash(userName, password);
408 }
409
410 /**
411 * Get a boolean property if it is set and return the value.
412 *
413 * @param key the property name
414 * @param defaultValue the default value
415 * @return the value
416 */
417 public boolean getProperty(String key, boolean defaultValue) {
418 return Utils.parseBoolean(getProperty(key, null), defaultValue, false);
419 }
420
421 /**
422 * Remove a boolean property if it is set and return the value.
423 *
424 * @param key the property name
425 * @param defaultValue the default value
426 * @return the value
427 */
428 public boolean removeProperty(String key, boolean defaultValue) {
429 return Utils.parseBoolean(removeProperty(key, null), defaultValue, false);
430 }
431
432 /**
433 * Remove a String property if it is set and return the value.
434 *
435 * @param key the property name
436 * @param defaultValue the default value
437 * @return the value
438 */
439 String removeProperty(String key, String defaultValue) {
440 if (SysProperties.CHECK && !isKnownSetting(key)) {
441 throw DbException.getInternalError(key);
442 }
443 Object x = prop.remove(key);
444 return x == null ? defaultValue : x.toString();
445 }
446
447 /**
448 * Get the unique and normalized database name (excluding settings).
449 *
450 * @return the database name
451 */
452 public String getName() {
453 if (!persistent) {
454 return name;
455 }
456 if (nameNormalized == null) {
457 if (!FileUtils.isAbsolute(name) && !name.contains("./") && !name.contains(".\\") && !name.contains(":/")
458 && !name.contains(":\\")) {
459 // the name could start with "./", or
460 // it could start with a prefix such as "nioMapped:./"
461 // for Windows, the path "\test" is not considered
462 // absolute as the drive letter is missing,
463 // but we consider it absolute
464 throw DbException.get(ErrorCode.URL_RELATIVE_TO_CWD, originalURL);
465 }
466 String suffix = Constants.SUFFIX_MV_FILE;
467 String n = FileUtils.toRealPath(name + suffix);
468 String fileName = FileUtils.getName(n);
469 if (fileName.length() < suffix.length() + 1) {
470 throw DbException.get(ErrorCode.INVALID_DATABASE_NAME_1, name);
471 }
472 nameNormalized = n.substring(0, n.length() - suffix.length());
473 }
474 return nameNormalized;
475 }
476
477 /**
478 * Get the file password hash if it is set.
479 *
480 * @return the password hash or null
481 */
482 public byte[] getFilePasswordHash() {
483 return filePasswordHash;
484 }
485
486 byte[] getFileEncryptionKey() {
487 return fileEncryptionKey;
488 }
489
490 /**
491 * Get the name of the user.
492 *
493 * @return the user name
494 */
495 public String getUserName() {
496 return user;
497 }
498
499 /**
500 * Get the user password hash.
501 *
502 * @return the password hash
503 */
504 byte[] getUserPasswordHash() {
505 return userPasswordHash;
506 }
507
508 /**
509 * Get the property keys.
510 *
511 * @return the property keys
512 */
513 String[] getKeys() {
514 return prop.keySet().toArray(new String[prop.size()]);
515 }
516
517 /**
518 * Get the value of the given property.
519 *
520 * @param key the property key
521 * @return the value as a String
522 */
523 String getProperty(String key) {
524 Object value = prop.get(key);
525 if (!(value instanceof String)) {
526 return null;
527 }
528 return value.toString();
529 }
530
531 /**
532 * Get the value of the given property.
533 *
534 * @param key the property key
535 * @param defaultValue the default value
536 * @return the value as a String
537 */
538 int getProperty(String key, int defaultValue) {
539 if (SysProperties.CHECK && !isKnownSetting(key)) {
540 throw DbException.getInternalError(key);
541 }
542 String s = getProperty(key);
543 return s == null ? defaultValue : Integer.parseInt(s);
544 }
545
546 /**
547 * Get the value of the given property.
548 *
549 * @param key the property key
550 * @param defaultValue the default value
551 * @return the value as a String
552 */
553 public String getProperty(String key, String defaultValue) {
554 if (SysProperties.CHECK && !isKnownSetting(key)) {
555 throw DbException.getInternalError(key);
556 }
557 String s = getProperty(key);
558 return s == null ? defaultValue : s;
559 }
560
561 /**
562 * Get the value of the given property.
563 *
564 * @param setting the setting id
565 * @param defaultValue the default value
566 * @return the value as a String
567 */
568 String getProperty(int setting, String defaultValue) {
569 String key = SetTypes.getTypeName(setting);
570 String s = getProperty(key);
571 return s == null ? defaultValue : s;
572 }
573
574 /**
575 * Get the value of the given property.
576 *
577 * @param setting the setting id
578 * @param defaultValue the default value
579 * @return the value as an integer
580 */
581 int getIntProperty(int setting, int defaultValue) {
582 String key = SetTypes.getTypeName(setting);
583 String s = getProperty(key, null);
584 try {
585 return s == null ? defaultValue : Integer.decode(s);
586 } catch (NumberFormatException e) {
587 return defaultValue;
588 }
589 }
590
591 /**
592 * Check if this is a remote connection with SSL enabled.
593 *
594 * @return true if it is
595 */
596 boolean isSSL() {
597 return ssl;
598 }
599
600 /**
601 * Overwrite the user name. The user name is case-insensitive and stored in
602 * uppercase. English conversion is used.
603 *
604 * @param name the user name
605 */
606 public void setUserName(String name) {
607 this.user = StringUtils.toUpperEnglish(name);
608 }
609
610 /**
611 * Set the user password hash.
612 *
613 * @param hash the new hash value
614 */
615 public void setUserPasswordHash(byte[] hash) {
616 this.userPasswordHash = hash;
617 }
618
619 /**
620 * Set the file password hash.
621 *
622 * @param hash the new hash value
623 */
624 public void setFilePasswordHash(byte[] hash) {
625 this.filePasswordHash = hash;
626 }
627
628 public void setFileEncryptionKey(byte[] key) {
629 this.fileEncryptionKey = key;
630 }
631
632 /**
633 * Overwrite a property.
634 *
635 * @param key the property name
636 * @param value the value
637 */
638 public void setProperty(String key, String value) {
639 // value is null if the value is an object
640 if (value != null) {
641 prop.setProperty(key, value);
642 }
643 }
644
645 /**
646 * Get the database URL.
647 *
648 * @return the URL
649 */
650 public String getURL() {
651 return url;
652 }
653
654 /**
655 * Get the complete original database URL.
656 *
657 * @return the database URL
658 */
659 public String getOriginalURL() {
660 return originalURL;
661 }
662
663 /**
664 * Set the original database URL.
665 *
666 * @param url the database url
667 */
668 public void setOriginalURL(String url) {
669 originalURL = url;
670 }
671
672 /**
673 * Returns the time zone.
674 *
675 * @return the time zone
676 */
677 public TimeZoneProvider getTimeZone() {
678 return timeZone;
679 }
680
681 /**
682 * Generate a URL format exception.
683 *
684 * @return the exception
685 */
686 DbException getFormatException() {
687 return DbException.get(ErrorCode.URL_FORMAT_ERROR_2, Constants.URL_FORMAT, url);
688 }
689
690 /**
691 * Switch to server mode, and set the server name and database key.
692 *
693 * @param serverKey the server name, '/', and the security key
694 */
695 public void setServerKey(String serverKey) {
696 remote = true;
697 persistent = false;
698 this.name = serverKey;
699 }
700
701 /**
702 * Returns the network connection information, or {@code null}.
703 *
704 * @return the network connection information, or {@code null}
705 */
706 public NetworkConnectionInfo getNetworkConnectionInfo() {
707 return networkConnectionInfo;
708 }
709
710 /**
711 * Sets the network connection information.
712 *
713 * @param networkConnectionInfo the network connection information
714 */
715 public void setNetworkConnectionInfo(NetworkConnectionInfo networkConnectionInfo) {
716 this.networkConnectionInfo = networkConnectionInfo;
717 }
718
719 public DbSettings getDbSettings() {
720 DbSettings defaultSettings = DbSettings.DEFAULT;
721 HashMap<String, String> s = new HashMap<>(DbSettings.TABLE_SIZE);
722 for (Object k : prop.keySet()) {
723 String key = k.toString();
724 if (!isKnownSetting(key) && defaultSettings.containsKey(key)) {
725 s.put(key, prop.getProperty(key));
726 }
727 }
728 return DbSettings.getInstance(s);
729 }
730
731 private static String remapURL(String url) {
732 String urlMap = SysProperties.URL_MAP;
733 if (urlMap != null && !urlMap.isEmpty()) {
734 try {
735 SortedProperties prop;
736 prop = SortedProperties.loadProperties(urlMap);
737 String url2 = prop.getProperty(url);
738 if (url2 == null) {
739 prop.put(url, "");
740 prop.store(urlMap);
741 } else {
742 url2 = url2.trim();
743 if (!url2.isEmpty()) {
744 return url2;
745 }
746 }
747 } catch (IOException e) {
748 throw DbException.convert(e);
749 }
750 }
751 return url;
752 }
753
754 /**
755 * Clear authentication properties.
756 */
757 public void cleanAuthenticationInfo() {
758 removeProperty("AUTHREALM", false);
759 removeProperty("AUTHZPWD", false);
760 }
761 }