Debian Codegraph @

src/main/org/h2/server/TcpServer.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.server;
7
8 import java.io.IOException;
9 import java.net.ServerSocket;
10 import java.net.Socket;
11 import java.net.UnknownHostException;
12 import java.sql.PreparedStatement;
13 import java.sql.SQLException;
14 import java.sql.Statement;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.HashSet;
18 import java.util.Set;
19 import java.util.concurrent.ConcurrentHashMap;
20
21 import org.h2.api.ErrorCode;
22 import org.h2.engine.Constants;
23 import org.h2.jdbc.JdbcConnection;
24 import org.h2.message.DbException;
25 import org.h2.util.MathUtils;
26 import org.h2.util.NetUtils;
27 import org.h2.util.StringUtils;
28 import org.h2.util.Tool;
29 import org.h2.util.Utils10;
30
31 /**
32 * The TCP server implements the native H2 database server protocol.
33 * It supports multiple client connections to multiple databases
34 * (many to many). The same database may be opened by multiple clients.
35 * Also supported is the mixed mode: opening databases in embedded mode,
36 * and at the same time start a TCP server to allow clients to connect to
37 * the same database over the network.
38 */
39 public class TcpServer implements Service {
40
41 private static final int SHUTDOWN_NORMAL = 0;
42 private static final int SHUTDOWN_FORCE = 1;
43
44 /**
45 * The name of the in-memory management database used by the TCP server
46 * to keep the active sessions.
47 */
48 private static final String MANAGEMENT_DB_PREFIX = "management_db_";
49
50 private static final ConcurrentHashMap<Integer, TcpServer> SERVERS = new ConcurrentHashMap<>();
51
52 private int port;
53 private boolean portIsSet;
54 private boolean trace;
55 private boolean ssl;
56 private boolean stop;
57 private ShutdownHandler shutdownHandler;
58 private ServerSocket serverSocket;
59 private final Set<TcpServerThread> running =
60 Collections.synchronizedSet(new HashSet<TcpServerThread>());
61 private String baseDir;
62 private boolean allowOthers;
63 private boolean isDaemon;
64 private boolean ifExists = true;
65 private JdbcConnection managementDb;
66 private PreparedStatement managementDbAdd;
67 private PreparedStatement managementDbRemove;
68 private String managementPassword = "";
69 private Thread listenerThread;
70 private int nextThreadId;
71 private String key, keyDatabase;
72
73 /**
74 * Get the database name of the management database.
75 * The management database contains a table with active sessions (SESSIONS).
76 *
77 * @param port the TCP server port
78 * @return the database name (usually starting with mem:)
79 */
80 public static String getManagementDbName(int port) {
81 return "mem:" + MANAGEMENT_DB_PREFIX + port;
82 }
83
84 private void initManagementDb() throws SQLException {
85 if (managementPassword.isEmpty()) {
86 managementPassword = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32));
87 }
88 // avoid using the driver manager
89 JdbcConnection conn = new JdbcConnection("jdbc:h2:" + getManagementDbName(port), null, "", managementPassword,
90 false);
91 managementDb = conn;
92
93 try (Statement stat = conn.createStatement()) {
94 stat.execute("CREATE ALIAS IF NOT EXISTS STOP_SERVER FOR '" + TcpServer.class.getName() + ".stopServer'");
95 stat.execute("CREATE TABLE IF NOT EXISTS SESSIONS" +
96 "(ID INT PRIMARY KEY, URL VARCHAR, `USER` VARCHAR, " +
97 "CONNECTED TIMESTAMP(9) WITH TIME ZONE)");
98 managementDbAdd = conn.prepareStatement(
99 "INSERT INTO SESSIONS VALUES(?, ?, ?, CURRENT_TIMESTAMP(9))");
100 managementDbRemove = conn.prepareStatement(
101 "DELETE FROM SESSIONS WHERE ID=?");
102 }
103 SERVERS.put(port, this);
104 }
105
106 /**
107 * Shut down this server.
108 */
109 void shutdown() {
110 if (shutdownHandler != null) {
111 shutdownHandler.shutdown();
112 }
113 }
114
115 public void setShutdownHandler(ShutdownHandler shutdownHandler) {
116 this.shutdownHandler = shutdownHandler;
117 }
118
119 /**
120 * Add a connection to the management database.
121 *
122 * @param id the connection id
123 * @param url the database URL
124 * @param user the user name
125 */
126 synchronized void addConnection(int id, String url, String user) {
127 try {
128 managementDbAdd.setInt(1, id);
129 managementDbAdd.setString(2, url);
130 managementDbAdd.setString(3, user);
131 managementDbAdd.execute();
132 } catch (SQLException e) {
133 DbException.traceThrowable(e);
134 }
135 }
136
137 /**
138 * Remove a connection from the management database.
139 *
140 * @param id the connection id
141 */
142 synchronized void removeConnection(int id) {
143 try {
144 managementDbRemove.setInt(1, id);
145 managementDbRemove.execute();
146 } catch (SQLException e) {
147 DbException.traceThrowable(e);
148 }
149 }
150
151 private synchronized void stopManagementDb() {
152 if (managementDb != null) {
153 try {
154 managementDb.close();
155 } catch (SQLException e) {
156 DbException.traceThrowable(e);
157 }
158 managementDb = null;
159 }
160 }
161
162 @Override
163 public void init(String... args) {
164 port = Constants.DEFAULT_TCP_PORT;
165 for (int i = 0; args != null && i < args.length; i++) {
166 String a = args[i];
167 if (Tool.isOption(a, "-trace")) {
168 trace = true;
169 } else if (Tool.isOption(a, "-tcpSSL")) {
170 ssl = true;
171 } else if (Tool.isOption(a, "-tcpPort")) {
172 port = Integer.decode(args[++i]);
173 portIsSet = true;
174 } else if (Tool.isOption(a, "-tcpPassword")) {
175 managementPassword = args[++i];
176 } else if (Tool.isOption(a, "-baseDir")) {
177 baseDir = args[++i];
178 } else if (Tool.isOption(a, "-key")) {
179 key = args[++i];
180 keyDatabase = args[++i];
181 } else if (Tool.isOption(a, "-tcpAllowOthers")) {
182 allowOthers = true;
183 } else if (Tool.isOption(a, "-tcpDaemon")) {
184 isDaemon = true;
185 } else if (Tool.isOption(a, "-ifExists")) {
186 ifExists = true;
187 } else if (Tool.isOption(a, "-ifNotExists")) {
188 ifExists = false;
189 }
190 }
191 }
192
193 @Override
194 public String getURL() {
195 return (ssl ? "ssl" : "tcp") + "://" + NetUtils.getLocalAddress() + ":" + port;
196 }
197
198 @Override
199 public int getPort() {
200 return port;
201 }
202
203 /**
204 * Returns whether a secure protocol is used.
205 *
206 * @return {@code true} if SSL socket is used, {@code false} if plain socket
207 * is used
208 */
209 public boolean getSSL() {
210 return ssl;
211 }
212
213 /**
214 * Check if this socket may connect to this server. Remote connections are
215 * not allowed if the flag allowOthers is set.
216 *
217 * @param socket the socket
218 * @return true if this client may connect
219 */
220 boolean allow(Socket socket) {
221 if (allowOthers) {
222 return true;
223 }
224 try {
225 return NetUtils.isLocalAddress(socket);
226 } catch (UnknownHostException e) {
227 traceError(e);
228 return false;
229 }
230 }
231
232 @Override
233 public synchronized void start() throws SQLException {
234 stop = false;
235 try {
236 serverSocket = NetUtils.createServerSocket(port, ssl);
237 } catch (DbException e) {
238 if (!portIsSet) {
239 serverSocket = NetUtils.createServerSocket(0, ssl);
240 } else {
241 throw e;
242 }
243 }
244 port = serverSocket.getLocalPort();
245 initManagementDb();
246 }
247
248 @Override
249 public void listen() {
250 listenerThread = Thread.currentThread();
251 String threadName = listenerThread.getName();
252 try {
253 while (!stop) {
254 Socket s = serverSocket.accept();
255 Utils10.setTcpQuickack(s, true);
256 int id = nextThreadId++;
257 TcpServerThread c = new TcpServerThread(s, this, id);
258 running.add(c);
259 Thread thread = new Thread(c, threadName + " thread-" + id);
260 thread.setDaemon(isDaemon);
261 c.setThread(thread);
262 thread.start();
263 }
264 serverSocket = NetUtils.closeSilently(serverSocket);
265 } catch (Exception e) {
266 if (!stop) {
267 DbException.traceThrowable(e);
268 }
269 }
270 stopManagementDb();
271 }
272
273 @Override
274 public synchronized boolean isRunning(boolean traceError) {
275 if (serverSocket == null) {
276 return false;
277 }
278 try {
279 Socket s = NetUtils.createLoopbackSocket(port, ssl);
280 s.close();
281 return true;
282 } catch (Exception e) {
283 if (traceError) {
284 traceError(e);
285 }
286 return false;
287 }
288 }
289
290 @Override
291 public void stop() {
292 // TODO server: share code between web and tcp servers
293 // need to remove the server first, otherwise the connection is broken
294 // while the server is still registered in this map
295 SERVERS.remove(port);
296 if (!stop) {
297 stopManagementDb();
298 stop = true;
299 if (serverSocket != null) {
300 try {
301 serverSocket.close();
302 } catch (IOException e) {
303 DbException.traceThrowable(e);
304 } catch (NullPointerException e) {
305 // ignore
306 }
307 serverSocket = null;
308 }
309 if (listenerThread != null) {
310 try {
311 listenerThread.join(1000);
312 } catch (InterruptedException e) {
313 DbException.traceThrowable(e);
314 }
315 }
316 }
317 // TODO server: using a boolean 'now' argument? a timeout?
318 for (TcpServerThread c : new ArrayList<>(running)) {
319 if (c != null) {
320 c.close();
321 try {
322 c.getThread().join(100);
323 } catch (Exception e) {
324 DbException.traceThrowable(e);
325 }
326 }
327 }
328 }
329
330 /**
331 * Stop a running server. This method is called via reflection from the
332 * STOP_SERVER function.
333 *
334 * @param port the port where the server runs, or 0 for all running servers
335 * @param password the password (or null)
336 * @param shutdownMode the shutdown mode, SHUTDOWN_NORMAL or SHUTDOWN_FORCE.
337 */
338 public static void stopServer(int port, String password, int shutdownMode) {
339 if (port == 0) {
340 for (int p : SERVERS.keySet().toArray(new Integer[0])) {
341 if (p != 0) {
342 stopServer(p, password, shutdownMode);
343 }
344 }
345 return;
346 }
347 TcpServer server = SERVERS.get(port);
348 if (server == null) {
349 return;
350 }
351 if (!server.managementPassword.equals(password)) {
352 return;
353 }
354 if (shutdownMode == SHUTDOWN_NORMAL) {
355 server.stopManagementDb();
356 server.stop = true;
357 try {
358 Socket s = NetUtils.createLoopbackSocket(port, false);
359 s.close();
360 } catch (Exception e) {
361 // try to connect - so that accept returns
362 }
363 } else if (shutdownMode == SHUTDOWN_FORCE) {
364 server.stop();
365 }
366 server.shutdown();
367 }
368
369 /**
370 * Remove a thread from the list.
371 *
372 * @param t the thread to remove
373 */
374 void remove(TcpServerThread t) {
375 running.remove(t);
376 }
377
378 /**
379 * Get the configured base directory.
380 *
381 * @return the base directory
382 */
383 String getBaseDir() {
384 return baseDir;
385 }
386
387 /**
388 * Print a message if the trace flag is enabled.
389 *
390 * @param s the message
391 */
392 void trace(String s) {
393 if (trace) {
394 System.out.println(s);
395 }
396 }
397 /**
398 * Print a stack trace if the trace flag is enabled.
399 *
400 * @param e the exception
401 */
402 void traceError(Throwable e) {
403 if (trace) {
404 e.printStackTrace();
405 }
406 }
407
408 @Override
409 public boolean getAllowOthers() {
410 return allowOthers;
411 }
412
413 @Override
414 public String getType() {
415 return "TCP";
416 }
417
418 @Override
419 public String getName() {
420 return "H2 TCP Server";
421 }
422
423 boolean getIfExists() {
424 return ifExists;
425 }
426
427 /**
428 * Stop the TCP server with the given URL.
429 *
430 * @param url the database URL
431 * @param password the password
432 * @param force if the server should be stopped immediately
433 * @param all whether all TCP servers that are running in the JVM should be
434 * stopped
435 * @throws SQLException on failure
436 */
437 public static synchronized void shutdown(String url, String password,
438 boolean force, boolean all) throws SQLException {
439 try {
440 int port = Constants.DEFAULT_TCP_PORT;
441 int idx = url.lastIndexOf(':');
442 if (idx >= 0) {
443 String p = url.substring(idx + 1);
444 if (StringUtils.isNumber(p)) {
445 port = Integer.decode(p);
446 }
447 }
448 String db = getManagementDbName(port);
449 for (int i = 0; i < 2; i++) {
450 try (JdbcConnection conn = new JdbcConnection("jdbc:h2:" + url + '/' + db, null, "", password, true)) {
451 PreparedStatement prep = conn.prepareStatement("CALL STOP_SERVER(?, ?, ?)");
452 prep.setInt(1, all ? 0 : port);
453 prep.setString(2, password);
454 prep.setInt(3, force ? SHUTDOWN_FORCE : SHUTDOWN_NORMAL);
455 try {
456 prep.execute();
457 } catch (SQLException e) {
458 if (force) {
459 // ignore
460 } else {
461 if (e.getErrorCode() != ErrorCode.CONNECTION_BROKEN_1) {
462 throw e;
463 }
464 }
465 }
466 break;
467 } catch (SQLException e) {
468 if (i == 1) {
469 throw e;
470 }
471 }
472 }
473 } catch (Exception e) {
474 throw DbException.toSQLException(e);
475 }
476 }
477
478 /**
479 * Cancel a running statement.
480 *
481 * @param sessionId the session id
482 * @param statementId the statement id
483 */
484 void cancelStatement(String sessionId, int statementId) {
485 for (TcpServerThread c : new ArrayList<>(running)) {
486 if (c != null) {
487 c.cancelStatement(sessionId, statementId);
488 }
489 }
490 }
491
492 /**
493 * If no key is set, return the original database name. If a key is set,
494 * check if the key matches. If yes, return the correct database name. If
495 * not, throw an exception.
496 *
497 * @param db the key to test (or database name if no key is used)
498 * @return the database name
499 * @throws DbException if a key is set but doesn't match
500 */
501 public String checkKeyAndGetDatabaseName(String db) {
502 if (key == null) {
503 return db;
504 }
505 if (key.equals(db)) {
506 return keyDatabase;
507 }
508 throw DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD);
509 }
510
511 @Override
512 public boolean isDaemon() {
513 return isDaemon;
514 }
515
516 }