| 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.server.web; |
| 7 |
|
| 8 |
import java.io.IOException; |
| 9 |
import java.io.InputStream; |
| 10 |
import java.io.OutputStream; |
| 11 |
import java.net.ServerSocket; |
| 12 |
import java.net.Socket; |
| 13 |
import java.nio.charset.StandardCharsets; |
| 14 |
import java.nio.file.Files; |
| 15 |
import java.nio.file.Path; |
| 16 |
import java.nio.file.Paths; |
| 17 |
import java.sql.Connection; |
| 18 |
import java.sql.SQLException; |
| 19 |
import java.time.ZoneId; |
| 20 |
import java.time.ZonedDateTime; |
| 21 |
import java.time.format.DateTimeFormatter; |
| 22 |
import java.util.ArrayList; |
| 23 |
import java.util.Arrays; |
| 24 |
import java.util.Collections; |
| 25 |
import java.util.HashMap; |
| 26 |
import java.util.HashSet; |
| 27 |
import java.util.Locale; |
| 28 |
import java.util.Map; |
| 29 |
import java.util.Map.Entry; |
| 30 |
import java.util.Properties; |
| 31 |
import java.util.Set; |
| 32 |
|
| 33 |
import org.h2.engine.Constants; |
| 34 |
import org.h2.engine.SysProperties; |
| 35 |
import org.h2.message.DbException; |
| 36 |
import org.h2.security.SHA256; |
| 37 |
import org.h2.server.Service; |
| 38 |
import org.h2.server.ShutdownHandler; |
| 39 |
import org.h2.store.fs.FileUtils; |
| 40 |
import org.h2.util.JdbcUtils; |
| 41 |
import org.h2.util.MathUtils; |
| 42 |
import org.h2.util.NetUtils; |
| 43 |
import org.h2.util.NetworkConnectionInfo; |
| 44 |
import org.h2.util.SortedProperties; |
| 45 |
import org.h2.util.StringUtils; |
| 46 |
import org.h2.util.Tool; |
| 47 |
import org.h2.util.Utils; |
| 48 |
|
| 49 |
/** |
| 50 |
* The web server is a simple standalone HTTP server that implements the H2 |
| 51 |
* Console application. It is not optimized for performance. |
| 52 |
*/ |
| 53 |
public class WebServer implements Service { |
| 54 |
|
| 55 |
static final String[][] LANGUAGES = { |
| 56 |
{ "cs", "\u010ce\u0161tina" }, |
| 57 |
{ "de", "Deutsch" }, |
| 58 |
{ "en", "English" }, |
| 59 |
{ "es", "Espa\u00f1ol" }, |
| 60 |
{ "fr", "Fran\u00e7ais" }, |
| 61 |
{ "hi", "Hindi \u0939\u093f\u0902\u0926\u0940" }, |
| 62 |
{ "hu", "Magyar"}, |
| 63 |
{ "ko", "\ud55c\uad6d\uc5b4"}, |
| 64 |
{ "in", "Indonesia"}, |
| 65 |
{ "it", "Italiano"}, |
| 66 |
{ "ja", "\u65e5\u672c\u8a9e"}, |
| 67 |
{ "nl", "Nederlands"}, |
| 68 |
{ "pl", "Polski"}, |
| 69 |
{ "pt_BR", "Portugu\u00eas (Brasil)"}, |
| 70 |
{ "pt_PT", "Portugu\u00eas (Europeu)"}, |
| 71 |
{ "ru", "\u0440\u0443\u0441\u0441\u043a\u0438\u0439"}, |
| 72 |
{ "sk", "Slovensky"}, |
| 73 |
{ "tr", "T\u00fcrk\u00e7e"}, |
| 74 |
{ "uk", "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430"}, |
| 75 |
{ "zh_CN", "\u4e2d\u6587 (\u7b80\u4f53)"}, |
| 76 |
{ "zh_TW", "\u4e2d\u6587 (\u7e41\u9ad4)"}, |
| 77 |
}; |
| 78 |
|
| 79 |
private static final String COMMAND_HISTORY = "commandHistory"; |
| 80 |
|
| 81 |
private static final String DEFAULT_LANGUAGE = "en"; |
| 82 |
|
| 83 |
private static final String[] GENERIC = { |
| 84 |
"Generic JNDI Data Source|javax.naming.InitialContext|" + |
| 85 |
"java:comp/env/jdbc/Test|sa", |
| 86 |
"Generic Teradata|com.teradata.jdbc.TeraDriver|" + |
| 87 |
"jdbc:teradata://whomooz/|", |
| 88 |
"Generic Snowflake|com.snowflake.client.jdbc.SnowflakeDriver|" + |
| 89 |
"jdbc:snowflake://accountName.snowflakecomputing.com|", |
| 90 |
"Generic Redshift|com.amazon.redshift.jdbc42.Driver|" + |
| 91 |
"jdbc:redshift://endpoint:5439/database|", |
| 92 |
"Generic Impala|org.cloudera.impala.jdbc41.Driver|" + |
| 93 |
"jdbc:impala://clustername:21050/default|", |
| 94 |
"Generic Hive 2|org.apache.hive.jdbc.HiveDriver|" + |
| 95 |
"jdbc:hive2://clustername:10000/default|", |
| 96 |
"Generic Hive|org.apache.hadoop.hive.jdbc.HiveDriver|" + |
| 97 |
"jdbc:hive://clustername:10000/default|", |
| 98 |
"Generic Azure SQL|com.microsoft.sqlserver.jdbc.SQLServerDriver|" + |
| 99 |
"jdbc:sqlserver://name.database.windows.net:1433|", |
| 100 |
"Generic Firebird Server|org.firebirdsql.jdbc.FBDriver|" + |
| 101 |
"jdbc:firebirdsql:localhost:c:/temp/firebird/test|sysdba", |
| 102 |
"Generic SQLite|org.sqlite.JDBC|" + |
| 103 |
"jdbc:sqlite:test|sa", |
| 104 |
"Generic DB2|com.ibm.db2.jcc.DB2Driver|" + |
| 105 |
"jdbc:db2://localhost/test|" , |
| 106 |
"Generic Oracle|oracle.jdbc.driver.OracleDriver|" + |
| 107 |
"jdbc:oracle:thin:@localhost:1521:XE|sa" , |
| 108 |
"Generic MS SQL Server 2000|com.microsoft.jdbc.sqlserver.SQLServerDriver|" + |
| 109 |
"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=sqlexpress|sa", |
| 110 |
"Generic MS SQL Server 2005|com.microsoft.sqlserver.jdbc.SQLServerDriver|" + |
| 111 |
"jdbc:sqlserver://localhost;DatabaseName=test|sa", |
| 112 |
"Generic PostgreSQL|org.postgresql.Driver|" + |
| 113 |
"jdbc:postgresql:test|" , |
| 114 |
"Generic MySQL|com.mysql.cj.jdbc.Driver|" + |
| 115 |
"jdbc:mysql://localhost:3306/test|" , |
| 116 |
"Generic MariaDB|org.mariadb.jdbc.Driver|" + |
| 117 |
"jdbc:mariadb://localhost:3306/test|" , |
| 118 |
"Generic HSQLDB|org.hsqldb.jdbcDriver|" + |
| 119 |
"jdbc:hsqldb:test;hsqldb.default_table_type=cached|sa" , |
| 120 |
"Generic Derby (Server)|org.apache.derby.client.ClientAutoloadedDriver|" + |
| 121 |
"jdbc:derby://localhost:1527/test;create=true|sa", |
| 122 |
"Generic Derby (Embedded)|org.apache.derby.iapi.jdbc.AutoloadedDriver|" + |
| 123 |
"jdbc:derby:test;create=true|sa", |
| 124 |
"Generic H2 (Server)|org.h2.Driver|" + |
| 125 |
"jdbc:h2:tcp://localhost/~/test|sa", |
| 126 |
// this will be listed on top for new installations |
| 127 |
"Generic H2 (Embedded)|org.h2.Driver|" + |
| 128 |
"jdbc:h2:~/test|sa", |
| 129 |
}; |
| 130 |
|
| 131 |
private static int ticker; |
| 132 |
|
| 133 |
/** |
| 134 |
* The session timeout (the default is 30 minutes). |
| 135 |
*/ |
| 136 |
private static final long SESSION_TIMEOUT = SysProperties.CONSOLE_TIMEOUT; |
| 137 |
|
| 138 |
// public static void main(String... args) throws IOException { |
| 139 |
// String s = IOUtils.readStringAndClose(new java.io.FileReader( |
| 140 |
// // "src/main/org/h2/server/web/res/_text_cs.prop"), -1); |
| 141 |
// "src/main/org/h2/res/_messages_cs.prop"), -1); |
| 142 |
// System.out.println(StringUtils.javaEncode("...")); |
| 143 |
// String[] list = Locale.getISOLanguages(); |
| 144 |
// for (int i = 0; i < list.length; i++) { |
| 145 |
// System.out.print(list[i] + " "); |
| 146 |
// } |
| 147 |
// System.out.println(); |
| 148 |
// String l = "de"; |
| 149 |
// String lang = new java.util.Locale(l). |
| 150 |
// getDisplayLanguage(new java.util.Locale(l)); |
| 151 |
// System.out.println(new java.util.Locale(l).getDisplayLanguage()); |
| 152 |
// System.out.println(lang); |
| 153 |
// java.util.Locale.CHINESE.getDisplayLanguage(java.util.Locale.CHINESE); |
| 154 |
// for (int i = 0; i < lang.length(); i++) { |
| 155 |
// System.out.println(Integer.toHexString(lang.charAt(i)) + " "); |
| 156 |
// } |
| 157 |
// } |
| 158 |
|
| 159 |
// private URLClassLoader urlClassLoader; |
| 160 |
private int port; |
| 161 |
private boolean allowOthers; |
| 162 |
private String externalNames; |
| 163 |
private boolean isDaemon; |
| 164 |
private final Set<WebThread> running = |
| 165 |
Collections.synchronizedSet(new HashSet<>()); |
| 166 |
private boolean ssl; |
| 167 |
private byte[] adminPassword; |
| 168 |
private final HashMap<String, ConnectionInfo> connInfoMap = new HashMap<>(); |
| 169 |
|
| 170 |
private long lastTimeoutCheck; |
| 171 |
private final HashMap<String, WebSession> sessions = new HashMap<>(); |
| 172 |
private final HashSet<String> languages = new HashSet<>(); |
| 173 |
private String startDateTime; |
| 174 |
private ServerSocket serverSocket; |
| 175 |
private String host; |
| 176 |
private String url; |
| 177 |
private ShutdownHandler shutdownHandler; |
| 178 |
private Thread listenerThread; |
| 179 |
private boolean ifExists = true; |
| 180 |
private String key; |
| 181 |
private boolean allowSecureCreation; |
| 182 |
private boolean trace; |
| 183 |
private TranslateThread translateThread; |
| 184 |
private boolean allowChunked = true; |
| 185 |
private String serverPropertiesDir = Constants.SERVER_PROPERTIES_DIR; |
| 186 |
// null means the history is not allowed to be stored |
| 187 |
private String commandHistoryString; |
| 188 |
|
| 189 |
/** |
| 190 |
* Read the given file from the file system or from the resources. |
| 191 |
* |
| 192 |
* @param file the file name |
| 193 |
* @return the data |
| 194 |
* @throws IOException on failure |
| 195 |
*/ |
| 196 |
byte[] getFile(String file) throws IOException { |
| 197 |
trace("getFile <" + file + ">"); |
| 198 |
byte[] data = Utils.getResource("/org/h2/server/web/res/" + file); |
| 199 |
if (data == null) { |
| 200 |
trace(" null"); |
| 201 |
} else { |
| 202 |
trace(" size=" + data.length); |
| 203 |
} |
| 204 |
return data; |
| 205 |
} |
| 206 |
|
| 207 |
/** |
| 208 |
* Remove this web thread from the set of running threads. |
| 209 |
* |
| 210 |
* @param t the thread to remove |
| 211 |
*/ |
| 212 |
synchronized void remove(WebThread t) { |
| 213 |
running.remove(t); |
| 214 |
} |
| 215 |
|
| 216 |
private static String generateSessionId() { |
| 217 |
byte[] buff = MathUtils.secureRandomBytes(16); |
| 218 |
return StringUtils.convertBytesToHex(buff); |
| 219 |
} |
| 220 |
|
| 221 |
/** |
| 222 |
* Get the web session object for the given session id. |
| 223 |
* |
| 224 |
* @param sessionId the session id |
| 225 |
* @return the web session or null |
| 226 |
*/ |
| 227 |
WebSession getSession(String sessionId) { |
| 228 |
long now = System.currentTimeMillis(); |
| 229 |
if (lastTimeoutCheck + SESSION_TIMEOUT < now) { |
| 230 |
for (String id : new ArrayList<>(sessions.keySet())) { |
| 231 |
WebSession session = sessions.get(id); |
| 232 |
if (session.lastAccess + SESSION_TIMEOUT < now) { |
| 233 |
trace("timeout for " + id); |
| 234 |
sessions.remove(id); |
| 235 |
} |
| 236 |
} |
| 237 |
lastTimeoutCheck = now; |
| 238 |
} |
| 239 |
WebSession session = sessions.get(sessionId); |
| 240 |
if (session != null) { |
| 241 |
session.lastAccess = System.currentTimeMillis(); |
| 242 |
} |
| 243 |
return session; |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* Create a new web session id and object. |
| 248 |
* |
| 249 |
* @param hostAddr the host address |
| 250 |
* @return the web session object |
| 251 |
*/ |
| 252 |
WebSession createNewSession(String hostAddr) { |
| 253 |
String newId; |
| 254 |
do { |
| 255 |
newId = generateSessionId(); |
| 256 |
} while (sessions.get(newId) != null); |
| 257 |
WebSession session = new WebSession(this); |
| 258 |
session.lastAccess = System.currentTimeMillis(); |
| 259 |
session.put("sessionId", newId); |
| 260 |
session.put("ip", hostAddr); |
| 261 |
session.put("language", DEFAULT_LANGUAGE); |
| 262 |
session.put("frame-border", "0"); |
| 263 |
session.put("frameset-border", "4"); |
| 264 |
sessions.put(newId, session); |
| 265 |
// always read the english translation, |
| 266 |
// so that untranslated text appears at least in english |
| 267 |
readTranslations(session, DEFAULT_LANGUAGE); |
| 268 |
return getSession(newId); |
| 269 |
} |
| 270 |
|
| 271 |
String getStartDateTime() { |
| 272 |
if (startDateTime == null) { |
| 273 |
startDateTime = DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH) |
| 274 |
.format(ZonedDateTime.now(ZoneId.of("UTC"))); |
| 275 |
} |
| 276 |
return startDateTime; |
| 277 |
} |
| 278 |
|
| 279 |
/** |
| 280 |
* Returns the key for privileged connections. |
| 281 |
* |
| 282 |
* @return key key, or null |
| 283 |
*/ |
| 284 |
String getKey() { |
| 285 |
return key; |
| 286 |
} |
| 287 |
|
| 288 |
/** |
| 289 |
* Sets the key for privileged connections. |
| 290 |
* |
| 291 |
* @param key key, or null |
| 292 |
*/ |
| 293 |
public void setKey(String key) { |
| 294 |
if (!allowOthers) { |
| 295 |
this.key = key; |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
/** |
| 300 |
* @param allowSecureCreation |
| 301 |
* whether creation of databases using the key should be allowed |
| 302 |
*/ |
| 303 |
public void setAllowSecureCreation(boolean allowSecureCreation) { |
| 304 |
if (!allowOthers) { |
| 305 |
this.allowSecureCreation = allowSecureCreation; |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
@Override |
| 310 |
public void init(String... args) { |
| 311 |
// set the serverPropertiesDir, because it's used in loadProperties() |
| 312 |
for (int i = 0; args != null && i < args.length; i++) { |
| 313 |
if ("-properties".equals(args[i])) { |
| 314 |
serverPropertiesDir = args[++i]; |
| 315 |
} |
| 316 |
} |
| 317 |
Properties prop = loadProperties(); |
| 318 |
port = SortedProperties.getIntProperty(prop, |
| 319 |
"webPort", Constants.DEFAULT_HTTP_PORT); |
| 320 |
ssl = SortedProperties.getBooleanProperty(prop, |
| 321 |
"webSSL", false); |
| 322 |
allowOthers = SortedProperties.getBooleanProperty(prop, |
| 323 |
"webAllowOthers", false); |
| 324 |
setExternalNames(SortedProperties.getStringProperty(prop, "webExternalNames", null)); |
| 325 |
setAdminPassword(SortedProperties.getStringProperty(prop, "webAdminPassword", null)); |
| 326 |
commandHistoryString = prop.getProperty(COMMAND_HISTORY); |
| 327 |
for (int i = 0; args != null && i < args.length; i++) { |
| 328 |
String a = args[i]; |
| 329 |
if (Tool.isOption(a, "-webPort")) { |
| 330 |
port = Integer.decode(args[++i]); |
| 331 |
} else if (Tool.isOption(a, "-webSSL")) { |
| 332 |
ssl = true; |
| 333 |
} else if (Tool.isOption(a, "-webAllowOthers")) { |
| 334 |
allowOthers = true; |
| 335 |
} else if (Tool.isOption(a, "-webExternalNames")) { |
| 336 |
setExternalNames(args[++i]); |
| 337 |
} else if (Tool.isOption(a, "-webDaemon")) { |
| 338 |
isDaemon = true; |
| 339 |
} else if (Tool.isOption(a, "-baseDir")) { |
| 340 |
String baseDir = args[++i]; |
| 341 |
SysProperties.setBaseDir(baseDir); |
| 342 |
} else if (Tool.isOption(a, "-ifExists")) { |
| 343 |
ifExists = true; |
| 344 |
} else if (Tool.isOption(a, "-ifNotExists")) { |
| 345 |
ifExists = false; |
| 346 |
} else if (Tool.isOption(a, "-webAdminPassword")) { |
| 347 |
setAdminPassword(args[++i]); |
| 348 |
} else if (Tool.isOption(a, "-properties")) { |
| 349 |
// already set |
| 350 |
i++; |
| 351 |
} else if (Tool.isOption(a, "-trace")) { |
| 352 |
trace = true; |
| 353 |
} |
| 354 |
} |
| 355 |
// if (driverList != null) { |
| 356 |
// try { |
| 357 |
// String[] drivers = |
| 358 |
// StringUtils.arraySplit(driverList, ',', false); |
| 359 |
// URL[] urls = new URL[drivers.length]; |
| 360 |
// for(int i=0; i<drivers.length; i++) { |
| 361 |
// urls[i] = new URL(drivers[i]); |
| 362 |
// } |
| 363 |
// urlClassLoader = URLClassLoader.newInstance(urls); |
| 364 |
// } catch (MalformedURLException e) { |
| 365 |
// TraceSystem.traceThrowable(e); |
| 366 |
// } |
| 367 |
// } |
| 368 |
for (String[] lang : LANGUAGES) { |
| 369 |
languages.add(lang[0]); |
| 370 |
} |
| 371 |
if (allowOthers) { |
| 372 |
key = null; |
| 373 |
} |
| 374 |
updateURL(); |
| 375 |
} |
| 376 |
|
| 377 |
@Override |
| 378 |
public String getURL() { |
| 379 |
updateURL(); |
| 380 |
return url; |
| 381 |
} |
| 382 |
|
| 383 |
/** |
| 384 |
* @return host name |
| 385 |
*/ |
| 386 |
public String getHost() { |
| 387 |
if (host == null) { |
| 388 |
updateURL(); |
| 389 |
} |
| 390 |
return host; |
| 391 |
} |
| 392 |
|
| 393 |
private void updateURL() { |
| 394 |
try { |
| 395 |
host = StringUtils.toLowerEnglish(NetUtils.getLocalAddress()); |
| 396 |
StringBuilder builder = new StringBuilder(ssl ? "https" : "http").append("://") |
| 397 |
.append(host).append(':').append(port); |
| 398 |
if (key != null && serverSocket != null) { |
| 399 |
builder.append("?key=").append(key); |
| 400 |
} |
| 401 |
url = builder.toString(); |
| 402 |
} catch (NoClassDefFoundError e) { |
| 403 |
// Google App Engine does not allow java.net.InetAddress |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
@Override |
| 408 |
public void start() { |
| 409 |
serverSocket = NetUtils.createServerSocket(port, ssl); |
| 410 |
port = serverSocket.getLocalPort(); |
| 411 |
updateURL(); |
| 412 |
} |
| 413 |
|
| 414 |
@Override |
| 415 |
public void listen() { |
| 416 |
this.listenerThread = Thread.currentThread(); |
| 417 |
try { |
| 418 |
while (serverSocket != null) { |
| 419 |
Socket s = serverSocket.accept(); |
| 420 |
WebThread c = new WebThread(s, this); |
| 421 |
running.add(c); |
| 422 |
c.start(); |
| 423 |
} |
| 424 |
} catch (Exception e) { |
| 425 |
trace(e.toString()); |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
@Override |
| 430 |
public boolean isRunning(boolean traceError) { |
| 431 |
if (serverSocket == null) { |
| 432 |
return false; |
| 433 |
} |
| 434 |
try { |
| 435 |
Socket s = NetUtils.createLoopbackSocket(port, ssl); |
| 436 |
s.close(); |
| 437 |
return true; |
| 438 |
} catch (Exception e) { |
| 439 |
if (traceError) { |
| 440 |
traceError(e); |
| 441 |
} |
| 442 |
return false; |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
public boolean isStopped() { |
| 447 |
return serverSocket == null; |
| 448 |
} |
| 449 |
|
| 450 |
@Override |
| 451 |
public void stop() { |
| 452 |
if (serverSocket != null) { |
| 453 |
try { |
| 454 |
serverSocket.close(); |
| 455 |
} catch (IOException e) { |
| 456 |
traceError(e); |
| 457 |
} |
| 458 |
serverSocket = null; |
| 459 |
} |
| 460 |
if (listenerThread != null) { |
| 461 |
try { |
| 462 |
listenerThread.join(1000); |
| 463 |
} catch (InterruptedException e) { |
| 464 |
DbException.traceThrowable(e); |
| 465 |
} |
| 466 |
} |
| 467 |
// TODO server: using a boolean 'now' argument? a timeout? |
| 468 |
for (WebSession session : new ArrayList<>(sessions.values())) { |
| 469 |
session.close(); |
| 470 |
} |
| 471 |
for (WebThread c : new ArrayList<>(running)) { |
| 472 |
try { |
| 473 |
c.stopNow(); |
| 474 |
c.join(100); |
| 475 |
} catch (Exception e) { |
| 476 |
traceError(e); |
| 477 |
} |
| 478 |
} |
| 479 |
} |
| 480 |
|
| 481 |
/** |
| 482 |
* Write trace information if trace is enabled. |
| 483 |
* |
| 484 |
* @param s the message to write |
| 485 |
*/ |
| 486 |
void trace(String s) { |
| 487 |
if (trace) { |
| 488 |
System.out.println(s); |
| 489 |
} |
| 490 |
} |
| 491 |
|
| 492 |
/** |
| 493 |
* Write the stack trace if trace is enabled. |
| 494 |
* |
| 495 |
* @param e the exception |
| 496 |
*/ |
| 497 |
void traceError(Throwable e) { |
| 498 |
if (trace) { |
| 499 |
e.printStackTrace(); |
| 500 |
} |
| 501 |
} |
| 502 |
|
| 503 |
/** |
| 504 |
* Check if this language is supported / translated. |
| 505 |
* |
| 506 |
* @param language the language |
| 507 |
* @return true if a translation is available |
| 508 |
*/ |
| 509 |
boolean supportsLanguage(String language) { |
| 510 |
return languages.contains(language); |
| 511 |
} |
| 512 |
|
| 513 |
/** |
| 514 |
* Read the translation for this language and save them in the 'text' |
| 515 |
* property of this session. |
| 516 |
* |
| 517 |
* @param session the session |
| 518 |
* @param language the language |
| 519 |
*/ |
| 520 |
void readTranslations(WebSession session, String language) { |
| 521 |
Properties text = new Properties(); |
| 522 |
try { |
| 523 |
trace("translation: "+language); |
| 524 |
byte[] trans = getFile("_text_"+language+".prop"); |
| 525 |
String s = new String(trans, StandardCharsets.UTF_8); |
| 526 |
trace(" " + s); |
| 527 |
text = SortedProperties.fromLines(s); |
| 528 |
// remove starting # (if not translated yet) |
| 529 |
for (Entry<Object, Object> entry : text.entrySet()) { |
| 530 |
String value = (String) entry.getValue(); |
| 531 |
if (value.startsWith("#")) { |
| 532 |
entry.setValue(value.substring(1)); |
| 533 |
} |
| 534 |
} |
| 535 |
} catch (IOException e) { |
| 536 |
DbException.traceThrowable(e); |
| 537 |
} |
| 538 |
session.put("text", new HashMap<>(text)); |
| 539 |
} |
| 540 |
|
| 541 |
ArrayList<HashMap<String, Object>> getSessions() { |
| 542 |
ArrayList<HashMap<String, Object>> list = new ArrayList<>(sessions.size()); |
| 543 |
for (WebSession s : sessions.values()) { |
| 544 |
list.add(s.getInfo()); |
| 545 |
} |
| 546 |
return list; |
| 547 |
} |
| 548 |
|
| 549 |
@Override |
| 550 |
public String getType() { |
| 551 |
return "Web Console"; |
| 552 |
} |
| 553 |
|
| 554 |
@Override |
| 555 |
public String getName() { |
| 556 |
return "H2 Console Server"; |
| 557 |
} |
| 558 |
|
| 559 |
void setAllowOthers(boolean b) { |
| 560 |
if (b) { |
| 561 |
key = null; |
| 562 |
} |
| 563 |
allowOthers = b; |
| 564 |
} |
| 565 |
|
| 566 |
@Override |
| 567 |
public boolean getAllowOthers() { |
| 568 |
return allowOthers; |
| 569 |
} |
| 570 |
|
| 571 |
void setExternalNames(String externalNames) { |
| 572 |
this.externalNames = externalNames != null ? StringUtils.toLowerEnglish(externalNames) : null; |
| 573 |
} |
| 574 |
|
| 575 |
String getExternalNames() { |
| 576 |
return externalNames; |
| 577 |
} |
| 578 |
|
| 579 |
void setSSL(boolean b) { |
| 580 |
ssl = b; |
| 581 |
} |
| 582 |
|
| 583 |
void setPort(int port) { |
| 584 |
this.port = port; |
| 585 |
} |
| 586 |
|
| 587 |
boolean getSSL() { |
| 588 |
return ssl; |
| 589 |
} |
| 590 |
|
| 591 |
@Override |
| 592 |
public int getPort() { |
| 593 |
return port; |
| 594 |
} |
| 595 |
|
| 596 |
public boolean isCommandHistoryAllowed() { |
| 597 |
return commandHistoryString != null; |
| 598 |
} |
| 599 |
|
| 600 |
public void setCommandHistoryAllowed(boolean allowed) { |
| 601 |
if (allowed) { |
| 602 |
if (commandHistoryString == null) { |
| 603 |
commandHistoryString = ""; |
| 604 |
} |
| 605 |
} else { |
| 606 |
commandHistoryString = null; |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
public ArrayList<String> getCommandHistoryList() { |
| 611 |
ArrayList<String> result = new ArrayList<>(); |
| 612 |
if (commandHistoryString == null) { |
| 613 |
return result; |
| 614 |
} |
| 615 |
|
| 616 |
// Split the commandHistoryString on non-escaped semicolons |
| 617 |
// and unescape it. |
| 618 |
StringBuilder sb = new StringBuilder(); |
| 619 |
for (int end = 0;; end++) { |
| 620 |
if (end == commandHistoryString.length() || |
| 621 |
commandHistoryString.charAt(end) == ';') { |
| 622 |
if (sb.length() > 0) { |
| 623 |
result.add(sb.toString()); |
| 624 |
sb.delete(0, sb.length()); |
| 625 |
} |
| 626 |
if (end == commandHistoryString.length()) { |
| 627 |
break; |
| 628 |
} |
| 629 |
} else if (commandHistoryString.charAt(end) == '\\' && |
| 630 |
end < commandHistoryString.length() - 1) { |
| 631 |
sb.append(commandHistoryString.charAt(++end)); |
| 632 |
} else { |
| 633 |
sb.append(commandHistoryString.charAt(end)); |
| 634 |
} |
| 635 |
} |
| 636 |
return result; |
| 637 |
} |
| 638 |
|
| 639 |
/** |
| 640 |
* Save the command history to the properties file. |
| 641 |
* |
| 642 |
* @param commandHistory the history |
| 643 |
*/ |
| 644 |
public void saveCommandHistoryList(ArrayList<String> commandHistory) { |
| 645 |
StringBuilder sb = new StringBuilder(); |
| 646 |
for (String s : commandHistory) { |
| 647 |
if (sb.length() > 0) { |
| 648 |
sb.append(';'); |
| 649 |
} |
| 650 |
sb.append(s.replace("\\", "\\\\").replace(";", "\\;")); |
| 651 |
} |
| 652 |
commandHistoryString = sb.toString(); |
| 653 |
saveProperties(null); |
| 654 |
} |
| 655 |
|
| 656 |
/** |
| 657 |
* Get the connection information for this setting. |
| 658 |
* |
| 659 |
* @param name the setting name |
| 660 |
* @return the connection information |
| 661 |
*/ |
| 662 |
ConnectionInfo getSetting(String name) { |
| 663 |
return connInfoMap.get(name); |
| 664 |
} |
| 665 |
|
| 666 |
/** |
| 667 |
* Update a connection information setting. |
| 668 |
* |
| 669 |
* @param info the connection information |
| 670 |
*/ |
| 671 |
void updateSetting(ConnectionInfo info) { |
| 672 |
connInfoMap.put(info.name, info); |
| 673 |
info.lastAccess = ticker++; |
| 674 |
} |
| 675 |
|
| 676 |
/** |
| 677 |
* Remove a connection information setting from the list |
| 678 |
* |
| 679 |
* @param name the setting to remove |
| 680 |
*/ |
| 681 |
void removeSetting(String name) { |
| 682 |
connInfoMap.remove(name); |
| 683 |
} |
| 684 |
|
| 685 |
private Properties loadProperties() { |
| 686 |
try { |
| 687 |
if ("null".equals(serverPropertiesDir)) { |
| 688 |
return new Properties(); |
| 689 |
} |
| 690 |
return SortedProperties.loadProperties( |
| 691 |
serverPropertiesDir + "/" + Constants.SERVER_PROPERTIES_NAME); |
| 692 |
} catch (Exception e) { |
| 693 |
DbException.traceThrowable(e); |
| 694 |
return new Properties(); |
| 695 |
} |
| 696 |
} |
| 697 |
|
| 698 |
/** |
| 699 |
* Get the list of connection information setting names. |
| 700 |
* |
| 701 |
* @return the connection info names |
| 702 |
*/ |
| 703 |
String[] getSettingNames() { |
| 704 |
ArrayList<ConnectionInfo> list = getSettings(); |
| 705 |
String[] names = new String[list.size()]; |
| 706 |
for (int i = 0; i < list.size(); i++) { |
| 707 |
names[i] = list.get(i).name; |
| 708 |
} |
| 709 |
return names; |
| 710 |
} |
| 711 |
|
| 712 |
/** |
| 713 |
* Get the list of connection info objects. |
| 714 |
* |
| 715 |
* @return the list |
| 716 |
*/ |
| 717 |
synchronized ArrayList<ConnectionInfo> getSettings() { |
| 718 |
ArrayList<ConnectionInfo> settings = new ArrayList<>(); |
| 719 |
if (connInfoMap.size() == 0) { |
| 720 |
Properties prop = loadProperties(); |
| 721 |
if (prop.size() == 0) { |
| 722 |
for (String gen : GENERIC) { |
| 723 |
ConnectionInfo info = new ConnectionInfo(gen); |
| 724 |
settings.add(info); |
| 725 |
updateSetting(info); |
| 726 |
} |
| 727 |
} else { |
| 728 |
for (int i = 0;; i++) { |
| 729 |
String data = prop.getProperty(Integer.toString(i)); |
| 730 |
if (data == null) { |
| 731 |
break; |
| 732 |
} |
| 733 |
ConnectionInfo info = new ConnectionInfo(data); |
| 734 |
settings.add(info); |
| 735 |
updateSetting(info); |
| 736 |
} |
| 737 |
} |
| 738 |
} else { |
| 739 |
settings.addAll(connInfoMap.values()); |
| 740 |
} |
| 741 |
Collections.sort(settings); |
| 742 |
return settings; |
| 743 |
} |
| 744 |
|
| 745 |
/** |
| 746 |
* Save the settings to the properties file. |
| 747 |
* |
| 748 |
* @param prop null or the properties webPort, webAllowOthers, and webSSL |
| 749 |
*/ |
| 750 |
synchronized void saveProperties(Properties prop) { |
| 751 |
try { |
| 752 |
if (prop == null) { |
| 753 |
Properties old = loadProperties(); |
| 754 |
prop = new SortedProperties(); |
| 755 |
prop.setProperty("webPort", |
| 756 |
Integer.toString(SortedProperties.getIntProperty(old, "webPort", port))); |
| 757 |
prop.setProperty("webAllowOthers", |
| 758 |
Boolean.toString(SortedProperties.getBooleanProperty(old, "webAllowOthers", allowOthers))); |
| 759 |
if (externalNames != null) { |
| 760 |
prop.setProperty("webExternalNames", externalNames); |
| 761 |
} |
| 762 |
prop.setProperty("webSSL", |
| 763 |
Boolean.toString(SortedProperties.getBooleanProperty(old, "webSSL", ssl))); |
| 764 |
if (adminPassword != null) { |
| 765 |
prop.setProperty("webAdminPassword", StringUtils.convertBytesToHex(adminPassword)); |
| 766 |
} |
| 767 |
if (commandHistoryString != null) { |
| 768 |
prop.setProperty(COMMAND_HISTORY, commandHistoryString); |
| 769 |
} |
| 770 |
} |
| 771 |
ArrayList<ConnectionInfo> settings = getSettings(); |
| 772 |
int len = settings.size(); |
| 773 |
for (int i = 0; i < len; i++) { |
| 774 |
ConnectionInfo info = settings.get(i); |
| 775 |
if (info != null) { |
| 776 |
prop.setProperty(Integer.toString(len - i - 1), info.getString()); |
| 777 |
} |
| 778 |
} |
| 779 |
if (!"null".equals(serverPropertiesDir)) { |
| 780 |
OutputStream out = FileUtils.newOutputStream( |
| 781 |
serverPropertiesDir + "/" + Constants.SERVER_PROPERTIES_NAME, false); |
| 782 |
prop.store(out, "H2 Server Properties"); |
| 783 |
out.close(); |
| 784 |
} |
| 785 |
} catch (Exception e) { |
| 786 |
DbException.traceThrowable(e); |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
/** |
| 791 |
* Open a database connection. |
| 792 |
* |
| 793 |
* @param driver the driver class name |
| 794 |
* @param databaseUrl the database URL |
| 795 |
* @param user the user name |
| 796 |
* @param password the password |
| 797 |
* @param userKey the key of privileged user |
| 798 |
* @param networkConnectionInfo the network connection information |
| 799 |
* @return the database connection |
| 800 |
* @throws SQLException on failure |
| 801 |
*/ |
| 802 |
Connection getConnection(String driver, String databaseUrl, String user, |
| 803 |
String password, String userKey, NetworkConnectionInfo networkConnectionInfo) throws SQLException { |
| 804 |
driver = driver.trim(); |
| 805 |
databaseUrl = databaseUrl.trim(); |
| 806 |
// do not trim the password, otherwise an |
| 807 |
// encrypted H2 database with empty user password doesn't work |
| 808 |
return JdbcUtils.getConnection(driver, databaseUrl, user.trim(), password, networkConnectionInfo, |
| 809 |
ifExists && (!allowSecureCreation || key == null || !key.equals(userKey))); |
| 810 |
} |
| 811 |
|
| 812 |
/** |
| 813 |
* Shut down the web server. |
| 814 |
*/ |
| 815 |
void shutdown() { |
| 816 |
if (shutdownHandler != null) { |
| 817 |
shutdownHandler.shutdown(); |
| 818 |
} |
| 819 |
} |
| 820 |
|
| 821 |
public void setShutdownHandler(ShutdownHandler shutdownHandler) { |
| 822 |
this.shutdownHandler = shutdownHandler; |
| 823 |
} |
| 824 |
|
| 825 |
/** |
| 826 |
* Create a session with a given connection. |
| 827 |
* |
| 828 |
* @param conn the connection |
| 829 |
* @return the URL of the web site to access this connection |
| 830 |
* @throws SQLException on failure |
| 831 |
*/ |
| 832 |
public String addSession(Connection conn) throws SQLException { |
| 833 |
WebSession session = createNewSession("local"); |
| 834 |
session.setShutdownServerOnDisconnect(); |
| 835 |
session.setConnection(conn); |
| 836 |
session.put("url", conn.getMetaData().getURL()); |
| 837 |
String s = (String) session.get("sessionId"); |
| 838 |
return url + "/frame.jsp?jsessionid=" + s; |
| 839 |
} |
| 840 |
|
| 841 |
/** |
| 842 |
* The translate thread reads and writes the file translation.properties |
| 843 |
* once a second. |
| 844 |
*/ |
| 845 |
private class TranslateThread extends Thread { |
| 846 |
|
| 847 |
private final Path file = Paths.get("translation.properties"); |
| 848 |
private final Map<Object, Object> translation; |
| 849 |
private volatile boolean stopNow; |
| 850 |
|
| 851 |
TranslateThread(Map<Object, Object> translation) { |
| 852 |
this.translation = translation; |
| 853 |
} |
| 854 |
|
| 855 |
public String getFileName() { |
| 856 |
return file.toAbsolutePath().toString(); |
| 857 |
} |
| 858 |
|
| 859 |
public void stopNow() { |
| 860 |
this.stopNow = true; |
| 861 |
try { |
| 862 |
join(); |
| 863 |
} catch (InterruptedException e) { |
| 864 |
// ignore |
| 865 |
} |
| 866 |
} |
| 867 |
|
| 868 |
@Override |
| 869 |
public void run() { |
| 870 |
while (!stopNow) { |
| 871 |
try { |
| 872 |
SortedProperties sp = new SortedProperties(); |
| 873 |
if (Files.exists(file)) { |
| 874 |
InputStream in = Files.newInputStream(file); |
| 875 |
sp.load(in); |
| 876 |
translation.putAll(sp); |
| 877 |
} else { |
| 878 |
OutputStream out = Files.newOutputStream(file); |
| 879 |
sp.putAll(translation); |
| 880 |
sp.store(out, "Translation"); |
| 881 |
} |
| 882 |
Thread.sleep(1000); |
| 883 |
} catch (Exception e) { |
| 884 |
traceError(e); |
| 885 |
} |
| 886 |
} |
| 887 |
} |
| 888 |
|
| 889 |
} |
| 890 |
|
| 891 |
/** |
| 892 |
* Start the translation thread that reads the file once a second. |
| 893 |
* |
| 894 |
* @param translation the translation map |
| 895 |
* @return the name of the file to translate |
| 896 |
*/ |
| 897 |
String startTranslate(Map<Object, Object> translation) { |
| 898 |
if (translateThread != null) { |
| 899 |
translateThread.stopNow(); |
| 900 |
} |
| 901 |
translateThread = new TranslateThread(translation); |
| 902 |
translateThread.setDaemon(true); |
| 903 |
translateThread.start(); |
| 904 |
return translateThread.getFileName(); |
| 905 |
} |
| 906 |
|
| 907 |
@Override |
| 908 |
public boolean isDaemon() { |
| 909 |
return isDaemon; |
| 910 |
} |
| 911 |
|
| 912 |
void setAllowChunked(boolean allowChunked) { |
| 913 |
this.allowChunked = allowChunked; |
| 914 |
} |
| 915 |
|
| 916 |
boolean getAllowChunked() { |
| 917 |
return allowChunked; |
| 918 |
} |
| 919 |
|
| 920 |
byte[] getAdminPassword() { |
| 921 |
return adminPassword; |
| 922 |
} |
| 923 |
|
| 924 |
void setAdminPassword(String password) { |
| 925 |
if (password == null || password.isEmpty()) { |
| 926 |
adminPassword = null; |
| 927 |
return; |
| 928 |
} |
| 929 |
if (password.length() != 128) { |
| 930 |
throw new IllegalArgumentException( |
| 931 |
"Use result of org.h2.server.web.WebServer.encodeAdminPassword(String)"); |
| 932 |
} |
| 933 |
adminPassword = StringUtils.convertHexToBytes(password); |
| 934 |
} |
| 935 |
|
| 936 |
/** |
| 937 |
* Generates a random salt and returns it with a hash of specified password |
| 938 |
* with this salt. |
| 939 |
* |
| 940 |
* @param password |
| 941 |
* the password |
| 942 |
* @return a salt and hash of salted password as a hex encoded string to be |
| 943 |
* used in configuration file |
| 944 |
* @throws IllegalArgumentException when password is too short |
| 945 |
*/ |
| 946 |
public static String encodeAdminPassword(String password) { |
| 947 |
if (password.length() < Constants.MIN_WEB_ADMIN_PASSWORD_LENGTH) { |
| 948 |
throw new IllegalArgumentException("Min length: " + Constants.MIN_WEB_ADMIN_PASSWORD_LENGTH); |
| 949 |
} |
| 950 |
byte[] salt = MathUtils.secureRandomBytes(32); |
| 951 |
byte[] hash = SHA256.getHashWithSalt(password.getBytes(StandardCharsets.UTF_8), salt); |
| 952 |
byte[] total = Arrays.copyOf(salt, 64); |
| 953 |
System.arraycopy(hash, 0, total, 32, 32); |
| 954 |
return StringUtils.convertBytesToHex(total); |
| 955 |
} |
| 956 |
|
| 957 |
/** |
| 958 |
* Check the admin password. |
| 959 |
* |
| 960 |
* @param password the password to test |
| 961 |
* @return true if admin password not configure, or admin password correct |
| 962 |
*/ |
| 963 |
boolean checkAdminPassword(String password) { |
| 964 |
if (adminPassword == null) { |
| 965 |
return false; |
| 966 |
} |
| 967 |
byte[] salt = Arrays.copyOf(adminPassword, 32); |
| 968 |
byte[] hash = new byte[32]; |
| 969 |
System.arraycopy(adminPassword, 32, hash, 0, 32); |
| 970 |
return Utils.compareSecure(hash, SHA256.getHashWithSalt(password.getBytes(StandardCharsets.UTF_8), salt)); |
| 971 |
} |
| 972 |
|
| 973 |
} |