Debian Codegraph @

src/main/org/h2/value/Transfer.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.value;
7
8 import java.io.BufferedInputStream;
9 import java.io.BufferedOutputStream;
10 import java.io.DataInputStream;
11 import java.io.DataOutputStream;
12 import java.io.IOException;
13 import java.io.Reader;
14 import java.math.BigDecimal;
15 import java.net.InetAddress;
16 import java.net.Socket;
17 import java.util.Iterator;
18 import java.util.LinkedHashMap;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.Map.Entry;
22
23 import org.h2.api.ErrorCode;
24 import org.h2.api.IntervalQualifier;
25 import org.h2.engine.Constants;
26 import org.h2.engine.Session;
27 import org.h2.message.DbException;
28 import org.h2.security.SHA256;
29 import org.h2.store.Data;
30 import org.h2.store.DataReader;
31 import org.h2.util.Bits;
32 import org.h2.util.DateTimeUtils;
33 import org.h2.util.IOUtils;
34 import org.h2.util.MathUtils;
35 import org.h2.util.NetUtils;
36 import org.h2.util.StringUtils;
37 import org.h2.util.Utils;
38 import org.h2.value.lob.LobData;
39 import org.h2.value.lob.LobDataDatabase;
40 import org.h2.value.lob.LobDataFetchOnDemand;
41
42 /**
43 * The transfer class is used to send and receive Value objects.
44 * It is used on both the client side, and on the server side.
45 */
46 public final class Transfer {
47
48 private static final int BUFFER_SIZE = 64 * 1024;
49 private static final int LOB_MAGIC = 0x1234;
50 private static final int LOB_MAC_SALT_LENGTH = 16;
51
52 private static final int NULL = 0;
53 private static final int BOOLEAN = 1;
54 private static final int TINYINT = 2;
55 private static final int SMALLINT = 3;
56 private static final int INTEGER = 4;
57 private static final int BIGINT = 5;
58 private static final int NUMERIC = 6;
59 private static final int DOUBLE = 7;
60 private static final int REAL = 8;
61 private static final int TIME = 9;
62 private static final int DATE = 10;
63 private static final int TIMESTAMP = 11;
64 private static final int VARBINARY = 12;
65 private static final int VARCHAR = 13;
66 private static final int VARCHAR_IGNORECASE = 14;
67 private static final int BLOB = 15;
68 private static final int CLOB = 16;
69 private static final int ARRAY = 17;
70 private static final int JAVA_OBJECT = 19;
71 private static final int UUID = 20;
72 private static final int CHAR = 21;
73 private static final int GEOMETRY = 22;
74 // 1.4.192
75 private static final int TIMESTAMP_TZ = 24;
76 // 1.4.195
77 private static final int ENUM = 25;
78 // 1.4.198
79 private static final int INTERVAL = 26;
80 private static final int ROW = 27;
81 // 1.4.200
82 private static final int JSON = 28;
83 private static final int TIME_TZ = 29;
84 // 2.0.202
85 private static final int BINARY = 30;
86 private static final int DECFLOAT = 31;
87
88 private static final int[] VALUE_TO_TI = new int[Value.TYPE_COUNT + 1];
89 private static final int[] TI_TO_VALUE = new int[45];
90
91 static {
92 addType(-1, Value.UNKNOWN);
93 addType(NULL, Value.NULL);
94 addType(BOOLEAN, Value.BOOLEAN);
95 addType(TINYINT, Value.TINYINT);
96 addType(SMALLINT, Value.SMALLINT);
97 addType(INTEGER, Value.INTEGER);
98 addType(BIGINT, Value.BIGINT);
99 addType(NUMERIC, Value.NUMERIC);
100 addType(DOUBLE, Value.DOUBLE);
101 addType(REAL, Value.REAL);
102 addType(TIME, Value.TIME);
103 addType(DATE, Value.DATE);
104 addType(TIMESTAMP, Value.TIMESTAMP);
105 addType(VARBINARY, Value.VARBINARY);
106 addType(VARCHAR, Value.VARCHAR);
107 addType(VARCHAR_IGNORECASE, Value.VARCHAR_IGNORECASE);
108 addType(BLOB, Value.BLOB);
109 addType(CLOB, Value.CLOB);
110 addType(ARRAY, Value.ARRAY);
111 addType(JAVA_OBJECT, Value.JAVA_OBJECT);
112 addType(UUID, Value.UUID);
113 addType(CHAR, Value.CHAR);
114 addType(GEOMETRY, Value.GEOMETRY);
115 addType(TIMESTAMP_TZ, Value.TIMESTAMP_TZ);
116 addType(ENUM, Value.ENUM);
117 addType(26, Value.INTERVAL_YEAR);
118 addType(27, Value.INTERVAL_MONTH);
119 addType(28, Value.INTERVAL_DAY);
120 addType(29, Value.INTERVAL_HOUR);
121 addType(30, Value.INTERVAL_MINUTE);
122 addType(31, Value.INTERVAL_SECOND);
123 addType(32, Value.INTERVAL_YEAR_TO_MONTH);
124 addType(33, Value.INTERVAL_DAY_TO_HOUR);
125 addType(34, Value.INTERVAL_DAY_TO_MINUTE);
126 addType(35, Value.INTERVAL_DAY_TO_SECOND);
127 addType(36, Value.INTERVAL_HOUR_TO_MINUTE);
128 addType(37, Value.INTERVAL_HOUR_TO_SECOND);
129 addType(38, Value.INTERVAL_MINUTE_TO_SECOND);
130 addType(39, Value.ROW);
131 addType(40, Value.JSON);
132 addType(41, Value.TIME_TZ);
133 addType(42, Value.BINARY);
134 addType(43, Value.DECFLOAT);
135 }
136
137 private static void addType(int typeInformationType, int valueType) {
138 VALUE_TO_TI[valueType + 1] = typeInformationType;
139 TI_TO_VALUE[typeInformationType + 1] = valueType;
140 }
141
142 private Socket socket;
143 private DataInputStream in;
144 private DataOutputStream out;
145 private Session session;
146 private boolean ssl;
147 private int version;
148 private byte[] lobMacSalt;
149
150 /**
151 * Create a new transfer object for the specified session.
152 *
153 * @param session the session
154 * @param s the socket
155 */
156 public Transfer(Session session, Socket s) {
157 this.session = session;
158 this.socket = s;
159 }
160
161 /**
162 * Initialize the transfer object. This method will try to open an input and
163 * output stream.
164 * @throws IOException on failure
165 */
166 public synchronized void init() throws IOException {
167 if (socket != null) {
168 in = new DataInputStream(
169 new BufferedInputStream(
170 socket.getInputStream(), Transfer.BUFFER_SIZE));
171 out = new DataOutputStream(
172 new BufferedOutputStream(
173 socket.getOutputStream(), Transfer.BUFFER_SIZE));
174 }
175 }
176
177 /**
178 * Write pending changes.
179 * @throws IOException on failure
180 */
181 public void flush() throws IOException {
182 out.flush();
183 }
184
185 /**
186 * Write a boolean.
187 *
188 * @param x the value
189 * @return itself
190 * @throws IOException on failure
191 */
192 public Transfer writeBoolean(boolean x) throws IOException {
193 out.writeByte((byte) (x ? 1 : 0));
194 return this;
195 }
196
197 /**
198 * Read a boolean.
199 *
200 * @return the value
201 * @throws IOException on failure
202 */
203 public boolean readBoolean() throws IOException {
204 return in.readByte() != 0;
205 }
206
207 /**
208 * Write a byte.
209 *
210 * @param x the value
211 * @return itself
212 * @throws IOException on failure
213 */
214 public Transfer writeByte(byte x) throws IOException {
215 out.writeByte(x);
216 return this;
217 }
218
219 /**
220 * Read a byte.
221 *
222 * @return the value
223 * @throws IOException on failure
224 */
225 public byte readByte() throws IOException {
226 return in.readByte();
227 }
228
229 /**
230 * Write a short.
231 *
232 * @param x the value
233 * @return itself
234 * @throws IOException on failure
235 */
236 private Transfer writeShort(short x) throws IOException {
237 out.writeShort(x);
238 return this;
239 }
240
241 /**
242 * Read a short.
243 *
244 * @return the value
245 * @throws IOException on failure
246 */
247 private short readShort() throws IOException {
248 return in.readShort();
249 }
250
251 /**
252 * Write an int.
253 *
254 * @param x the value
255 * @return itself
256 * @throws IOException on failure
257 */
258 public Transfer writeInt(int x) throws IOException {
259 out.writeInt(x);
260 return this;
261 }
262
263 /**
264 * Read an int.
265 *
266 * @return the value
267 * @throws IOException on failure
268 */
269 public int readInt() throws IOException {
270 return in.readInt();
271 }
272
273 /**
274 * Write a long.
275 *
276 * @param x the value
277 * @return itself
278 * @throws IOException on failure
279 */
280 public Transfer writeLong(long x) throws IOException {
281 out.writeLong(x);
282 return this;
283 }
284
285 /**
286 * Read a long.
287 *
288 * @return the value
289 * @throws IOException on failure
290 */
291 public long readLong() throws IOException {
292 return in.readLong();
293 }
294
295 /**
296 * Write a double.
297 *
298 * @param i the value
299 * @return itself
300 * @throws IOException on failure
301 */
302 private Transfer writeDouble(double i) throws IOException {
303 out.writeDouble(i);
304 return this;
305 }
306
307 /**
308 * Write a float.
309 *
310 * @param i the value
311 * @return itself
312 */
313 private Transfer writeFloat(float i) throws IOException {
314 out.writeFloat(i);
315 return this;
316 }
317
318 /**
319 * Read a double.
320 *
321 * @return the value
322 * @throws IOException on failure
323 */
324 private double readDouble() throws IOException {
325 return in.readDouble();
326 }
327
328 /**
329 * Read a float.
330 *
331 * @return the value
332 * @throws IOException on failure
333 */
334 private float readFloat() throws IOException {
335 return in.readFloat();
336 }
337
338 /**
339 * Write a string. The maximum string length is Integer.MAX_VALUE.
340 *
341 * @param s the value
342 * @return itself
343 * @throws IOException on failure
344 */
345 public Transfer writeString(String s) throws IOException {
346 if (s == null) {
347 out.writeInt(-1);
348 } else {
349 out.writeInt(s.length());
350 out.writeChars(s);
351 }
352 return this;
353 }
354
355 /**
356 * Read a string.
357 *
358 * @return the value
359 * @throws IOException on failure
360 */
361 public String readString() throws IOException {
362 int len = in.readInt();
363 if (len == -1) {
364 return null;
365 }
366 StringBuilder buff = new StringBuilder(len);
367 for (int i = 0; i < len; i++) {
368 buff.append(in.readChar());
369 }
370 String s = buff.toString();
371 s = StringUtils.cache(s);
372 return s;
373 }
374
375 /**
376 * Write a byte array.
377 *
378 * @param data the value
379 * @return itself
380 * @throws IOException on failure
381 */
382 public Transfer writeBytes(byte[] data) throws IOException {
383 if (data == null) {
384 writeInt(-1);
385 } else {
386 writeInt(data.length);
387 out.write(data);
388 }
389 return this;
390 }
391
392 /**
393 * Write a number of bytes.
394 *
395 * @param buff the value
396 * @param off the offset
397 * @param len the length
398 * @return itself
399 * @throws IOException on failure
400 */
401 public Transfer writeBytes(byte[] buff, int off, int len) throws IOException {
402 out.write(buff, off, len);
403 return this;
404 }
405
406 /**
407 * Read a byte array.
408 *
409 * @return the value
410 * @throws IOException on failure
411 */
412 public byte[] readBytes() throws IOException {
413 int len = readInt();
414 if (len == -1) {
415 return null;
416 }
417 byte[] b = Utils.newBytes(len);
418 in.readFully(b);
419 return b;
420 }
421
422 /**
423 * Read a number of bytes.
424 *
425 * @param buff the target buffer
426 * @param off the offset
427 * @param len the number of bytes to read
428 * @throws IOException on failure
429 */
430 public void readBytes(byte[] buff, int off, int len) throws IOException {
431 in.readFully(buff, off, len);
432 }
433
434 /**
435 * Close the transfer object and the socket.
436 */
437 public synchronized void close() {
438 if (socket != null) {
439 try {
440 if (out != null) {
441 out.flush();
442 }
443 socket.close();
444 } catch (IOException e) {
445 DbException.traceThrowable(e);
446 } finally {
447 socket = null;
448 }
449 }
450 }
451
452 /**
453 * Write value type, precision, and scale.
454 *
455 * @param type data type information
456 * @return itself
457 * @throws IOException on failure
458 */
459 public Transfer writeTypeInfo(TypeInfo type) throws IOException {
460 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
461 writeTypeInfo20(type);
462 } else {
463 writeTypeInfo19(type);
464 }
465 return this;
466 }
467
468 private void writeTypeInfo20(TypeInfo type) throws IOException {
469 int valueType = type.getValueType();
470 writeInt(VALUE_TO_TI[valueType + 1]);
471 switch (valueType) {
472 case Value.UNKNOWN:
473 case Value.NULL:
474 case Value.BOOLEAN:
475 case Value.TINYINT:
476 case Value.SMALLINT:
477 case Value.INTEGER:
478 case Value.BIGINT:
479 case Value.DATE:
480 case Value.UUID:
481 break;
482 case Value.CHAR:
483 case Value.VARCHAR:
484 case Value.VARCHAR_IGNORECASE:
485 case Value.BINARY:
486 case Value.VARBINARY:
487 case Value.DECFLOAT:
488 case Value.JAVA_OBJECT:
489 case Value.JSON:
490 writeInt((int) type.getDeclaredPrecision());
491 break;
492 case Value.CLOB:
493 case Value.BLOB:
494 writeLong(type.getDeclaredPrecision());
495 break;
496 case Value.NUMERIC:
497 writeInt((int) type.getDeclaredPrecision());
498 writeInt(type.getDeclaredScale());
499 writeBoolean(type.getExtTypeInfo() != null);
500 break;
501 case Value.REAL:
502 case Value.DOUBLE:
503 case Value.INTERVAL_YEAR:
504 case Value.INTERVAL_MONTH:
505 case Value.INTERVAL_DAY:
506 case Value.INTERVAL_HOUR:
507 case Value.INTERVAL_MINUTE:
508 case Value.INTERVAL_YEAR_TO_MONTH:
509 case Value.INTERVAL_DAY_TO_HOUR:
510 case Value.INTERVAL_DAY_TO_MINUTE:
511 case Value.INTERVAL_HOUR_TO_MINUTE:
512 writeBytePrecisionWithDefault(type.getDeclaredPrecision());
513 break;
514 case Value.TIME:
515 case Value.TIME_TZ:
516 case Value.TIMESTAMP:
517 case Value.TIMESTAMP_TZ:
518 writeByteScaleWithDefault(type.getDeclaredScale());
519 break;
520 case Value.INTERVAL_SECOND:
521 case Value.INTERVAL_DAY_TO_SECOND:
522 case Value.INTERVAL_HOUR_TO_SECOND:
523 case Value.INTERVAL_MINUTE_TO_SECOND:
524 writeBytePrecisionWithDefault(type.getDeclaredPrecision());
525 writeByteScaleWithDefault(type.getDeclaredScale());
526 break;
527 case Value.ENUM:
528 writeTypeInfoEnum(type);
529 break;
530 case Value.GEOMETRY:
531 writeTypeInfoGeometry(type);
532 break;
533 case Value.ARRAY:
534 writeInt((int) type.getDeclaredPrecision());
535 writeTypeInfo((TypeInfo) type.getExtTypeInfo());
536 break;
537 case Value.ROW:
538 writeTypeInfoRow(type);
539 break;
540 default:
541 throw DbException.getUnsupportedException("value type " + valueType);
542 }
543 }
544
545 private void writeBytePrecisionWithDefault(long precision) throws IOException {
546 writeByte(precision >= 0 ? (byte) precision : -1);
547 }
548
549 private void writeByteScaleWithDefault(int scale) throws IOException {
550 writeByte(scale >= 0 ? (byte) scale : -1);
551 }
552
553 private void writeTypeInfoEnum(TypeInfo type) throws IOException {
554 ExtTypeInfoEnum ext = (ExtTypeInfoEnum) type.getExtTypeInfo();
555 if (ext != null) {
556 int c = ext.getCount();
557 writeInt(c);
558 for (int i = 0; i < c; i++) {
559 writeString(ext.getEnumerator(i));
560 }
561 } else {
562 writeInt(0);
563 }
564 }
565
566 private void writeTypeInfoGeometry(TypeInfo type) throws IOException {
567 ExtTypeInfoGeometry ext = (ExtTypeInfoGeometry) type.getExtTypeInfo();
568 if (ext == null) {
569 writeByte((byte) 0);
570 } else {
571 int t = ext.getType();
572 Integer srid = ext.getSrid();
573 if (t == 0) {
574 if (srid == null) {
575 writeByte((byte) 0);
576 } else {
577 writeByte((byte) 2);
578 writeInt(srid);
579 }
580 } else {
581 if (srid == null) {
582 writeByte((byte) 1);
583 writeShort((short) t);
584 } else {
585 writeByte((byte) 3);
586 writeShort((short) t);
587 writeInt(srid);
588 }
589 }
590 }
591 }
592
593 private void writeTypeInfoRow(TypeInfo type) throws IOException {
594 Set<Map.Entry<String, TypeInfo>> fields = ((ExtTypeInfoRow) type.getExtTypeInfo()).getFields();
595 writeInt(fields.size());
596 for (Map.Entry<String, TypeInfo> field : fields) {
597 writeString(field.getKey()).writeTypeInfo(field.getValue());
598 }
599 }
600
601 private void writeTypeInfo19(TypeInfo type) throws IOException {
602 int valueType = type.getValueType();
603 switch (valueType) {
604 case Value.BINARY:
605 valueType = Value.VARBINARY;
606 break;
607 case Value.DECFLOAT:
608 valueType = Value.NUMERIC;
609 break;
610 }
611 writeInt(VALUE_TO_TI[valueType + 1]).writeLong(type.getPrecision()).writeInt(type.getScale());
612 }
613
614 /**
615 * Read a type information.
616 *
617 * @return the type information
618 * @throws IOException on failure
619 */
620 public TypeInfo readTypeInfo() throws IOException {
621 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
622 return readTypeInfo20();
623 } else {
624 return readTypeInfo19();
625 }
626 }
627
628 private TypeInfo readTypeInfo20() throws IOException {
629 int valueType = TI_TO_VALUE[readInt() + 1];
630 long precision = -1L;
631 int scale = -1;
632 ExtTypeInfo ext = null;
633 switch (valueType) {
634 case Value.UNKNOWN:
635 case Value.NULL:
636 case Value.BOOLEAN:
637 case Value.TINYINT:
638 case Value.SMALLINT:
639 case Value.INTEGER:
640 case Value.BIGINT:
641 case Value.DATE:
642 case Value.UUID:
643 break;
644 case Value.CHAR:
645 case Value.VARCHAR:
646 case Value.VARCHAR_IGNORECASE:
647 case Value.BINARY:
648 case Value.VARBINARY:
649 case Value.DECFLOAT:
650 case Value.JAVA_OBJECT:
651 case Value.JSON:
652 precision = readInt();
653 break;
654 case Value.CLOB:
655 case Value.BLOB:
656 precision = readLong();
657 break;
658 case Value.NUMERIC:
659 precision = readInt();
660 scale = readInt();
661 if (readBoolean()) {
662 ext = ExtTypeInfoNumeric.DECIMAL;
663 }
664 break;
665 case Value.REAL:
666 case Value.DOUBLE:
667 case Value.INTERVAL_YEAR:
668 case Value.INTERVAL_MONTH:
669 case Value.INTERVAL_DAY:
670 case Value.INTERVAL_HOUR:
671 case Value.INTERVAL_MINUTE:
672 case Value.INTERVAL_YEAR_TO_MONTH:
673 case Value.INTERVAL_DAY_TO_HOUR:
674 case Value.INTERVAL_DAY_TO_MINUTE:
675 case Value.INTERVAL_HOUR_TO_MINUTE:
676 precision = readByte();
677 break;
678 case Value.TIME:
679 case Value.TIME_TZ:
680 case Value.TIMESTAMP:
681 case Value.TIMESTAMP_TZ:
682 scale = readByte();
683 break;
684 case Value.INTERVAL_SECOND:
685 case Value.INTERVAL_DAY_TO_SECOND:
686 case Value.INTERVAL_HOUR_TO_SECOND:
687 case Value.INTERVAL_MINUTE_TO_SECOND:
688 precision = readByte();
689 scale = readByte();
690 break;
691 case Value.ENUM:
692 ext = readTypeInfoEnum();
693 break;
694 case Value.GEOMETRY:
695 ext = readTypeInfoGeometry();
696 break;
697 case Value.ARRAY:
698 precision = readInt();
699 ext = readTypeInfo();
700 break;
701 case Value.ROW:
702 ext = readTypeInfoRow();
703 break;
704 default:
705 throw DbException.getUnsupportedException("value type " + valueType);
706 }
707 return TypeInfo.getTypeInfo(valueType, precision, scale, ext);
708 }
709
710 private ExtTypeInfo readTypeInfoEnum() throws IOException {
711 ExtTypeInfo ext;
712 int c = readInt();
713 if (c > 0) {
714 String[] enumerators = new String[c];
715 for (int i = 0; i < c; i++) {
716 enumerators[i] = readString();
717 }
718 ext = new ExtTypeInfoEnum(enumerators);
719 } else {
720 ext = null;
721 }
722 return ext;
723 }
724
725 private ExtTypeInfo readTypeInfoGeometry() throws IOException {
726 ExtTypeInfo ext;
727 int e = readByte();
728 switch (e) {
729 case 0:
730 ext = null;
731 break;
732 case 1:
733 ext = new ExtTypeInfoGeometry(readShort(), null);
734 break;
735 case 2:
736 ext = new ExtTypeInfoGeometry(0, readInt());
737 break;
738 case 3:
739 ext = new ExtTypeInfoGeometry(readShort(), readInt());
740 break;
741 default:
742 throw DbException.getUnsupportedException("GEOMETRY type encoding " + e);
743 }
744 return ext;
745 }
746
747 private ExtTypeInfo readTypeInfoRow() throws IOException {
748 LinkedHashMap<String, TypeInfo> fields = new LinkedHashMap<>();
749 for (int i = 0, l = readInt(); i < l; i++) {
750 String name = readString();
751 if (fields.putIfAbsent(name, readTypeInfo()) != null) {
752 throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1, name);
753 }
754 }
755 return new ExtTypeInfoRow(fields);
756 }
757
758 private TypeInfo readTypeInfo19() throws IOException {
759 return TypeInfo.getTypeInfo(TI_TO_VALUE[readInt() + 1], readLong(), readInt(), null);
760 }
761
762 /**
763 * Write a value.
764 *
765 * @param v the value
766 * @throws IOException on failure
767 */
768 public void writeValue(Value v) throws IOException {
769 int type = v.getValueType();
770 switch (type) {
771 case Value.NULL:
772 writeInt(NULL);
773 break;
774 case Value.BINARY:
775 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
776 writeInt(BINARY);
777 writeBytes(v.getBytesNoCopy());
778 break;
779 }
780 //$FALL-THROUGH$
781 case Value.VARBINARY:
782 writeInt(VARBINARY);
783 writeBytes(v.getBytesNoCopy());
784 break;
785 case Value.JAVA_OBJECT:
786 writeInt(JAVA_OBJECT);
787 writeBytes(v.getBytesNoCopy());
788 break;
789 case Value.UUID: {
790 writeInt(UUID);
791 ValueUuid uuid = (ValueUuid) v;
792 writeLong(uuid.getHigh());
793 writeLong(uuid.getLow());
794 break;
795 }
796 case Value.BOOLEAN:
797 writeInt(BOOLEAN);
798 writeBoolean(v.getBoolean());
799 break;
800 case Value.TINYINT:
801 writeInt(TINYINT);
802 writeByte(v.getByte());
803 break;
804 case Value.TIME:
805 writeInt(TIME);
806 writeLong(((ValueTime) v).getNanos());
807 break;
808 case Value.TIME_TZ: {
809 ValueTimeTimeZone t = (ValueTimeTimeZone) v;
810 if (version >= Constants.TCP_PROTOCOL_VERSION_19) {
811 writeInt(TIME_TZ);
812 writeLong(t.getNanos());
813 writeInt(t.getTimeZoneOffsetSeconds());
814 } else {
815 writeInt(TIME);
816 /*
817 * Don't call SessionRemote.currentTimestamp(), it may require
818 * own remote call and old server will not return custom time
819 * zone anyway.
820 */
821 ValueTimestampTimeZone current = session.isRemote()
822 ? DateTimeUtils.currentTimestamp(DateTimeUtils.getTimeZone()) : session.currentTimestamp();
823 writeLong(DateTimeUtils.normalizeNanosOfDay(t.getNanos() +
824 (t.getTimeZoneOffsetSeconds() - current.getTimeZoneOffsetSeconds())
825 * DateTimeUtils.NANOS_PER_DAY));
826 }
827 break;
828 }
829 case Value.DATE:
830 writeInt(DATE);
831 writeLong(((ValueDate) v).getDateValue());
832 break;
833 case Value.TIMESTAMP: {
834 writeInt(TIMESTAMP);
835 ValueTimestamp ts = (ValueTimestamp) v;
836 writeLong(ts.getDateValue());
837 writeLong(ts.getTimeNanos());
838 break;
839 }
840 case Value.TIMESTAMP_TZ: {
841 writeInt(TIMESTAMP_TZ);
842 ValueTimestampTimeZone ts = (ValueTimestampTimeZone) v;
843 writeLong(ts.getDateValue());
844 writeLong(ts.getTimeNanos());
845 int timeZoneOffset = ts.getTimeZoneOffsetSeconds();
846 writeInt(version >= Constants.TCP_PROTOCOL_VERSION_19 //
847 ? timeZoneOffset : timeZoneOffset / 60);
848 break;
849 }
850 case Value.DECFLOAT:
851 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
852 writeInt(DECFLOAT);
853 writeString(v.getString());
854 break;
855 }
856 //$FALL-THROUGH$
857 case Value.NUMERIC:
858 writeInt(NUMERIC);
859 writeString(v.getString());
860 break;
861 case Value.DOUBLE:
862 writeInt(DOUBLE);
863 writeDouble(v.getDouble());
864 break;
865 case Value.REAL:
866 writeInt(REAL);
867 writeFloat(v.getFloat());
868 break;
869 case Value.INTEGER:
870 writeInt(INTEGER);
871 writeInt(v.getInt());
872 break;
873 case Value.BIGINT:
874 writeInt(BIGINT);
875 writeLong(v.getLong());
876 break;
877 case Value.SMALLINT:
878 writeInt(SMALLINT);
879 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
880 writeShort(v.getShort());
881 } else {
882 writeInt(v.getShort());
883 }
884 break;
885 case Value.VARCHAR:
886 writeInt(VARCHAR);
887 writeString(v.getString());
888 break;
889 case Value.VARCHAR_IGNORECASE:
890 writeInt(VARCHAR_IGNORECASE);
891 writeString(v.getString());
892 break;
893 case Value.CHAR:
894 writeInt(CHAR);
895 writeString(v.getString());
896 break;
897 case Value.BLOB: {
898 writeInt(BLOB);
899 ValueBlob lob = (ValueBlob) v;
900 LobData lobData = lob.getLobData();
901 long length = lob.octetLength();
902 if (lobData instanceof LobDataDatabase) {
903 LobDataDatabase lobDataDatabase = (LobDataDatabase) lobData;
904 writeLong(-1);
905 writeInt(lobDataDatabase.getTableId());
906 writeLong(lobDataDatabase.getLobId());
907 writeBytes(calculateLobMac(lobDataDatabase.getLobId()));
908 writeLong(length);
909 break;
910 }
911 if (length < 0) {
912 throw DbException.get(
913 ErrorCode.CONNECTION_BROKEN_1, "length=" + length);
914 }
915 writeLong(length);
916 long written = IOUtils.copyAndCloseInput(lob.getInputStream(), out);
917 if (written != length) {
918 throw DbException.get(
919 ErrorCode.CONNECTION_BROKEN_1, "length:" + length + " written:" + written);
920 }
921 writeInt(LOB_MAGIC);
922 break;
923 }
924 case Value.CLOB: {
925 writeInt(CLOB);
926 ValueClob lob = (ValueClob) v;
927 LobData lobData = lob.getLobData();
928 long charLength = lob.charLength();
929 if (lobData instanceof LobDataDatabase) {
930 LobDataDatabase lobDataDatabase = (LobDataDatabase) lobData;
931 writeLong(-1);
932 writeInt(lobDataDatabase.getTableId());
933 writeLong(lobDataDatabase.getLobId());
934 writeBytes(calculateLobMac(lobDataDatabase.getLobId()));
935 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
936 writeLong(lob.octetLength());
937 }
938 writeLong(charLength);
939 break;
940 }
941 if (charLength < 0) {
942 throw DbException.get(
943 ErrorCode.CONNECTION_BROKEN_1, "length=" + charLength);
944 }
945 writeLong(charLength);
946 Reader reader = lob.getReader();
947 Data.copyString(reader, out);
948 writeInt(LOB_MAGIC);
949 break;
950 }
951 case Value.ARRAY: {
952 writeInt(ARRAY);
953 ValueArray va = (ValueArray) v;
954 Value[] list = va.getList();
955 int len = list.length;
956 writeInt(len);
957 for (Value value : list) {
958 writeValue(value);
959 }
960 break;
961 }
962 case Value.ROW: {
963 writeInt(version >= Constants.TCP_PROTOCOL_VERSION_18 ? ROW : ARRAY);
964 ValueRow va = (ValueRow) v;
965 Value[] list = va.getList();
966 int len = list.length;
967 writeInt(len);
968 for (Value value : list) {
969 writeValue(value);
970 }
971 break;
972 }
973 case Value.ENUM: {
974 writeInt(ENUM);
975 writeInt(v.getInt());
976 if (version < Constants.TCP_PROTOCOL_VERSION_20) {
977 writeString(v.getString());
978 }
979 break;
980 }
981 case Value.GEOMETRY:
982 writeInt(GEOMETRY);
983 writeBytes(v.getBytesNoCopy());
984 break;
985 case Value.INTERVAL_YEAR:
986 case Value.INTERVAL_MONTH:
987 case Value.INTERVAL_DAY:
988 case Value.INTERVAL_HOUR:
989 case Value.INTERVAL_MINUTE:
990 if (version >= Constants.TCP_PROTOCOL_VERSION_18) {
991 ValueInterval interval = (ValueInterval) v;
992 int ordinal = type - Value.INTERVAL_YEAR;
993 if (interval.isNegative()) {
994 ordinal = ~ordinal;
995 }
996 writeInt(INTERVAL);
997 writeByte((byte) ordinal);
998 writeLong(interval.getLeading());
999 } else {
1000 writeInt(VARCHAR);
1001 writeString(v.getString());
1002 }
1003 break;
1004 case Value.INTERVAL_SECOND:
1005 case Value.INTERVAL_YEAR_TO_MONTH:
1006 case Value.INTERVAL_DAY_TO_HOUR:
1007 case Value.INTERVAL_DAY_TO_MINUTE:
1008 case Value.INTERVAL_DAY_TO_SECOND:
1009 case Value.INTERVAL_HOUR_TO_MINUTE:
1010 case Value.INTERVAL_HOUR_TO_SECOND:
1011 case Value.INTERVAL_MINUTE_TO_SECOND:
1012 if (version >= Constants.TCP_PROTOCOL_VERSION_18) {
1013 ValueInterval interval = (ValueInterval) v;
1014 int ordinal = type - Value.INTERVAL_YEAR;
1015 if (interval.isNegative()) {
1016 ordinal = ~ordinal;
1017 }
1018 writeInt(INTERVAL);
1019 writeByte((byte) ordinal);
1020 writeLong(interval.getLeading());
1021 writeLong(interval.getRemaining());
1022 } else {
1023 writeInt(VARCHAR);
1024 writeString(v.getString());
1025 }
1026 break;
1027 case Value.JSON: {
1028 writeInt(JSON);
1029 writeBytes(v.getBytesNoCopy());
1030 break;
1031 }
1032 default:
1033 throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "type=" + type);
1034 }
1035 }
1036
1037 /**
1038 * Read a value.
1039 *
1040 * @param columnType the data type of value, or {@code null}
1041 * @return the value
1042 * @throws IOException on failure
1043 */
1044 public Value readValue(TypeInfo columnType) throws IOException {
1045 int type = readInt();
1046 switch (type) {
1047 case NULL:
1048 return ValueNull.INSTANCE;
1049 case VARBINARY:
1050 return ValueVarbinary.getNoCopy(readBytes());
1051 case BINARY:
1052 return ValueBinary.getNoCopy(readBytes());
1053 case UUID:
1054 return ValueUuid.get(readLong(), readLong());
1055 case JAVA_OBJECT:
1056 return ValueJavaObject.getNoCopy(readBytes());
1057 case BOOLEAN:
1058 return ValueBoolean.get(readBoolean());
1059 case TINYINT:
1060 return ValueTinyint.get(readByte());
1061 case DATE:
1062 return ValueDate.fromDateValue(readLong());
1063 case TIME:
1064 return ValueTime.fromNanos(readLong());
1065 case TIME_TZ:
1066 return ValueTimeTimeZone.fromNanos(readLong(), readInt());
1067 case TIMESTAMP:
1068 return ValueTimestamp.fromDateValueAndNanos(readLong(), readLong());
1069 case TIMESTAMP_TZ: {
1070 long dateValue = readLong(), timeNanos = readLong();
1071 int timeZoneOffset = readInt();
1072 return ValueTimestampTimeZone.fromDateValueAndNanos(dateValue, timeNanos,
1073 version >= Constants.TCP_PROTOCOL_VERSION_19 ? timeZoneOffset : timeZoneOffset * 60);
1074 }
1075 case NUMERIC:
1076 return ValueNumeric.get(new BigDecimal(readString()));
1077 case DOUBLE:
1078 return ValueDouble.get(readDouble());
1079 case REAL:
1080 return ValueReal.get(readFloat());
1081 case ENUM: {
1082 int ordinal = readInt();
1083 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
1084 return ((ExtTypeInfoEnum) columnType.getExtTypeInfo()).getValue(ordinal, session);
1085 }
1086 return ValueEnumBase.get(readString(), ordinal);
1087 }
1088 case INTEGER:
1089 return ValueInteger.get(readInt());
1090 case BIGINT:
1091 return ValueBigint.get(readLong());
1092 case SMALLINT:
1093 if (version >= Constants.TCP_PROTOCOL_VERSION_20) {
1094 return ValueSmallint.get(readShort());
1095 } else {
1096 return ValueSmallint.get((short) readInt());
1097 }
1098 case VARCHAR:
1099 return ValueVarchar.get(readString());
1100 case VARCHAR_IGNORECASE:
1101 return ValueVarcharIgnoreCase.get(readString());
1102 case CHAR:
1103 return ValueChar.get(readString());
1104 case BLOB: {
1105 long length = readLong();
1106 if (length == -1) {
1107 // fetch-on-demand LOB
1108 int tableId = readInt();
1109 long id = readLong();
1110 byte[] hmac = readBytes();
1111 long precision = readLong();
1112 return new ValueBlob(new LobDataFetchOnDemand(session.getDataHandler(), tableId, id, hmac), precision);
1113 }
1114 Value v = session.getDataHandler().getLobStorage().createBlob(in, length);
1115 int magic = readInt();
1116 if (magic != LOB_MAGIC) {
1117 throw DbException.get(
1118 ErrorCode.CONNECTION_BROKEN_1, "magic=" + magic);
1119 }
1120 return v;
1121 }
1122 case CLOB: {
1123 long charLength = readLong();
1124 if (charLength == -1) {
1125 // fetch-on-demand LOB
1126 int tableId = readInt();
1127 long id = readLong();
1128 byte[] hmac = readBytes();
1129 long octetLength = version >= Constants.TCP_PROTOCOL_VERSION_20 ? readLong() : -1L;
1130 charLength = readLong();
1131 return new ValueClob(new LobDataFetchOnDemand(session.getDataHandler(), tableId, id, hmac),
1132 octetLength, charLength);
1133 }
1134 if (charLength < 0) {
1135 throw DbException.get(
1136 ErrorCode.CONNECTION_BROKEN_1, "length="+ charLength);
1137 }
1138 Value v = session.getDataHandler().getLobStorage().
1139 createClob(new DataReader(in), charLength);
1140 int magic = readInt();
1141 if (magic != LOB_MAGIC) {
1142 throw DbException.get(
1143 ErrorCode.CONNECTION_BROKEN_1, "magic=" + magic);
1144 }
1145 return v;
1146 }
1147 case ARRAY: {
1148 int len = readInt();
1149 if (len < 0) {
1150 // Unlikely, but possible with H2 1.4.200 and older versions
1151 len = ~len;
1152 readString();
1153 }
1154 if (columnType != null) {
1155 TypeInfo elementType = (TypeInfo) columnType.getExtTypeInfo();
1156 return ValueArray.get(elementType, readArrayElements(len, elementType), session);
1157 }
1158 return ValueArray.get(readArrayElements(len, null), session);
1159 }
1160 case ROW: {
1161 int len = readInt();
1162 Value[] list = new Value[len];
1163 if (columnType != null) {
1164 ExtTypeInfoRow extTypeInfoRow = (ExtTypeInfoRow) columnType.getExtTypeInfo();
1165 Iterator<Entry<String, TypeInfo>> fields = extTypeInfoRow.getFields().iterator();
1166 for (int i = 0; i < len; i++) {
1167 list[i] = readValue(fields.next().getValue());
1168 }
1169 return ValueRow.get(columnType, list);
1170 }
1171 for (int i = 0; i < len; i++) {
1172 list[i] = readValue(null);
1173 }
1174 return ValueRow.get(list);
1175 }
1176 case GEOMETRY:
1177 return ValueGeometry.get(readBytes());
1178 case INTERVAL: {
1179 int ordinal = readByte();
1180 boolean negative = ordinal < 0;
1181 if (negative) {
1182 ordinal = ~ordinal;
1183 }
1184 return ValueInterval.from(IntervalQualifier.valueOf(ordinal), negative, readLong(),
1185 ordinal < 5 ? 0 : readLong());
1186 }
1187 case JSON:
1188 // Do not trust the value
1189 return ValueJson.fromJson(readBytes());
1190 case DECFLOAT: {
1191 String s = readString();
1192 switch (s) {
1193 case "-Infinity":
1194 return ValueDecfloat.NEGATIVE_INFINITY;
1195 case "Infinity":
1196 return ValueDecfloat.POSITIVE_INFINITY;
1197 case "NaN":
1198 return ValueDecfloat.NAN;
1199 default:
1200 return ValueDecfloat.get(new BigDecimal(s));
1201 }
1202 }
1203 default:
1204 throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "type=" + type);
1205 }
1206 }
1207
1208 private Value[] readArrayElements(int len, TypeInfo elementType) throws IOException {
1209 Value[] list = new Value[len];
1210 for (int i = 0; i < len; i++) {
1211 list[i] = readValue(elementType);
1212 }
1213 return list;
1214 }
1215
1216 /**
1217 * Read a row count.
1218 *
1219 * @return the row count
1220 * @throws IOException on failure
1221 */
1222 public long readRowCount() throws IOException {
1223 return version >= Constants.TCP_PROTOCOL_VERSION_20 ? readLong() : readInt();
1224 }
1225
1226 /**
1227 * Write a row count.
1228 *
1229 * @param rowCount the row count
1230 * @return itself
1231 * @throws IOException on failure
1232 */
1233 public Transfer writeRowCount(long rowCount) throws IOException {
1234 return version >= Constants.TCP_PROTOCOL_VERSION_20 ? writeLong(rowCount)
1235 : writeInt(rowCount < Integer.MAX_VALUE ? (int) rowCount : Integer.MAX_VALUE);
1236 }
1237
1238 /**
1239 * Get the socket.
1240 *
1241 * @return the socket
1242 */
1243 public Socket getSocket() {
1244 return socket;
1245 }
1246
1247 /**
1248 * Set the session.
1249 *
1250 * @param session the session
1251 */
1252 public void setSession(Session session) {
1253 this.session = session;
1254 }
1255
1256 /**
1257 * Enable or disable SSL.
1258 *
1259 * @param ssl the new value
1260 */
1261 public void setSSL(boolean ssl) {
1262 this.ssl = ssl;
1263 }
1264
1265 /**
1266 * Open a new connection to the same address and port as this one.
1267 *
1268 * @return the new transfer object
1269 * @throws IOException on failure
1270 */
1271 public Transfer openNewConnection() throws IOException {
1272 InetAddress address = socket.getInetAddress();
1273 int port = socket.getPort();
1274 Socket s2 = NetUtils.createSocket(address, port, ssl);
1275 Transfer trans = new Transfer(null, s2);
1276 trans.setSSL(ssl);
1277 return trans;
1278 }
1279
1280 public void setVersion(int version) {
1281 this.version = version;
1282 }
1283
1284 public int getVersion() {
1285 return version;
1286 }
1287
1288 public synchronized boolean isClosed() {
1289 return socket == null || socket.isClosed();
1290 }
1291
1292 /**
1293 * Verify the HMAC.
1294 *
1295 * @param hmac the message authentication code
1296 * @param lobId the lobId
1297 * @throws DbException if the HMAC does not match
1298 */
1299 public void verifyLobMac(byte[] hmac, long lobId) {
1300 byte[] result = calculateLobMac(lobId);
1301 if (!Utils.compareSecure(hmac, result)) {
1302 throw DbException.get(ErrorCode.CONNECTION_BROKEN_1,
1303 "Invalid lob hmac; possibly the connection was re-opened internally");
1304 }
1305 }
1306
1307 private byte[] calculateLobMac(long lobId) {
1308 if (lobMacSalt == null) {
1309 lobMacSalt = MathUtils.secureRandomBytes(LOB_MAC_SALT_LENGTH);
1310 }
1311 byte[] data = new byte[8];
1312 Bits.writeLong(data, 0, lobId);
1313 return SHA256.getHashWithSalt(data, lobMacSalt);
1314 }
1315
1316 }