Debian Codegraph @

src/main/org/h2/server/pg/PgServerThread.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.ByteArrayInputStream;
9 import java.io.ByteArrayOutputStream;
10 import java.io.DataInputStream;
11 import java.io.DataOutputStream;
12 import java.io.EOFException;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.io.OutputStream;
16 import java.io.StringReader;
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
19 import java.net.Socket;
20 import java.nio.charset.Charset;
21 import java.nio.charset.StandardCharsets;
22 import java.sql.SQLException;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Properties;
28 import java.util.regex.Pattern;
29
30 import org.h2.api.ErrorCode;
31 import org.h2.command.CommandInterface;
32 import org.h2.engine.ConnectionInfo;
33 import org.h2.engine.Constants;
34 import org.h2.engine.Database;
35 import org.h2.engine.Engine;
36 import org.h2.engine.SessionLocal;
37 import org.h2.engine.SysProperties;
38 import org.h2.expression.ParameterInterface;
39 import org.h2.message.DbException;
40 import org.h2.result.ResultInterface;
41 import org.h2.schema.Schema;
42 import org.h2.table.Column;
43 import org.h2.table.Table;
44 import org.h2.util.DateTimeUtils;
45 import org.h2.util.MathUtils;
46 import org.h2.util.NetUtils;
47 import org.h2.util.NetworkConnectionInfo;
48 import org.h2.util.ScriptReader;
49 import org.h2.util.StringUtils;
50 import org.h2.util.TimeZoneProvider;
51 import org.h2.util.Utils;
52 import org.h2.util.Utils10;
53 import org.h2.value.CaseInsensitiveMap;
54 import org.h2.value.TypeInfo;
55 import org.h2.value.Value;
56 import org.h2.value.ValueArray;
57 import org.h2.value.ValueBigint;
58 import org.h2.value.ValueDate;
59 import org.h2.value.ValueDecfloat;
60 import org.h2.value.ValueDouble;
61 import org.h2.value.ValueInteger;
62 import org.h2.value.ValueNull;
63 import org.h2.value.ValueNumeric;
64 import org.h2.value.ValueReal;
65 import org.h2.value.ValueSmallint;
66 import org.h2.value.ValueTime;
67 import org.h2.value.ValueTimeTimeZone;
68 import org.h2.value.ValueTimestamp;
69 import org.h2.value.ValueTimestampTimeZone;
70 import org.h2.value.ValueVarbinary;
71 import org.h2.value.ValueVarchar;
72
73 /**
74 * One server thread is opened for each client.
75 */
76 public final class PgServerThread implements Runnable {
77
78 private static final boolean INTEGER_DATE_TYPES = false;
79
80 private static final Pattern SHOULD_QUOTE = Pattern.compile(".*[\",\\\\{}].*");
81
82 private static String pgTimeZone(String value) {
83 if (value.startsWith("GMT+")) {
84 return convertTimeZone(value, "GMT-");
85 } else if (value.startsWith("GMT-")) {
86 return convertTimeZone(value, "GMT+");
87 } else if (value.startsWith("UTC+")) {
88 return convertTimeZone(value, "UTC-");
89 } else if (value.startsWith("UTC-")) {
90 return convertTimeZone(value, "UTC+");
91 } else {
92 return value;
93 }
94 }
95
96 private static String convertTimeZone(String value, String prefix) {
97 int length = value.length();
98 return new StringBuilder(length).append(prefix).append(value, 4, length).toString();
99 }
100
101 private final PgServer server;
102 private Socket socket;
103 private SessionLocal session;
104 private boolean stop;
105 private DataInputStream dataInRaw;
106 private DataInputStream dataIn;
107 private OutputStream out;
108 private int messageType;
109 private ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
110 private DataOutputStream dataOut;
111 private Thread thread;
112 private boolean initDone;
113 private String userName;
114 private String databaseName;
115 private int processId;
116 private final int secret;
117 private CommandInterface activeRequest;
118 private String clientEncoding = SysProperties.PG_DEFAULT_CLIENT_ENCODING;
119 private String dateStyle = "ISO, MDY";
120 private TimeZoneProvider timeZone = DateTimeUtils.getTimeZone();
121 private final HashMap<String, Prepared> prepared =
122 new CaseInsensitiveMap<>();
123 private final HashMap<String, Portal> portals =
124 new CaseInsensitiveMap<>();
125
126 PgServerThread(Socket socket, PgServer server) {
127 this.server = server;
128 this.socket = socket;
129 this.secret = (int) MathUtils.secureRandomLong();
130 }
131
132 @Override
133 public void run() {
134 try {
135 server.trace("Connect");
136 InputStream ins = socket.getInputStream();
137 out = socket.getOutputStream();
138 dataInRaw = new DataInputStream(ins);
139 while (!stop) {
140 process();
141 out.flush();
142 }
143 } catch (EOFException e) {
144 // more or less normal disconnect
145 } catch (Exception e) {
146 server.traceError(e);
147 } finally {
148 server.trace("Disconnect");
149 close();
150 }
151 }
152
153 private String readString() throws IOException {
154 ByteArrayOutputStream buff = new ByteArrayOutputStream();
155 while (true) {
156 int x = dataIn.read();
157 if (x <= 0) {
158 break;
159 }
160 buff.write(x);
161 }
162 return Utils10.byteArrayOutputStreamToString(buff, getEncoding());
163 }
164
165 private int readInt() throws IOException {
166 return dataIn.readInt();
167 }
168
169 private short readShort() throws IOException {
170 return dataIn.readShort();
171 }
172
173 private byte readByte() throws IOException {
174 return dataIn.readByte();
175 }
176
177 private void readFully(byte[] buff) throws IOException {
178 dataIn.readFully(buff);
179 }
180
181 private void process() throws IOException {
182 int x;
183 if (initDone) {
184 x = dataInRaw.read();
185 if (x < 0) {
186 stop = true;
187 return;
188 }
189 } else {
190 x = 0;
191 }
192 int len = dataInRaw.readInt();
193 len -= 4;
194 byte[] data = Utils.newBytes(len);
195 dataInRaw.readFully(data, 0, len);
196 dataIn = new DataInputStream(new ByteArrayInputStream(data, 0, len));
197 switch (x) {
198 case 0:
199 server.trace("Init");
200 int version = readInt();
201 if (version == 80877102) {
202 server.trace("CancelRequest");
203 int pid = readInt();
204 int key = readInt();
205 PgServerThread c = server.getThread(pid);
206 if (c != null && key == c.secret) {
207 c.cancelRequest();
208 } else {
209 // According to the PostgreSQL documentation, when canceling
210 // a request, if an invalid secret is provided then no
211 // exception should be sent back to the client.
212 server.trace("Invalid CancelRequest: pid=" + pid + ", key=" + key);
213 }
214 close();
215 } else if (version == 80877103) {
216 server.trace("SSLRequest");
217 out.write('N');
218 } else {
219 server.trace("StartupMessage");
220 server.trace(" version " + version +
221 " (" + (version >> 16) + "." + (version & 0xff) + ")");
222 while (true) {
223 String param = readString();
224 if (param.isEmpty()) {
225 break;
226 }
227 String value = readString();
228 switch (param) {
229 case "user":
230 this.userName = value;
231 break;
232 case "database":
233 this.databaseName = server.checkKeyAndGetDatabaseName(value);
234 break;
235 case "client_encoding":
236 // node-postgres will send "'utf-8'"
237 int length = value.length();
238 if (length >= 2 && value.charAt(0) == '\''
239 && value.charAt(length - 1) == '\'') {
240 value = value.substring(1, length - 1);
241 }
242 // UTF8
243 clientEncoding = value;
244 break;
245 case "DateStyle":
246 if (value.indexOf(',') < 0) {
247 value += ", MDY";
248 }
249 dateStyle = value;
250 break;
251 case "TimeZone":
252 try {
253 timeZone = TimeZoneProvider.ofId(pgTimeZone(value));
254 } catch (Exception e) {
255 server.trace("Unknown TimeZone: " + value);
256 }
257 break;
258 }
259 // extra_float_digits 2
260 // geqo on (Genetic Query Optimization)
261 server.trace(" param " + param + "=" + value);
262 }
263 sendAuthenticationCleartextPassword();
264 initDone = true;
265 }
266 break;
267 case 'p': {
268 server.trace("PasswordMessage");
269 String password = readString();
270 try {
271 Properties info = new Properties();
272 info.put("MODE", "PostgreSQL");
273 info.put("DATABASE_TO_LOWER", "TRUE");
274 info.put("DEFAULT_NULL_ORDERING", "HIGH");
275 String url = "jdbc:h2:" + databaseName;
276 ConnectionInfo ci = new ConnectionInfo(url, info, userName, password);
277 String baseDir = server.getBaseDir();
278 if (baseDir == null) {
279 baseDir = SysProperties.getBaseDir();
280 }
281 if (baseDir != null) {
282 ci.setBaseDir(baseDir);
283 }
284 if (server.getIfExists()) {
285 ci.setProperty("FORBID_CREATION", "TRUE");
286 }
287 ci.setNetworkConnectionInfo(new NetworkConnectionInfo( //
288 NetUtils.ipToShortForm(new StringBuilder("pg://"), //
289 socket.getLocalAddress().getAddress(), true) //
290 .append(':').append(socket.getLocalPort()).toString(), //
291 socket.getInetAddress().getAddress(), socket.getPort(), null));
292 session = Engine.createSession(ci);
293 initDb();
294 sendAuthenticationOk();
295 } catch (Exception e) {
296 e.printStackTrace();
297 stop = true;
298 }
299 break;
300 }
301 case 'P': {
302 server.trace("Parse");
303 Prepared p = new Prepared();
304 p.name = readString();
305 p.sql = getSQL(readString());
306 int paramTypesCount = readShort();
307 int[] paramTypes = null;
308 if (paramTypesCount > 0) {
309 paramTypes = new int[paramTypesCount];
310 for (int i = 0; i < paramTypesCount; i++) {
311 paramTypes[i] = readInt();
312 }
313 }
314 try {
315 p.prep = session.prepareLocal(p.sql);
316 ArrayList<? extends ParameterInterface> parameters = p.prep.getParameters();
317 int count = parameters.size();
318 p.paramType = new int[count];
319 for (int i = 0; i < count; i++) {
320 int type;
321 if (i < paramTypesCount && paramTypes[i] != 0) {
322 type = paramTypes[i];
323 server.checkType(type);
324 } else {
325 type = PgServer.convertType(parameters.get(i).getType());
326 }
327 p.paramType[i] = type;
328 }
329 prepared.put(p.name, p);
330 sendParseComplete();
331 } catch (Exception e) {
332 sendErrorResponse(e);
333 }
334 break;
335 }
336 case 'B': {
337 server.trace("Bind");
338 Portal portal = new Portal();
339 portal.name = readString();
340 String prepName = readString();
341 Prepared prep = prepared.get(prepName);
342 if (prep == null) {
343 sendErrorResponse("Prepared not found");
344 break;
345 }
346 portal.prep = prep;
347 portals.put(portal.name, portal);
348 int formatCodeCount = readShort();
349 int[] formatCodes = new int[formatCodeCount];
350 for (int i = 0; i < formatCodeCount; i++) {
351 formatCodes[i] = readShort();
352 }
353 int paramCount = readShort();
354 try {
355 ArrayList<? extends ParameterInterface> parameters = prep.prep.getParameters();
356 for (int i = 0; i < paramCount; i++) {
357 setParameter(parameters, prep.paramType[i], i, formatCodes);
358 }
359 } catch (Exception e) {
360 sendErrorResponse(e);
361 break;
362 }
363 int resultCodeCount = readShort();
364 portal.resultColumnFormat = new int[resultCodeCount];
365 for (int i = 0; i < resultCodeCount; i++) {
366 portal.resultColumnFormat[i] = readShort();
367 }
368 sendBindComplete();
369 break;
370 }
371 case 'C': {
372 char type = (char) readByte();
373 String name = readString();
374 server.trace("Close");
375 if (type == 'S') {
376 Prepared p = prepared.remove(name);
377 if (p != null) {
378 p.close();
379 }
380 } else if (type == 'P') {
381 Portal p = portals.remove(name);
382 if (p != null) {
383 p.prep.closeResult();
384 }
385 } else {
386 server.trace("expected S or P, got " + type);
387 sendErrorResponse("expected S or P");
388 break;
389 }
390 sendCloseComplete();
391 break;
392 }
393 case 'D': {
394 char type = (char) readByte();
395 String name = readString();
396 server.trace("Describe");
397 if (type == 'S') {
398 Prepared p = prepared.get(name);
399 if (p == null) {
400 sendErrorResponse("Prepared not found: " + name);
401 } else {
402 try {
403 sendParameterDescription(p.prep.getParameters(), p.paramType);
404 sendRowDescription(p.prep.getMetaData(), null);
405 } catch (Exception e) {
406 sendErrorResponse(e);
407 }
408 }
409 } else if (type == 'P') {
410 Portal p = portals.get(name);
411 if (p == null) {
412 sendErrorResponse("Portal not found: " + name);
413 } else {
414 CommandInterface prep = p.prep.prep;
415 try {
416 sendRowDescription(prep.getMetaData(), p.resultColumnFormat);
417 } catch (Exception e) {
418 sendErrorResponse(e);
419 }
420 }
421 } else {
422 server.trace("expected S or P, got " + type);
423 sendErrorResponse("expected S or P");
424 }
425 break;
426 }
427 case 'E': {
428 String name = readString();
429 server.trace("Execute");
430 Portal p = portals.get(name);
431 if (p == null) {
432 sendErrorResponse("Portal not found: " + name);
433 break;
434 }
435 int maxRows = readInt();
436 Prepared prepared = p.prep;
437 CommandInterface prep = prepared.prep;
438 server.trace(prepared.sql);
439 try {
440 setActiveRequest(prep);
441 if (prep.isQuery()) {
442 executeQuery(prepared, prep, p.resultColumnFormat, maxRows);
443 } else {
444 sendCommandComplete(prep, prep.executeUpdate(null).getUpdateCount());
445 }
446 } catch (Exception e) {
447 sendErrorOrCancelResponse(e);
448 } finally {
449 setActiveRequest(null);
450 }
451 break;
452 }
453 case 'S': {
454 server.trace("Sync");
455 sendReadyForQuery();
456 break;
457 }
458 case 'Q': {
459 server.trace("Query");
460 String query = readString();
461 @SuppressWarnings("resource")
462 ScriptReader reader = new ScriptReader(new StringReader(query));
463 while (true) {
464 String s = reader.readStatement();
465 if (s == null) {
466 break;
467 }
468 s = getSQL(s);
469 try (CommandInterface command = session.prepareLocal(s)) {
470 setActiveRequest(command);
471 if (command.isQuery()) {
472 try (ResultInterface result = command.executeQuery(0, false)) {
473 sendRowDescription(result, null);
474 while (result.next()) {
475 sendDataRow(result, null);
476 }
477 sendCommandComplete(command, 0);
478 }
479 } else {
480 sendCommandComplete(command, command.executeUpdate(null).getUpdateCount());
481 }
482 } catch (Exception e) {
483 sendErrorOrCancelResponse(e);
484 break;
485 } finally {
486 setActiveRequest(null);
487 }
488 }
489 sendReadyForQuery();
490 break;
491 }
492 case 'X': {
493 server.trace("Terminate");
494 close();
495 break;
496 }
497 default:
498 server.trace("Unsupported: " + x + " (" + (char) x + ")");
499 break;
500 }
501 }
502
503 private void executeQuery(Prepared prepared, CommandInterface prep, int[] resultColumnFormat, int maxRows)
504 throws Exception {
505 ResultInterface result = prepared.result;
506 if (result == null) {
507 result = prep.executeQuery(0L, false);
508 }
509 try {
510 // the meta-data is sent in the prior 'Describe'
511 if (maxRows == 0) {
512 while (result.next()) {
513 sendDataRow(result, resultColumnFormat);
514 }
515 } else {
516 for (; maxRows > 0 && result.next(); maxRows--) {
517 sendDataRow(result, resultColumnFormat);
518 }
519 if (result.hasNext()) {
520 prepared.result = result;
521 sendCommandSuspended();
522 return;
523 }
524 }
525 prepared.closeResult();
526 sendCommandComplete(prep, 0);
527 } catch (Exception e) {
528 prepared.closeResult();
529 throw e;
530 }
531 }
532
533 private String getSQL(String s) {
534 String lower = StringUtils.toLowerEnglish(s);
535 if (lower.startsWith("show max_identifier_length")) {
536 s = "CALL 63";
537 } else if (lower.startsWith("set client_encoding to")) {
538 s = "set DATESTYLE ISO";
539 }
540 // s = StringUtils.replaceAll(s, "i.indkey[ia.attnum-1]", "0");
541 if (server.getTrace()) {
542 server.trace(s + ";");
543 }
544 return s;
545 }
546
547 private void sendCommandComplete(CommandInterface command, long updateCount) throws IOException {
548 startMessage('C');
549 switch (command.getCommandType()) {
550 case CommandInterface.INSERT:
551 writeStringPart("INSERT 0 ");
552 writeString(Long.toString(updateCount));
553 break;
554 case CommandInterface.UPDATE:
555 writeStringPart("UPDATE ");
556 writeString(Long.toString(updateCount));
557 break;
558 case CommandInterface.DELETE:
559 writeStringPart("DELETE ");
560 writeString(Long.toString(updateCount));
561 break;
562 case CommandInterface.SELECT:
563 case CommandInterface.CALL:
564 writeString("SELECT");
565 break;
566 case CommandInterface.BEGIN:
567 writeString("BEGIN");
568 break;
569 default:
570 server.trace("check CommandComplete tag for command " + command);
571 writeStringPart("UPDATE ");
572 writeString(Long.toString(updateCount));
573 }
574 sendMessage();
575 }
576
577 private void sendCommandSuspended() throws IOException {
578 startMessage('s');
579 sendMessage();
580 }
581
582 private void sendDataRow(ResultInterface result, int[] formatCodes) throws IOException {
583 int columns = result.getVisibleColumnCount();
584 startMessage('D');
585 writeShort(columns);
586 Value[] row = result.currentRow();
587 for (int i = 0; i < columns; i++) {
588 int pgType = PgServer.convertType(result.getColumnType(i));
589 boolean text = formatAsText(pgType, formatCodes, i);
590 writeDataColumn(row[i], pgType, text);
591 }
592 sendMessage();
593 }
594
595 private static long toPostgreDays(long dateValue) {
596 return DateTimeUtils.absoluteDayFromDateValue(dateValue) - 10_957;
597 }
598
599 private void writeDataColumn(Value v, int pgType, boolean text) throws IOException {
600 if (v == ValueNull.INSTANCE) {
601 writeInt(-1);
602 return;
603 }
604 if (text) {
605 // plain text
606 switch (pgType) {
607 case PgServer.PG_TYPE_BOOL:
608 writeInt(1);
609 dataOut.writeByte(v.getBoolean() ? 't' : 'f');
610 break;
611 case PgServer.PG_TYPE_BYTEA: {
612 byte[] bytes = v.getBytesNoCopy();
613 int length = bytes.length;
614 int cnt = length;
615 for (int i = 0; i < length; i++) {
616 byte b = bytes[i];
617 if (b < 32 || b > 126) {
618 cnt += 3;
619 } else if (b == 92) {
620 cnt++;
621 }
622 }
623 byte[] data = new byte[cnt];
624 for (int i = 0, j = 0; i < length; i++) {
625 byte b = bytes[i];
626 if (b < 32 || b > 126) {
627 data[j++] = '\\';
628 data[j++] = (byte) (((b >>> 6) & 3) + '0');
629 data[j++] = (byte) (((b >>> 3) & 7) + '0');
630 data[j++] = (byte) ((b & 7) + '0');
631 } else if (b == 92) {
632 data[j++] = '\\';
633 data[j++] = '\\';
634 } else {
635 data[j++] = b;
636 }
637 }
638 writeInt(data.length);
639 write(data);
640 break;
641 }
642 case PgServer.PG_TYPE_INT2_ARRAY:
643 case PgServer.PG_TYPE_INT4_ARRAY:
644 case PgServer.PG_TYPE_VARCHAR_ARRAY:
645 ByteArrayOutputStream baos = new ByteArrayOutputStream();
646 baos.write('{');
647 Value[] values = ((ValueArray) v).getList();
648 Charset encoding = getEncoding();
649 for (int i = 0; i < values.length; i++) {
650 if (i > 0) {
651 baos.write(',');
652 }
653 String s = values[i].getString();
654 if (SHOULD_QUOTE.matcher(s).matches()) {
655 List<String> ss = new ArrayList<>();
656 for (String s0 : s.split("\\\\")) {
657 ss.add(s0.replace("\"", "\\\""));
658 }
659 s = "\"" + String.join("\\\\", ss) + "\"";
660 }
661 baos.write(s.getBytes(encoding));
662 }
663 baos.write('}');
664 writeInt(baos.size());
665 write(baos);
666 break;
667 default:
668 byte[] data = v.getString().getBytes(getEncoding());
669 writeInt(data.length);
670 write(data);
671 }
672 } else {
673 // binary
674 switch (pgType) {
675 case PgServer.PG_TYPE_BOOL:
676 writeInt(1);
677 dataOut.writeByte(v.getBoolean() ? 1 : 0);
678 break;
679 case PgServer.PG_TYPE_INT2:
680 writeInt(2);
681 writeShort(v.getShort());
682 break;
683 case PgServer.PG_TYPE_INT4:
684 writeInt(4);
685 writeInt(v.getInt());
686 break;
687 case PgServer.PG_TYPE_INT8:
688 writeInt(8);
689 dataOut.writeLong(v.getLong());
690 break;
691 case PgServer.PG_TYPE_FLOAT4:
692 writeInt(4);
693 dataOut.writeFloat(v.getFloat());
694 break;
695 case PgServer.PG_TYPE_FLOAT8:
696 writeInt(8);
697 dataOut.writeDouble(v.getDouble());
698 break;
699 case PgServer.PG_TYPE_NUMERIC:
700 writeNumericBinary(v.getBigDecimal());
701 break;
702 case PgServer.PG_TYPE_BYTEA: {
703 byte[] data = v.getBytesNoCopy();
704 writeInt(data.length);
705 write(data);
706 break;
707 }
708 case PgServer.PG_TYPE_DATE:
709 writeInt(4);
710 writeInt((int) toPostgreDays(((ValueDate) v).getDateValue()));
711 break;
712 case PgServer.PG_TYPE_TIME:
713 writeTimeBinary(((ValueTime) v).getNanos(), 8);
714 break;
715 case PgServer.PG_TYPE_TIMETZ: {
716 ValueTimeTimeZone t = (ValueTimeTimeZone) v;
717 long m = t.getNanos();
718 writeTimeBinary(m, 12);
719 dataOut.writeInt(-t.getTimeZoneOffsetSeconds());
720 break;
721 }
722 case PgServer.PG_TYPE_TIMESTAMP: {
723 ValueTimestamp t = (ValueTimestamp) v;
724 long m = toPostgreDays(t.getDateValue()) * 86_400;
725 long nanos = t.getTimeNanos();
726 writeTimestampBinary(m, nanos);
727 break;
728 }
729 case PgServer.PG_TYPE_TIMESTAMPTZ: {
730 ValueTimestampTimeZone t = (ValueTimestampTimeZone) v;
731 long m = toPostgreDays(t.getDateValue()) * 86_400;
732 long nanos = t.getTimeNanos() - t.getTimeZoneOffsetSeconds() * 1_000_000_000L;
733 if (nanos < 0L) {
734 m--;
735 nanos += DateTimeUtils.NANOS_PER_DAY;
736 }
737 writeTimestampBinary(m, nanos);
738 break;
739 }
740 default: throw new IllegalStateException("output binary format is undefined");
741 }
742 }
743 }
744
745 private static final int[] POWERS10 = {1, 10, 100, 1000, 10000};
746 private static final int MAX_GROUP_SCALE = 4;
747 private static final int MAX_GROUP_SIZE = POWERS10[4];
748 private static final short NUMERIC_POSITIVE = 0x0000;
749 private static final short NUMERIC_NEGATIVE = 0x4000;
750 private static final short NUMERIC_NAN = (short) 0xC000;
751 private static final BigInteger NUMERIC_CHUNK_MULTIPLIER = BigInteger.valueOf(10_000L);
752
753 private static int divide(BigInteger[] unscaled, int divisor) {
754 BigInteger[] bi = unscaled[0].divideAndRemainder(BigInteger.valueOf(divisor));
755 unscaled[0] = bi[0];
756 return bi[1].intValue();
757 }
758
759 // https://www.npgsql.org/dev/types.html
760 // https://github.com/npgsql/npgsql/blob/8a479081f707784b5040747b23102c3d6371b9d3/
761 // src/Npgsql/TypeHandlers/NumericHandlers/NumericHandler.cs#L166
762 private void writeNumericBinary(BigDecimal value) throws IOException {
763 int weight = 0;
764 List<Integer> groups = new ArrayList<>();
765 int scale = value.scale();
766 int signum = value.signum();
767 if (signum != 0) {
768 BigInteger[] unscaled = {null};
769 if (scale < 0) {
770 unscaled[0] = value.setScale(0).unscaledValue();
771 scale = 0;
772 } else {
773 unscaled[0] = value.unscaledValue();
774 }
775 if (signum < 0) {
776 unscaled[0] = unscaled[0].negate();
777 }
778 weight = -scale / MAX_GROUP_SCALE - 1;
779 int remainder = 0;
780 int scaleChunk = scale % MAX_GROUP_SCALE;
781 if (scaleChunk > 0) {
782 remainder = divide(unscaled, POWERS10[scaleChunk]) * POWERS10[MAX_GROUP_SCALE - scaleChunk];
783 if (remainder != 0) {
784 weight--;
785 }
786 }
787 if (remainder == 0) {
788 while ((remainder = divide(unscaled, MAX_GROUP_SIZE)) == 0) {
789 weight++;
790 }
791 }
792 groups.add(remainder);
793 while (unscaled[0].signum() != 0) {
794 groups.add(divide(unscaled, MAX_GROUP_SIZE));
795 }
796 }
797 int groupCount = groups.size();
798 if (groupCount + weight > Short.MAX_VALUE || scale > Short.MAX_VALUE) {
799 throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, value.toString());
800 }
801 writeInt(8 + groupCount * 2);
802 writeShort(groupCount);
803 writeShort(groupCount + weight);
804 writeShort(signum < 0 ? NUMERIC_NEGATIVE : NUMERIC_POSITIVE);
805 writeShort(scale);
806 for (int i = groupCount - 1; i >= 0; i--) {
807 writeShort(groups.get(i));
808 }
809 }
810
811 private void writeTimeBinary(long m, int numBytes) throws IOException {
812 writeInt(numBytes);
813 if (INTEGER_DATE_TYPES) {
814 // long format
815 m /= 1_000;
816 } else {
817 // double format
818 m = Double.doubleToLongBits(m * 0.000_000_001);
819 }
820 dataOut.writeLong(m);
821 }
822
823 private void writeTimestampBinary(long m, long nanos) throws IOException {
824 writeInt(8);
825 if (INTEGER_DATE_TYPES) {
826 // long format
827 m = m * 1_000_000 + nanos / 1_000;
828 } else {
829 // double format
830 m = Double.doubleToLongBits(m + nanos * 0.000_000_001);
831 }
832 dataOut.writeLong(m);
833 }
834
835 private Charset getEncoding() {
836 if ("UNICODE".equals(clientEncoding)) {
837 return StandardCharsets.UTF_8;
838 }
839 return Charset.forName(clientEncoding);
840 }
841
842 private void setParameter(ArrayList<? extends ParameterInterface> parameters, int pgType, int i, int[] formatCodes)
843 throws IOException {
844 boolean text = true;
845 if (formatCodes.length == 1) {
846 text = formatCodes[0] == 0;
847 } else if (i < formatCodes.length) {
848 text = formatCodes[i] == 0;
849 }
850 int paramLen = readInt();
851 Value value;
852 if (paramLen == -1) {
853 value = ValueNull.INSTANCE;
854 } else if (text) {
855 // plain text
856 byte[] data = Utils.newBytes(paramLen);
857 readFully(data);
858 String str = new String(data, getEncoding());
859 switch (pgType) {
860 case PgServer.PG_TYPE_DATE: {
861 // Strip timezone offset
862 int idx = str.indexOf(' ');
863 if (idx > 0) {
864 str = str.substring(0, idx);
865 }
866 break;
867 }
868 case PgServer.PG_TYPE_TIME: {
869 // Strip timezone offset
870 int idx = str.indexOf('+');
871 if (idx <= 0) {
872 idx = str.indexOf('-');
873 }
874 if (idx > 0) {
875 str = str.substring(0, idx);
876 }
877 break;
878 }
879 }
880 value = ValueVarchar.get(str, session);
881 } else {
882 // binary
883 switch (pgType) {
884 case PgServer.PG_TYPE_INT2:
885 checkParamLength(2, paramLen);
886 value = ValueSmallint.get(readShort());
887 break;
888 case PgServer.PG_TYPE_INT4:
889 checkParamLength(4, paramLen);
890 value = ValueInteger.get(readInt());
891 break;
892 case PgServer.PG_TYPE_INT8:
893 checkParamLength(8, paramLen);
894 value = ValueBigint.get(dataIn.readLong());
895 break;
896 case PgServer.PG_TYPE_FLOAT4:
897 checkParamLength(4, paramLen);
898 value = ValueReal.get(dataIn.readFloat());
899 break;
900 case PgServer.PG_TYPE_FLOAT8:
901 checkParamLength(8, paramLen);
902 value = ValueDouble.get(dataIn.readDouble());
903 break;
904 case PgServer.PG_TYPE_BYTEA: {
905 byte[] d = Utils.newBytes(paramLen);
906 readFully(d);
907 value = ValueVarbinary.getNoCopy(d);
908 break;
909 }
910 case PgServer.PG_TYPE_NUMERIC:
911 value = readNumericBinary(paramLen);
912 break;
913 default:
914 server.trace("Binary format for type: "+pgType+" is unsupported");
915 byte[] d = Utils.newBytes(paramLen);
916 readFully(d);
917 value = ValueVarchar.get(new String(d, getEncoding()), session);
918 }
919 }
920 parameters.get(i).setValue(value, true);
921 }
922
923 private static void checkParamLength(int expected, int got) {
924 if (expected != got) {
925 throw DbException.getInvalidValueException("paramLen", got);
926 }
927 }
928
929 private Value readNumericBinary(int paramLen) throws IOException {
930 if (paramLen < 8) {
931 throw DbException.getInvalidValueException("numeric binary length", paramLen);
932 }
933 short len = readShort();
934 short weight = readShort();
935 short sign = readShort();
936 short scale = readShort();
937 if (len * 2 + 8 != paramLen) {
938 throw DbException.getInvalidValueException("numeric binary length", paramLen);
939 }
940 if (sign == NUMERIC_NAN) {
941 return ValueDecfloat.NAN;
942 }
943 if (sign != NUMERIC_POSITIVE && sign != NUMERIC_NEGATIVE) {
944 throw DbException.getInvalidValueException("numeric sign", sign);
945 }
946 if ((scale & 0x3FFF) != scale) {
947 throw DbException.getInvalidValueException("numeric scale", scale);
948 }
949 if (len == 0) {
950 return scale == 0 ? ValueNumeric.ZERO : ValueNumeric.get(new BigDecimal(BigInteger.ZERO, scale));
951 }
952 BigInteger n = BigInteger.ZERO;
953 for (int i = 0; i < len; i++) {
954 short c = readShort();
955 if (c < 0 || c > 9_999) {
956 throw DbException.getInvalidValueException("numeric chunk", c);
957 }
958 n = n.multiply(NUMERIC_CHUNK_MULTIPLIER).add(BigInteger.valueOf(c));
959 }
960 if (sign != NUMERIC_POSITIVE) {
961 n = n.negate();
962 }
963 return ValueNumeric.get(new BigDecimal(n, (len - weight - 1) * 4).setScale(scale));
964 }
965
966 private void sendErrorOrCancelResponse(Exception e) throws IOException {
967 if (e instanceof DbException && ((DbException) e).getErrorCode() == ErrorCode.STATEMENT_WAS_CANCELED) {
968 sendCancelQueryResponse();
969 } else {
970 sendErrorResponse(e);
971 }
972 }
973
974 private void sendErrorResponse(Exception re) throws IOException {
975 SQLException e = DbException.toSQLException(re);
976 server.traceError(e);
977 startMessage('E');
978 write('S');
979 writeString("ERROR");
980 write('C');
981 writeString(e.getSQLState());
982 write('M');
983 writeString(e.getMessage());
984 write('D');
985 writeString(e.toString());
986 write(0);
987 sendMessage();
988 }
989
990 private void sendCancelQueryResponse() throws IOException {
991 server.trace("CancelSuccessResponse");
992 startMessage('E');
993 write('S');
994 writeString("ERROR");
995 write('C');
996 writeString("57014");
997 write('M');
998 writeString("canceling statement due to user request");
999 write(0);
1000 sendMessage();
1001 }
1002
1003 private void sendParameterDescription(ArrayList<? extends ParameterInterface> parameters, int[] paramTypes)
1004 throws Exception {
1005 int count = parameters.size();
1006 startMessage('t');
1007 writeShort(count);
1008 for (int i = 0; i < count; i++) {
1009 int type;
1010 if (paramTypes != null && paramTypes[i] != 0) {
1011 type = paramTypes[i];
1012 } else {
1013 type = PgServer.PG_TYPE_VARCHAR;
1014 }
1015 server.checkType(type);
1016 writeInt(type);
1017 }
1018 sendMessage();
1019 }
1020
1021 private void sendNoData() throws IOException {
1022 startMessage('n');
1023 sendMessage();
1024 }
1025
1026 private void sendRowDescription(ResultInterface result, int[] formatCodes) throws IOException {
1027 if (result == null) {
1028 sendNoData();
1029 } else {
1030 int columns = result.getVisibleColumnCount();
1031 int[] oids = new int[columns];
1032 int[] attnums = new int[columns];
1033 int[] types = new int[columns];
1034 int[] precision = new int[columns];
1035 String[] names = new String[columns];
1036 Database database = session.getDatabase();
1037 for (int i = 0; i < columns; i++) {
1038 String name = result.getColumnName(i);
1039 Schema schema = database.findSchema(result.getSchemaName(i));
1040 if (schema != null) {
1041 Table table = schema.findTableOrView(session, result.getTableName(i));
1042 if (table != null) {
1043 oids[i] = table.getId();
1044 Column column = table.findColumn(name);
1045 if (column != null) {
1046 attnums[i] = column.getColumnId() + 1;
1047 }
1048 }
1049 }
1050 names[i] = name;
1051 TypeInfo type = result.getColumnType(i);
1052 int pgType = PgServer.convertType(type);
1053 // the ODBC client needs the column pg_catalog.pg_index
1054 // to be of type 'int2vector'
1055 // if (name.equalsIgnoreCase("indkey") &&
1056 // "pg_index".equalsIgnoreCase(
1057 // meta.getTableName(i + 1))) {
1058 // type = PgServer.PG_TYPE_INT2VECTOR;
1059 // }
1060 precision[i] = type.getDisplaySize();
1061 if (type.getValueType() != Value.NULL) {
1062 server.checkType(pgType);
1063 }
1064 types[i] = pgType;
1065 }
1066 startMessage('T');
1067 writeShort(columns);
1068 for (int i = 0; i < columns; i++) {
1069 writeString(StringUtils.toLowerEnglish(names[i]));
1070 // object ID
1071 writeInt(oids[i]);
1072 // attribute number of the column
1073 writeShort(attnums[i]);
1074 // data type
1075 writeInt(types[i]);
1076 // pg_type.typlen
1077 writeShort(getTypeSize(types[i], precision[i]));
1078 // pg_attribute.atttypmod
1079 writeInt(-1);
1080 // the format type: text = 0, binary = 1
1081 writeShort(formatAsText(types[i], formatCodes, i) ? 0 : 1);
1082 }
1083 sendMessage();
1084 }
1085 }
1086
1087 /**
1088 * Check whether the given type should be formatted as text.
1089 *
1090 * @param pgType data type
1091 * @param formatCodes format codes, or {@code null}
1092 * @param column 0-based column number
1093 * @return true for text
1094 */
1095 private static boolean formatAsText(int pgType, int[] formatCodes, int column) {
1096 boolean text = true;
1097 if (formatCodes != null && formatCodes.length > 0) {
1098 if (formatCodes.length == 1) {
1099 text = formatCodes[0] == 0;
1100 } else if (column < formatCodes.length) {
1101 text = formatCodes[column] == 0;
1102 }
1103 }
1104 return text;
1105 }
1106
1107 private static int getTypeSize(int pgType, int precision) {
1108 switch (pgType) {
1109 case PgServer.PG_TYPE_BOOL:
1110 return 1;
1111 case PgServer.PG_TYPE_VARCHAR:
1112 return Math.max(255, precision + 10);
1113 default:
1114 return precision + 4;
1115 }
1116 }
1117
1118 private void sendErrorResponse(String message) throws IOException {
1119 server.trace("Exception: " + message);
1120 startMessage('E');
1121 write('S');
1122 writeString("ERROR");
1123 write('C');
1124 // PROTOCOL VIOLATION
1125 writeString("08P01");
1126 write('M');
1127 writeString(message);
1128 sendMessage();
1129 }
1130
1131 private void sendParseComplete() throws IOException {
1132 startMessage('1');
1133 sendMessage();
1134 }
1135
1136 private void sendBindComplete() throws IOException {
1137 startMessage('2');
1138 sendMessage();
1139 }
1140
1141 private void sendCloseComplete() throws IOException {
1142 startMessage('3');
1143 sendMessage();
1144 }
1145
1146 private void initDb() {
1147 session.setTimeZone(timeZone);
1148 try (CommandInterface command = session.prepareLocal("set search_path = public, pg_catalog")) {
1149 command.executeUpdate(null);
1150 }
1151 HashSet<Integer> typeSet = server.getTypeSet();
1152 if (typeSet.isEmpty()) {
1153 try (CommandInterface command = session.prepareLocal("select oid from pg_catalog.pg_type");
1154 ResultInterface result = command.executeQuery(0, false)) {
1155 while (result.next()) {
1156 typeSet.add(result.currentRow()[0].getInt());
1157 }
1158 }
1159 }
1160 }
1161
1162 /**
1163 * Close this connection.
1164 */
1165 void close() {
1166 for (Prepared prep : prepared.values()) {
1167 prep.close();
1168 }
1169 try {
1170 stop = true;
1171 try {
1172 session.close();
1173 } catch (Exception e) {
1174 // Ignore
1175 }
1176 if (socket != null) {
1177 socket.close();
1178 }
1179 server.trace("Close");
1180 } catch (Exception e) {
1181 server.traceError(e);
1182 }
1183 session = null;
1184 socket = null;
1185 server.remove(this);
1186 }
1187
1188 private void sendAuthenticationCleartextPassword() throws IOException {
1189 startMessage('R');
1190 writeInt(3);
1191 sendMessage();
1192 }
1193
1194 private void sendAuthenticationOk() throws IOException {
1195 startMessage('R');
1196 writeInt(0);
1197 sendMessage();
1198 sendParameterStatus("client_encoding", clientEncoding);
1199 sendParameterStatus("DateStyle", dateStyle);
1200 sendParameterStatus("is_superuser", "off");
1201 sendParameterStatus("server_encoding", "SQL_ASCII");
1202 sendParameterStatus("server_version", Constants.PG_VERSION);
1203 sendParameterStatus("session_authorization", userName);
1204 sendParameterStatus("standard_conforming_strings", "off");
1205 sendParameterStatus("TimeZone", pgTimeZone(timeZone.getId()));
1206 // Don't inline, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=569498
1207 String value = INTEGER_DATE_TYPES ? "on" : "off";
1208 sendParameterStatus("integer_datetimes", value);
1209 sendBackendKeyData();
1210 sendReadyForQuery();
1211 }
1212
1213 private void sendReadyForQuery() throws IOException {
1214 startMessage('Z');
1215 write((byte) (session.getAutoCommit() ? /* idle */ 'I' : /* in a transaction block */ 'T'));
1216 sendMessage();
1217 }
1218
1219 private void sendBackendKeyData() throws IOException {
1220 startMessage('K');
1221 writeInt(processId);
1222 writeInt(secret);
1223 sendMessage();
1224 }
1225
1226 private void writeString(String s) throws IOException {
1227 writeStringPart(s);
1228 write(0);
1229 }
1230
1231 private void writeStringPart(String s) throws IOException {
1232 write(s.getBytes(getEncoding()));
1233 }
1234
1235 private void writeInt(int i) throws IOException {
1236 dataOut.writeInt(i);
1237 }
1238
1239 private void writeShort(int i) throws IOException {
1240 dataOut.writeShort(i);
1241 }
1242
1243 private void write(byte[] data) throws IOException {
1244 dataOut.write(data);
1245 }
1246
1247 private void write(ByteArrayOutputStream baos) throws IOException {
1248 baos.writeTo(dataOut);
1249 }
1250
1251 private void write(int b) throws IOException {
1252 dataOut.write(b);
1253 }
1254
1255 private void startMessage(int newMessageType) {
1256 this.messageType = newMessageType;
1257 if (outBuffer.size() <= 65_536) {
1258 outBuffer.reset();
1259 } else {
1260 outBuffer = new ByteArrayOutputStream();
1261 }
1262 dataOut = new DataOutputStream(outBuffer);
1263 }
1264
1265 private void sendMessage() throws IOException {
1266 dataOut.flush();
1267 dataOut = new DataOutputStream(out);
1268 write(messageType);
1269 writeInt(outBuffer.size() + 4);
1270 write(outBuffer);
1271 dataOut.flush();
1272 }
1273
1274 private void sendParameterStatus(String param, String value)
1275 throws IOException {
1276 startMessage('S');
1277 writeString(param);
1278 writeString(value);
1279 sendMessage();
1280 }
1281
1282 void setThread(Thread thread) {
1283 this.thread = thread;
1284 }
1285
1286 Thread getThread() {
1287 return thread;
1288 }
1289
1290 void setProcessId(int id) {
1291 this.processId = id;
1292 }
1293
1294 int getProcessId() {
1295 return this.processId;
1296 }
1297
1298 private synchronized void setActiveRequest(CommandInterface statement) {
1299 activeRequest = statement;
1300 }
1301
1302 /**
1303 * Kill a currently running query on this thread.
1304 */
1305 private synchronized void cancelRequest() {
1306 if (activeRequest != null) {
1307 activeRequest.cancel();
1308 activeRequest = null;
1309 }
1310 }
1311
1312 /**
1313 * Represents a PostgreSQL Prepared object.
1314 */
1315 static class Prepared {
1316
1317 /**
1318 * The object name.
1319 */
1320 String name;
1321
1322 /**
1323 * The SQL statement.
1324 */
1325 String sql;
1326
1327 /**
1328 * The prepared statement.
1329 */
1330 CommandInterface prep;
1331
1332 /**
1333 * The current result (for suspended portal).
1334 */
1335 ResultInterface result;
1336
1337 /**
1338 * The list of parameter types (if set).
1339 */
1340 int[] paramType;
1341
1342 /**
1343 * Closes prepared statement and result, if any.
1344 */
1345 void close() {
1346 try {
1347 closeResult();
1348 prep.close();
1349 } catch (Exception e) {
1350 // Ignore
1351 }
1352 }
1353
1354 /**
1355 * Closes the result, if any.
1356 */
1357 void closeResult() {
1358 ResultInterface result = this.result;
1359 if (result != null) {
1360 this.result = null;
1361 result.close();
1362 }
1363 }
1364 }
1365
1366 /**
1367 * Represents a PostgreSQL Portal object.
1368 */
1369 static class Portal {
1370
1371 /**
1372 * The portal name.
1373 */
1374 String name;
1375
1376 /**
1377 * The format used in the result set columns (if set).
1378 */
1379 int[] resultColumnFormat;
1380
1381 /**
1382 * The prepared object.
1383 */
1384 Prepared prep;
1385 }
1386 }