Debian Codegraph @

src/main/org/h2/server/pg/PgServer.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.pg;
7
8 import java.io.IOException;
9 import java.net.ServerSocket;
10 import java.net.Socket;
11 import java.net.UnknownHostException;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.HashSet;
15 import java.util.Set;
16 import java.util.concurrent.atomic.AtomicInteger;
17 import org.h2.api.ErrorCode;
18 import org.h2.message.DbException;
19 import org.h2.server.Service;
20 import org.h2.util.NetUtils;
21 import org.h2.util.Tool;
22 import org.h2.util.Utils10;
23 import org.h2.value.TypeInfo;
24 import org.h2.value.Value;
25
26 /**
27 * This class implements a subset of the PostgreSQL protocol as described here:
28 * https://www.postgresql.org/docs/devel/protocol.html
29 * The PostgreSQL catalog is described here:
30 * https://www.postgresql.org/docs/7.4/catalogs.html
31 *
32 * @author Thomas Mueller
33 * @author Sergi Vladykin 2009-07-03 (convertType)
34 */
35 public class PgServer implements Service {
36
37 /**
38 * The default port to use for the PG server.
39 * This value is also in the documentation and in the Server javadoc.
40 */
41 public static final int DEFAULT_PORT = 5435;
42
43 /**
44 * The VARCHAR type.
45 */
46 public static final int PG_TYPE_VARCHAR = 1043;
47
48 public static final int PG_TYPE_BOOL = 16;
49 public static final int PG_TYPE_BYTEA = 17;
50 public static final int PG_TYPE_BPCHAR = 1042;
51 public static final int PG_TYPE_INT8 = 20;
52 public static final int PG_TYPE_INT2 = 21;
53 public static final int PG_TYPE_INT4 = 23;
54 public static final int PG_TYPE_TEXT = 25;
55 public static final int PG_TYPE_FLOAT4 = 700;
56 public static final int PG_TYPE_FLOAT8 = 701;
57 public static final int PG_TYPE_UNKNOWN = 705;
58 public static final int PG_TYPE_INT2_ARRAY = 1005;
59 public static final int PG_TYPE_INT4_ARRAY = 1007;
60 public static final int PG_TYPE_VARCHAR_ARRAY = 1015;
61 public static final int PG_TYPE_DATE = 1082;
62 public static final int PG_TYPE_TIME = 1083;
63 public static final int PG_TYPE_TIMETZ = 1266;
64 public static final int PG_TYPE_TIMESTAMP = 1114;
65 public static final int PG_TYPE_TIMESTAMPTZ = 1184;
66 public static final int PG_TYPE_NUMERIC = 1700;
67
68 private final HashSet<Integer> typeSet = new HashSet<>();
69
70 private int port = PgServer.DEFAULT_PORT;
71 private boolean portIsSet;
72 private boolean stop;
73 private boolean trace;
74 private ServerSocket serverSocket;
75 private final Set<PgServerThread> running = Collections.
76 synchronizedSet(new HashSet<PgServerThread>());
77 private final AtomicInteger pid = new AtomicInteger();
78 private String baseDir;
79 private boolean allowOthers;
80 private boolean isDaemon;
81 private boolean ifExists = true;
82 private String key, keyDatabase;
83
84 @Override
85 public void init(String... args) {
86 port = DEFAULT_PORT;
87 for (int i = 0; args != null && i < args.length; i++) {
88 String a = args[i];
89 if (Tool.isOption(a, "-trace")) {
90 trace = true;
91 } else if (Tool.isOption(a, "-pgPort")) {
92 port = Integer.decode(args[++i]);
93 portIsSet = true;
94 } else if (Tool.isOption(a, "-baseDir")) {
95 baseDir = args[++i];
96 } else if (Tool.isOption(a, "-pgAllowOthers")) {
97 allowOthers = true;
98 } else if (Tool.isOption(a, "-pgDaemon")) {
99 isDaemon = true;
100 } else if (Tool.isOption(a, "-ifExists")) {
101 ifExists = true;
102 } else if (Tool.isOption(a, "-ifNotExists")) {
103 ifExists = false;
104 } else if (Tool.isOption(a, "-key")) {
105 key = args[++i];
106 keyDatabase = args[++i];
107 }
108 }
109 // int testing;
110 // trace = true;
111 }
112
113 boolean getTrace() {
114 return trace;
115 }
116
117 /**
118 * Print a message if the trace flag is enabled.
119 *
120 * @param s the message
121 */
122 void trace(String s) {
123 if (trace) {
124 System.out.println(s);
125 }
126 }
127
128 /**
129 * Remove a thread from the list.
130 *
131 * @param t the thread to remove
132 */
133 synchronized void remove(PgServerThread t) {
134 running.remove(t);
135 }
136
137 /**
138 * Print the stack trace if the trace flag is enabled.
139 *
140 * @param e the exception
141 */
142 void traceError(Exception e) {
143 if (trace) {
144 e.printStackTrace();
145 }
146 }
147
148 @Override
149 public String getURL() {
150 return "pg://" + NetUtils.getLocalAddress() + ":" + port;
151 }
152
153 @Override
154 public int getPort() {
155 return port;
156 }
157
158 private boolean allow(Socket socket) {
159 if (allowOthers) {
160 return true;
161 }
162 try {
163 return NetUtils.isLocalAddress(socket);
164 } catch (UnknownHostException e) {
165 traceError(e);
166 return false;
167 }
168 }
169
170 @Override
171 public void start() {
172 stop = false;
173 try {
174 serverSocket = NetUtils.createServerSocket(port, false);
175 } catch (DbException e) {
176 if (!portIsSet) {
177 serverSocket = NetUtils.createServerSocket(0, false);
178 } else {
179 throw e;
180 }
181 }
182 port = serverSocket.getLocalPort();
183 }
184
185 @Override
186 public void listen() {
187 String threadName = Thread.currentThread().getName();
188 try {
189 while (!stop) {
190 Socket s = serverSocket.accept();
191 if (!allow(s)) {
192 trace("Connection not allowed");
193 s.close();
194 } else {
195 Utils10.setTcpQuickack(s, true);
196 PgServerThread c = new PgServerThread(s, this);
197 running.add(c);
198 int id = pid.incrementAndGet();
199 c.setProcessId(id);
200 Thread thread = new Thread(c, threadName + " thread-" + id);
201 thread.setDaemon(isDaemon);
202 c.setThread(thread);
203 thread.start();
204 }
205 }
206 } catch (Exception e) {
207 if (!stop) {
208 e.printStackTrace();
209 }
210 }
211 }
212
213 @Override
214 public void stop() {
215 // TODO server: combine with tcp server
216 if (!stop) {
217 stop = true;
218 if (serverSocket != null) {
219 try {
220 serverSocket.close();
221 } catch (IOException e) {
222 // TODO log exception
223 e.printStackTrace();
224 }
225 serverSocket = null;
226 }
227 }
228 // TODO server: using a boolean 'now' argument? a timeout?
229 for (PgServerThread c : new ArrayList<>(running)) {
230 c.close();
231 try {
232 Thread t = c.getThread();
233 if (t != null) {
234 t.join(100);
235 }
236 } catch (Exception e) {
237 // TODO log exception
238 e.printStackTrace();
239 }
240 }
241 }
242
243 @Override
244 public boolean isRunning(boolean traceError) {
245 if (serverSocket == null) {
246 return false;
247 }
248 try {
249 Socket s = NetUtils.createLoopbackSocket(serverSocket.getLocalPort(), false);
250 s.close();
251 return true;
252 } catch (Exception e) {
253 if (traceError) {
254 traceError(e);
255 }
256 return false;
257 }
258 }
259
260 /**
261 * Get the thread with the given process id.
262 *
263 * @param processId the process id
264 * @return the thread
265 */
266 PgServerThread getThread(int processId) {
267 for (PgServerThread c : new ArrayList<>(running)) {
268 if (c.getProcessId() == processId) {
269 return c;
270 }
271 }
272 return null;
273 }
274
275 String getBaseDir() {
276 return baseDir;
277 }
278
279 @Override
280 public boolean getAllowOthers() {
281 return allowOthers;
282 }
283
284 @Override
285 public String getType() {
286 return "PG";
287 }
288
289 @Override
290 public String getName() {
291 return "H2 PG Server";
292 }
293
294 boolean getIfExists() {
295 return ifExists;
296 }
297
298 /**
299 * Returns the name of the given type.
300 *
301 * @param pgType the PostgreSQL type oid
302 * @return the name of the given type
303 */
304 public static String formatType(int pgType) {
305 int valueType;
306 switch (pgType) {
307 case 0:
308 return "-";
309 case PG_TYPE_BOOL:
310 valueType = Value.BOOLEAN;
311 break;
312 case PG_TYPE_BYTEA:
313 valueType = Value.VARBINARY;
314 break;
315 case 18:
316 return "char";
317 case 19:
318 return "name";
319 case PG_TYPE_INT8:
320 valueType = Value.BIGINT;
321 break;
322 case PG_TYPE_INT2:
323 valueType = Value.SMALLINT;
324 break;
325 case 22:
326 return "int2vector";
327 case PG_TYPE_INT4:
328 valueType = Value.INTEGER;
329 break;
330 case 24:
331 return "regproc";
332 case PG_TYPE_TEXT:
333 valueType = Value.CLOB;
334 break;
335 case PG_TYPE_FLOAT4:
336 valueType = Value.REAL;
337 break;
338 case PG_TYPE_FLOAT8:
339 valueType = Value.DOUBLE;
340 break;
341 case PG_TYPE_INT2_ARRAY:
342 return "smallint[]";
343 case PG_TYPE_INT4_ARRAY:
344 return "integer[]";
345 case PG_TYPE_VARCHAR_ARRAY:
346 return "character varying[]";
347 case PG_TYPE_BPCHAR:
348 valueType = Value.CHAR;
349 break;
350 case PG_TYPE_VARCHAR:
351 valueType = Value.VARCHAR;
352 break;
353 case PG_TYPE_DATE:
354 valueType = Value.DATE;
355 break;
356 case PG_TYPE_TIME:
357 valueType = Value.TIME;
358 break;
359 case PG_TYPE_TIMETZ:
360 valueType = Value.TIME_TZ;
361 break;
362 case PG_TYPE_TIMESTAMP:
363 valueType = Value.TIMESTAMP;
364 break;
365 case PG_TYPE_TIMESTAMPTZ:
366 valueType = Value.TIMESTAMP_TZ;
367 break;
368 case PG_TYPE_NUMERIC:
369 valueType = Value.NUMERIC;
370 break;
371 case 2205:
372 return "regclass";
373 default:
374 return "???";
375 }
376 return Value.getTypeName(valueType);
377 }
378
379 /**
380 * Convert the SQL type to a PostgreSQL type
381 *
382 * @param type the SQL type
383 * @return the PostgreSQL type
384 */
385 public static int convertType(TypeInfo type) {
386 switch (type.getValueType()) {
387 case Value.BOOLEAN:
388 return PG_TYPE_BOOL;
389 case Value.VARCHAR:
390 return PG_TYPE_VARCHAR;
391 case Value.NULL:
392 case Value.CLOB:
393 return PG_TYPE_TEXT;
394 case Value.CHAR:
395 return PG_TYPE_BPCHAR;
396 case Value.SMALLINT:
397 return PG_TYPE_INT2;
398 case Value.INTEGER:
399 return PG_TYPE_INT4;
400 case Value.BIGINT:
401 return PG_TYPE_INT8;
402 case Value.NUMERIC:
403 case Value.DECFLOAT:
404 return PG_TYPE_NUMERIC;
405 case Value.REAL:
406 return PG_TYPE_FLOAT4;
407 case Value.DOUBLE:
408 return PG_TYPE_FLOAT8;
409 case Value.TIME:
410 return PG_TYPE_TIME;
411 case Value.TIME_TZ:
412 return PG_TYPE_TIMETZ;
413 case Value.DATE:
414 return PG_TYPE_DATE;
415 case Value.TIMESTAMP:
416 return PG_TYPE_TIMESTAMP;
417 case Value.TIMESTAMP_TZ:
418 return PG_TYPE_TIMESTAMPTZ;
419 case Value.BINARY:
420 case Value.VARBINARY:
421 return PG_TYPE_BYTEA;
422 case Value.ARRAY: {
423 type = (TypeInfo) type.getExtTypeInfo();
424 switch (type.getValueType()) {
425 case Value.SMALLINT:
426 return PG_TYPE_INT2_ARRAY;
427 case Value.INTEGER:
428 return PG_TYPE_INT4_ARRAY;
429 case Value.VARCHAR:
430 return PG_TYPE_VARCHAR_ARRAY;
431 default:
432 return PG_TYPE_VARCHAR_ARRAY;
433 }
434 }
435 default:
436 return PG_TYPE_UNKNOWN;
437 }
438 }
439
440 /**
441 * Get the type hash set.
442 *
443 * @return the type set
444 */
445 HashSet<Integer> getTypeSet() {
446 return typeSet;
447 }
448
449 /**
450 * Check whether a data type is supported.
451 * A warning is logged if not.
452 *
453 * @param type the type
454 */
455 void checkType(int type) {
456 if (!typeSet.contains(type)) {
457 trace("Unsupported type: " + type);
458 }
459 }
460
461 /**
462 * If no key is set, return the original database name. If a key is set,
463 * check if the key matches. If yes, return the correct database name. If
464 * not, throw an exception.
465 *
466 * @param db the key to test (or database name if no key is used)
467 * @return the database name
468 * @throws DbException if a key is set but doesn't match
469 */
470 public String checkKeyAndGetDatabaseName(String db) {
471 if (key == null) {
472 return db;
473 }
474 if (key.equals(db)) {
475 return keyDatabase;
476 }
477 throw DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD);
478 }
479
480 @Override
481 public boolean isDaemon() {
482 return isDaemon;
483 }
484
485 }