MysqlIO.java
201 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
/*
Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; version 2
of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.jdbc;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.ref.SoftReference;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.Deflater;
import com.mysql.jdbc.authentication.MysqlClearPasswordPlugin;
import com.mysql.jdbc.authentication.MysqlNativePasswordPlugin;
import com.mysql.jdbc.authentication.MysqlOldPasswordPlugin;
import com.mysql.jdbc.authentication.Sha256PasswordPlugin;
import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;
import com.mysql.jdbc.exceptions.MySQLTimeoutException;
import com.mysql.jdbc.log.LogUtils;
import com.mysql.jdbc.profiler.ProfilerEvent;
import com.mysql.jdbc.profiler.ProfilerEventHandler;
import com.mysql.jdbc.util.ReadAheadInputStream;
import com.mysql.jdbc.util.ResultSetUtil;
/**
* This class is used by Connection for communicating with the MySQL server.
*/
public class MysqlIO {
private static final String CODE_PAGE_1252 = "Cp1252";
protected static final int NULL_LENGTH = ~0;
protected static final int COMP_HEADER_LENGTH = 3;
protected static final int MIN_COMPRESS_LEN = 50;
protected static final int HEADER_LENGTH = 4;
protected static final int AUTH_411_OVERHEAD = 33;
public static final int SEED_LENGTH = 20;
private static int maxBufferSize = 65535;
private static final String NONE = "none";
private static final int CLIENT_LONG_PASSWORD = 0x00000001; /* new more secure passwords */
private static final int CLIENT_FOUND_ROWS = 0x00000002;
private static final int CLIENT_LONG_FLAG = 0x00000004; /* Get all column flags */
protected static final int CLIENT_CONNECT_WITH_DB = 0x00000008;
private static final int CLIENT_COMPRESS = 0x00000020; /* Can use compression protcol */
private static final int CLIENT_LOCAL_FILES = 0x00000080; /* Can use LOAD DATA LOCAL */
private static final int CLIENT_PROTOCOL_41 = 0x00000200; // for > 4.1.1
private static final int CLIENT_INTERACTIVE = 0x00000400;
protected static final int CLIENT_SSL = 0x00000800;
private static final int CLIENT_TRANSACTIONS = 0x00002000; // Client knows about transactions
protected static final int CLIENT_RESERVED = 0x00004000; // for 4.1.0 only
protected static final int CLIENT_SECURE_CONNECTION = 0x00008000;
private static final int CLIENT_MULTI_STATEMENTS = 0x00010000; // Enable/disable multiquery support
private static final int CLIENT_MULTI_RESULTS = 0x00020000; // Enable/disable multi-results
private static final int CLIENT_PLUGIN_AUTH = 0x00080000;
private static final int CLIENT_CONNECT_ATTRS = 0x00100000;
private static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x00200000;
private static final int CLIENT_CAN_HANDLE_EXPIRED_PASSWORD = 0x00400000;
private static final int CLIENT_SESSION_TRACK = 0x00800000;
private static final int CLIENT_DEPRECATE_EOF = 0x01000000;
private static final int SERVER_STATUS_IN_TRANS = 1;
private static final int SERVER_STATUS_AUTOCOMMIT = 2; // Server in auto_commit mode
static final int SERVER_MORE_RESULTS_EXISTS = 8; // Multi query - next query exists
private static final int SERVER_QUERY_NO_GOOD_INDEX_USED = 16;
private static final int SERVER_QUERY_NO_INDEX_USED = 32;
private static final int SERVER_QUERY_WAS_SLOW = 2048;
private static final int SERVER_STATUS_CURSOR_EXISTS = 64;
private static final String FALSE_SCRAMBLE = "xxxxxxxx";
protected static final int MAX_QUERY_SIZE_TO_LOG = 1024; // truncate logging of queries at 1K
protected static final int MAX_QUERY_SIZE_TO_EXPLAIN = 1024 * 1024; // don't explain queries above 1MB
protected static final int INITIAL_PACKET_SIZE = 1024;
/**
* We store the platform 'encoding' here, only used to avoid munging filenames for LOAD DATA LOCAL INFILE...
*/
private static String jvmPlatformCharset = null;
/**
* We need to have a 'marker' for all-zero datetimes so that ResultSet can decide what to do based on connection setting
*/
protected final static String ZERO_DATE_VALUE_MARKER = "0000-00-00";
protected final static String ZERO_DATETIME_VALUE_MARKER = "0000-00-00 00:00:00";
private static final String EXPLAINABLE_STATEMENT = "SELECT";
private static final String[] EXPLAINABLE_STATEMENT_EXTENSION = new String[] { "INSERT", "UPDATE", "REPLACE", "DELETE" };
static {
OutputStreamWriter outWriter = null;
//
// Use the I/O system to get the encoding (if possible), to avoid security restrictions on System.getProperty("file.encoding") in applets (why is that
// restricted?)
//
try {
outWriter = new OutputStreamWriter(new ByteArrayOutputStream());
jvmPlatformCharset = outWriter.getEncoding();
} finally {
try {
if (outWriter != null) {
outWriter.close();
}
} catch (IOException ioEx) {
// ignore
}
}
}
/** Max number of bytes to dump when tracing the protocol */
private final static int MAX_PACKET_DUMP_LENGTH = 1024;
private boolean packetSequenceReset = false;
protected int serverCharsetIndex;
//
// Use this when reading in rows to avoid thousands of new() calls, because the byte arrays just get copied out of the packet anyway
//
private Buffer reusablePacket = null;
private Buffer sendPacket = null;
private Buffer sharedSendPacket = null;
/** Data to the server */
protected BufferedOutputStream mysqlOutput = null;
protected MySQLConnection connection;
private Deflater deflater = null;
protected InputStream mysqlInput = null;
private LinkedList<StringBuilder> packetDebugRingBuffer = null;
private RowData streamingData = null;
/** The connection to the server */
public Socket mysqlConnection = null;
protected SocketFactory socketFactory = null;
//
// Packet used for 'LOAD DATA LOCAL INFILE'
//
// We use a SoftReference, so that we don't penalize intermittent use of this feature
//
private SoftReference<Buffer> loadFileBufRef;
//
// Used to send large packets to the server versions 4+
// We use a SoftReference, so that we don't penalize intermittent use of this feature
//
private SoftReference<Buffer> splitBufRef;
private SoftReference<Buffer> compressBufRef;
protected String host = null;
protected String seed;
private String serverVersion = null;
private String socketFactoryClassName = null;
private byte[] packetHeaderBuf = new byte[4];
private boolean colDecimalNeedsBump = false; // do we need to increment the colDecimal flag?
private boolean hadWarnings = false;
private boolean has41NewNewProt = false;
/** Does the server support long column info? */
private boolean hasLongColumnInfo = false;
private boolean isInteractiveClient = false;
private boolean logSlowQueries = false;
/**
* Does the character set of this connection match the character set of the
* platform
*/
private boolean platformDbCharsetMatches = true; // changed once we've connected.
private boolean profileSql = false;
private boolean queryBadIndexUsed = false;
private boolean queryNoIndexUsed = false;
private boolean serverQueryWasSlow = false;
/** Should we use 4.1 protocol extensions? */
private boolean use41Extensions = false;
private boolean useCompression = false;
private boolean useNewLargePackets = false;
private boolean useNewUpdateCounts = false; // should we use the new larger update counts?
private byte packetSequence = 0;
private byte compressedPacketSequence = 0;
private byte readPacketSequence = -1;
private boolean checkPacketSequence = false;
private byte protocolVersion = 0;
private int maxAllowedPacket = 1024 * 1024;
protected int maxThreeBytes = 255 * 255 * 255;
protected int port = 3306;
protected int serverCapabilities;
private int serverMajorVersion = 0;
private int serverMinorVersion = 0;
private int oldServerStatus = 0;
private int serverStatus = 0;
private int serverSubMinorVersion = 0;
private int warningCount = 0;
protected long clientParam = 0;
protected long lastPacketSentTimeMs = 0;
protected long lastPacketReceivedTimeMs = 0;
private boolean traceProtocol = false;
private boolean enablePacketDebug = false;
private boolean useConnectWithDb;
private boolean needToGrabQueryFromPacket;
private boolean autoGenerateTestcaseScript;
private long threadId;
private boolean useNanosForElapsedTime;
private long slowQueryThreshold;
private String queryTimingUnits;
private boolean useDirectRowUnpack = true;
private int useBufferRowSizeThreshold;
private int commandCount = 0;
private List<StatementInterceptorV2> statementInterceptors;
private ExceptionInterceptor exceptionInterceptor;
private int authPluginDataLength = 0;
/**
* Constructor: Connect to the MySQL server and setup a stream connection.
*
* @param host
* the hostname to connect to
* @param port
* the port number that the server is listening on
* @param props
* the Properties from DriverManager.getConnection()
* @param socketFactoryClassName
* the socket factory to use
* @param conn
* the Connection that is creating us
* @param socketTimeout
* the timeout to set for the socket (0 means no
* timeout)
*
* @throws IOException
* if an IOException occurs during connect.
* @throws SQLException
* if a database access error occurs.
*/
public MysqlIO(String host, int port, Properties props, String socketFactoryClassName, MySQLConnection conn, int socketTimeout,
int useBufferRowSizeThreshold) throws IOException, SQLException {
this.connection = conn;
if (this.connection.getEnablePacketDebug()) {
this.packetDebugRingBuffer = new LinkedList<StringBuilder>();
}
this.traceProtocol = this.connection.getTraceProtocol();
this.useAutoSlowLog = this.connection.getAutoSlowLog();
this.useBufferRowSizeThreshold = useBufferRowSizeThreshold;
this.useDirectRowUnpack = this.connection.getUseDirectRowUnpack();
this.logSlowQueries = this.connection.getLogSlowQueries();
this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE);
this.sendPacket = new Buffer(INITIAL_PACKET_SIZE);
this.port = port;
this.host = host;
this.socketFactoryClassName = socketFactoryClassName;
this.socketFactory = createSocketFactory();
this.exceptionInterceptor = this.connection.getExceptionInterceptor();
try {
this.mysqlConnection = this.socketFactory.connect(this.host, this.port, props);
if (socketTimeout != 0) {
try {
this.mysqlConnection.setSoTimeout(socketTimeout);
} catch (Exception ex) {
/* Ignore if the platform does not support it */
}
}
this.mysqlConnection = this.socketFactory.beforeHandshake();
if (this.connection.getUseReadAheadInput()) {
this.mysqlInput = new ReadAheadInputStream(this.mysqlConnection.getInputStream(), 16384, this.connection.getTraceProtocol(),
this.connection.getLog());
} else if (this.connection.useUnbufferedInput()) {
this.mysqlInput = this.mysqlConnection.getInputStream();
} else {
this.mysqlInput = new BufferedInputStream(this.mysqlConnection.getInputStream(), 16384);
}
this.mysqlOutput = new BufferedOutputStream(this.mysqlConnection.getOutputStream(), 16384);
this.isInteractiveClient = this.connection.getInteractiveClient();
this.profileSql = this.connection.getProfileSql();
this.autoGenerateTestcaseScript = this.connection.getAutoGenerateTestcaseScript();
this.needToGrabQueryFromPacket = (this.profileSql || this.logSlowQueries || this.autoGenerateTestcaseScript);
if (this.connection.getUseNanosForElapsedTime() && TimeUtil.nanoTimeAvailable()) {
this.useNanosForElapsedTime = true;
this.queryTimingUnits = Messages.getString("Nanoseconds");
} else {
this.queryTimingUnits = Messages.getString("Milliseconds");
}
if (this.connection.getLogSlowQueries()) {
calculateSlowQueryThreshold();
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, 0, 0, ioEx, getExceptionInterceptor());
}
}
/**
* Does the server send back extra column info?
*
* @return true if so
*/
public boolean hasLongColumnInfo() {
return this.hasLongColumnInfo;
}
protected boolean isDataAvailable() throws SQLException {
try {
return this.mysqlInput.available() > 0;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* @return Returns the lastPacketSentTimeMs.
*/
protected long getLastPacketSentTimeMs() {
return this.lastPacketSentTimeMs;
}
protected long getLastPacketReceivedTimeMs() {
return this.lastPacketReceivedTimeMs;
}
/**
* Build a result set. Delegates to buildResultSetWithRows() to build a
* JDBC-version-specific ResultSet, given rows as byte data, and field
* information.
*
* @param callingStatement
* @param columnCount
* the number of columns in the result set
* @param maxRows
* the maximum number of rows to read (-1 means all rows)
* @param resultSetType
* (TYPE_FORWARD_ONLY, TYPE_SCROLL_????)
* @param resultSetConcurrency
* the type of result set (CONCUR_UPDATABLE or
* READ_ONLY)
* @param streamResults
* should the result set be read all at once, or
* streamed?
* @param catalog
* the database name in use when the result set was created
* @param isBinaryEncoded
* is this result set in native encoding?
* @param unpackFieldInfo
* should we read MYSQL_FIELD info (if available)?
*
* @return a result set
*
* @throws SQLException
* if a database access error occurs
*/
protected ResultSetImpl getResultSet(StatementImpl callingStatement, long columnCount, int maxRows, int resultSetType, int resultSetConcurrency,
boolean streamResults, String catalog, boolean isBinaryEncoded, Field[] metadataFromCache) throws SQLException {
Buffer packet; // The packet from the server
Field[] fields = null;
// Read in the column information
if (metadataFromCache == null /* we want the metadata from the server */) {
fields = new Field[(int) columnCount];
for (int i = 0; i < columnCount; i++) {
Buffer fieldPacket = null;
fieldPacket = readPacket();
fields[i] = unpackField(fieldPacket, false);
}
} else {
for (int i = 0; i < columnCount; i++) {
skipPacket();
}
}
// There is no EOF packet after fields when CLIENT_DEPRECATE_EOF is set
if (!isEOFDeprecated() ||
// if we asked to use cursor then there should be an OK packet here
(this.connection.versionMeetsMinimum(5, 0, 2) && callingStatement != null && isBinaryEncoded && callingStatement.isCursorRequired())) {
packet = reuseAndReadPacket(this.reusablePacket);
readServerStatusForResultSets(packet);
}
//
// Handle cursor-based fetch first
//
if (this.connection.versionMeetsMinimum(5, 0, 2) && this.connection.getUseCursorFetch() && isBinaryEncoded && callingStatement != null
&& callingStatement.getFetchSize() != 0 && callingStatement.getResultSetType() == ResultSet.TYPE_FORWARD_ONLY) {
ServerPreparedStatement prepStmt = (com.mysql.jdbc.ServerPreparedStatement) callingStatement;
boolean usingCursor = true;
//
// Server versions 5.0.5 or newer will only open a cursor and set this flag if they can, otherwise they punt and go back to mysql_store_results()
// behavior
//
if (this.connection.versionMeetsMinimum(5, 0, 5)) {
usingCursor = (this.serverStatus & SERVER_STATUS_CURSOR_EXISTS) != 0;
}
if (usingCursor) {
RowData rows = new RowDataCursor(this, prepStmt, fields);
ResultSetImpl rs = buildResultSetWithRows(callingStatement, catalog, fields, rows, resultSetType, resultSetConcurrency, isBinaryEncoded);
if (usingCursor) {
rs.setFetchSize(callingStatement.getFetchSize());
}
return rs;
}
}
RowData rowData = null;
if (!streamResults) {
rowData = readSingleRowSet(columnCount, maxRows, resultSetConcurrency, isBinaryEncoded, (metadataFromCache == null) ? fields : metadataFromCache);
} else {
rowData = new RowDataDynamic(this, (int) columnCount, (metadataFromCache == null) ? fields : metadataFromCache, isBinaryEncoded);
this.streamingData = rowData;
}
ResultSetImpl rs = buildResultSetWithRows(callingStatement, catalog, (metadataFromCache == null) ? fields : metadataFromCache, rowData, resultSetType,
resultSetConcurrency, isBinaryEncoded);
return rs;
}
// We do this to break the chain between MysqlIO and Connection, so that we can have PhantomReferences on connections that let the driver clean up the
// socket connection without having to use finalize() somewhere (which although more straightforward, is horribly inefficent).
protected NetworkResources getNetworkResources() {
return new NetworkResources(this.mysqlConnection, this.mysqlInput, this.mysqlOutput);
}
/**
* Forcibly closes the underlying socket to MySQL.
*/
protected final void forceClose() {
try {
getNetworkResources().forceClose();
} finally {
this.mysqlConnection = null;
this.mysqlInput = null;
this.mysqlOutput = null;
}
}
/**
* Reads and discards a single MySQL packet from the input stream.
*
* @throws SQLException
* if the network fails while skipping the
* packet.
*/
protected final void skipPacket() throws SQLException {
try {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.1"));
}
int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.2"));
traceMessageBuf.append(packetLength);
traceMessageBuf.append(Messages.getString("MysqlIO.3"));
traceMessageBuf.append(StringUtils.dumpAsHex(this.packetHeaderBuf, 4));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
byte multiPacketSeq = this.packetHeaderBuf[3];
if (!this.packetSequenceReset) {
if (this.enablePacketDebug && this.checkPacketSequence) {
checkPacketSequencing(multiPacketSeq);
}
} else {
this.packetSequenceReset = false;
}
this.readPacketSequence = multiPacketSeq;
skipFully(this.mysqlInput, packetLength);
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
try {
this.connection.realClose(false, false, true, oom);
} catch (Exception ex) {
}
throw oom;
}
}
/**
* Read one packet from the MySQL server
*
* @return the packet from the server.
*
* @throws SQLException
* @throws CommunicationsException
*/
protected final Buffer readPacket() throws SQLException {
try {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.1"));
}
int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
if (packetLength > this.maxAllowedPacket) {
throw new PacketTooBigException(packetLength, this.maxAllowedPacket);
}
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.2"));
traceMessageBuf.append(packetLength);
traceMessageBuf.append(Messages.getString("MysqlIO.3"));
traceMessageBuf.append(StringUtils.dumpAsHex(this.packetHeaderBuf, 4));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
byte multiPacketSeq = this.packetHeaderBuf[3];
if (!this.packetSequenceReset) {
if (this.enablePacketDebug && this.checkPacketSequence) {
checkPacketSequencing(multiPacketSeq);
}
} else {
this.packetSequenceReset = false;
}
this.readPacketSequence = multiPacketSeq;
// Read data
byte[] buffer = new byte[packetLength];
int numBytesRead = readFully(this.mysqlInput, buffer, 0, packetLength);
if (numBytesRead != packetLength) {
throw new IOException("Short read, expected " + packetLength + " bytes, only read " + numBytesRead);
}
Buffer packet = new Buffer(buffer);
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.4"));
traceMessageBuf.append(getPacketDumpToLog(packet, packetLength));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
if (this.enablePacketDebug) {
enqueuePacketForDebugging(false, false, 0, this.packetHeaderBuf, packet);
}
if (this.connection.getMaintainTimeStats()) {
this.lastPacketReceivedTimeMs = System.currentTimeMillis();
}
return packet;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
try {
this.connection.realClose(false, false, true, oom);
} catch (Exception ex) {
}
throw oom;
}
}
/**
* Unpacks the Field information from the given packet. Understands pre 4.1
* and post 4.1 server version field packet structures.
*
* @param packet
* the packet containing the field information
* @param extractDefaultValues
* should default values be extracted?
*
* @return the unpacked field
*
* @throws SQLException
*/
protected final Field unpackField(Buffer packet, boolean extractDefaultValues) throws SQLException {
if (this.use41Extensions) {
// we only store the position of the string and
// materialize only if needed...
if (this.has41NewNewProt) {
// Not used yet, 5.0?
int catalogNameStart = packet.getPosition() + 1;
int catalogNameLength = packet.fastSkipLenString();
catalogNameStart = adjustStartForFieldLength(catalogNameStart, catalogNameLength);
}
int databaseNameStart = packet.getPosition() + 1;
int databaseNameLength = packet.fastSkipLenString();
databaseNameStart = adjustStartForFieldLength(databaseNameStart, databaseNameLength);
int tableNameStart = packet.getPosition() + 1;
int tableNameLength = packet.fastSkipLenString();
tableNameStart = adjustStartForFieldLength(tableNameStart, tableNameLength);
// orgTableName is never used so skip
int originalTableNameStart = packet.getPosition() + 1;
int originalTableNameLength = packet.fastSkipLenString();
originalTableNameStart = adjustStartForFieldLength(originalTableNameStart, originalTableNameLength);
// we only store the position again...
int nameStart = packet.getPosition() + 1;
int nameLength = packet.fastSkipLenString();
nameStart = adjustStartForFieldLength(nameStart, nameLength);
// orgColName is not required so skip...
int originalColumnNameStart = packet.getPosition() + 1;
int originalColumnNameLength = packet.fastSkipLenString();
originalColumnNameStart = adjustStartForFieldLength(originalColumnNameStart, originalColumnNameLength);
packet.readByte();
short charSetNumber = (short) packet.readInt();
long colLength = 0;
if (this.has41NewNewProt) {
colLength = packet.readLong();
} else {
colLength = packet.readLongInt();
}
int colType = packet.readByte() & 0xff;
short colFlag = 0;
if (this.hasLongColumnInfo) {
colFlag = (short) packet.readInt();
} else {
colFlag = (short) (packet.readByte() & 0xff);
}
int colDecimals = packet.readByte() & 0xff;
int defaultValueStart = -1;
int defaultValueLength = -1;
if (extractDefaultValues) {
defaultValueStart = packet.getPosition() + 1;
defaultValueLength = packet.fastSkipLenString();
}
Field field = new Field(this.connection, packet.getByteBuffer(), databaseNameStart, databaseNameLength, tableNameStart, tableNameLength,
originalTableNameStart, originalTableNameLength, nameStart, nameLength, originalColumnNameStart, originalColumnNameLength, colLength,
colType, colFlag, colDecimals, defaultValueStart, defaultValueLength, charSetNumber);
return field;
}
int tableNameStart = packet.getPosition() + 1;
int tableNameLength = packet.fastSkipLenString();
tableNameStart = adjustStartForFieldLength(tableNameStart, tableNameLength);
int nameStart = packet.getPosition() + 1;
int nameLength = packet.fastSkipLenString();
nameStart = adjustStartForFieldLength(nameStart, nameLength);
int colLength = packet.readnBytes();
int colType = packet.readnBytes();
packet.readByte(); // We know it's currently 2
short colFlag = 0;
if (this.hasLongColumnInfo) {
colFlag = (short) (packet.readInt());
} else {
colFlag = (short) (packet.readByte() & 0xff);
}
int colDecimals = (packet.readByte() & 0xff);
if (this.colDecimalNeedsBump) {
colDecimals++;
}
Field field = new Field(this.connection, packet.getByteBuffer(), nameStart, nameLength, tableNameStart, tableNameLength, colLength, colType, colFlag,
colDecimals);
return field;
}
private int adjustStartForFieldLength(int nameStart, int nameLength) {
if (nameLength < 251) {
return nameStart;
}
if (nameLength >= 251 && nameLength < 65536) {
return nameStart + 2;
}
if (nameLength >= 65536 && nameLength < 16777216) {
return nameStart + 3;
}
return nameStart + 8;
}
protected boolean isSetNeededForAutoCommitMode(boolean autoCommitFlag) {
if (this.use41Extensions && this.connection.getElideSetAutoCommits()) {
boolean autoCommitModeOnServer = ((this.serverStatus & SERVER_STATUS_AUTOCOMMIT) != 0);
if (!autoCommitFlag && versionMeetsMinimum(5, 0, 0)) {
// Just to be safe, check if a transaction is in progress on the server....
// if so, then we must be in autoCommit == false
// therefore return the opposite of transaction status
boolean inTransactionOnServer = ((this.serverStatus & SERVER_STATUS_IN_TRANS) != 0);
return !inTransactionOnServer;
}
return autoCommitModeOnServer != autoCommitFlag;
}
return true;
}
protected boolean inTransactionOnServer() {
return (this.serverStatus & SERVER_STATUS_IN_TRANS) != 0;
}
/**
* Re-authenticates as the given user and password
*
* @param userName
* @param password
* @param database
*
* @throws SQLException
*/
protected void changeUser(String userName, String password, String database) throws SQLException {
this.packetSequence = -1;
this.compressedPacketSequence = -1;
int passwordLength = 16;
int userLength = (userName != null) ? userName.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD;
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
proceedHandshakeWithPluggableAuthentication(userName, password, database, null);
} else if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
Buffer changeUserPacket = new Buffer(packLength + 1);
changeUserPacket.writeByte((byte) MysqlDefs.COM_CHANGE_USER);
if (versionMeetsMinimum(4, 1, 1)) {
secureAuth411(changeUserPacket, packLength, userName, password, database, false);
} else {
secureAuth(changeUserPacket, packLength, userName, password, database, false);
}
} else {
// Passwords can be 16 chars long
Buffer packet = new Buffer(packLength);
packet.writeByte((byte) MysqlDefs.COM_CHANGE_USER);
// User/Password data
packet.writeString(userName);
if (this.protocolVersion > 9) {
packet.writeString(Util.newCrypt(password, this.seed, this.connection.getPasswordCharacterEncoding()));
} else {
packet.writeString(Util.oldCrypt(password, this.seed));
}
boolean localUseConnectWithDb = this.useConnectWithDb && (database != null && database.length() > 0);
if (localUseConnectWithDb) {
packet.writeString(database);
} else {
//Not needed, old server does not require \0
//packet.writeString("");
}
send(packet, packet.getPosition());
checkErrorPacket();
if (!localUseConnectWithDb) {
changeDatabaseTo(database);
}
}
}
/**
* Checks for errors in the reply packet, and if none, returns the reply
* packet, ready for reading
*
* @return a packet ready for reading.
*
* @throws SQLException
* is the packet is an error packet
*/
protected Buffer checkErrorPacket() throws SQLException {
return checkErrorPacket(-1);
}
/**
* Determines if the database charset is the same as the platform charset
*/
protected void checkForCharsetMismatch() {
if (this.connection.getUseUnicode() && (this.connection.getEncoding() != null)) {
String encodingToCheck = jvmPlatformCharset;
if (encodingToCheck == null) {
encodingToCheck = System.getProperty("file.encoding");
}
if (encodingToCheck == null) {
this.platformDbCharsetMatches = false;
} else {
this.platformDbCharsetMatches = encodingToCheck.equals(this.connection.getEncoding());
}
}
}
protected void clearInputStream() throws SQLException {
try {
int len;
// Due to a bug in some older Linux kernels (fixed after the patch "tcp: fix FIONREAD/SIOCINQ"), our SocketInputStream.available() may return 1 even
// if there is no data in the Stream, so, we need to check if InputStream.skip() actually skipped anything.
while ((len = this.mysqlInput.available()) > 0 && this.mysqlInput.skip(len) > 0) {
continue;
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
protected void resetReadPacketSequence() {
this.readPacketSequence = 0;
}
protected void dumpPacketRingBuffer() throws SQLException {
if ((this.packetDebugRingBuffer != null) && this.connection.getEnablePacketDebug()) {
StringBuilder dumpBuffer = new StringBuilder();
dumpBuffer.append("Last " + this.packetDebugRingBuffer.size() + " packets received from server, from oldest->newest:\n");
dumpBuffer.append("\n");
for (Iterator<StringBuilder> ringBufIter = this.packetDebugRingBuffer.iterator(); ringBufIter.hasNext();) {
dumpBuffer.append(ringBufIter.next());
dumpBuffer.append("\n");
}
this.connection.getLog().logTrace(dumpBuffer.toString());
}
}
/**
* Runs an 'EXPLAIN' on the given query and dumps the results to the log
*
* @param querySQL
* @param truncatedQuery
*
* @throws SQLException
*/
protected void explainSlowQuery(byte[] querySQL, String truncatedQuery) throws SQLException {
if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT)
|| (versionMeetsMinimum(5, 6, 3) && StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT_EXTENSION) != -1)) {
PreparedStatement stmt = null;
java.sql.ResultSet rs = null;
try {
stmt = (PreparedStatement) this.connection.clientPrepareStatement("EXPLAIN ?");
stmt.setBytesNoEscapeNoQuotes(1, querySQL);
rs = stmt.executeQuery();
StringBuilder explainResults = new StringBuilder(Messages.getString("MysqlIO.8") + truncatedQuery + Messages.getString("MysqlIO.9"));
ResultSetUtil.appendResultSetSlashGStyle(explainResults, rs);
this.connection.getLog().logWarn(explainResults.toString());
} catch (SQLException sqlEx) {
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
}
}
static int getMaxBuf() {
return maxBufferSize;
}
/**
* Get the major version of the MySQL server we are talking to.
*/
final int getServerMajorVersion() {
return this.serverMajorVersion;
}
/**
* Get the minor version of the MySQL server we are talking to.
*/
final int getServerMinorVersion() {
return this.serverMinorVersion;
}
/**
* Get the sub-minor version of the MySQL server we are talking to.
*/
final int getServerSubMinorVersion() {
return this.serverSubMinorVersion;
}
/**
* Get the version string of the server we are talking to
*/
String getServerVersion() {
return this.serverVersion;
}
/**
* Initialize communications with the MySQL server. Handles logging on, and
* handling initial connection errors.
*
* @param user
* @param password
* @param database
*
* @throws SQLException
* @throws CommunicationsException
*/
void doHandshake(String user, String password, String database) throws SQLException {
// Read the first packet
this.checkPacketSequence = false;
this.readPacketSequence = 0;
Buffer buf = readPacket();
// Get the protocol version
this.protocolVersion = buf.readByte();
if (this.protocolVersion == -1) {
try {
this.mysqlConnection.close();
} catch (Exception e) {
// ignore
}
int errno = 2000;
errno = buf.readInt();
String serverErrorMessage = buf.readString("ASCII", getExceptionInterceptor());
StringBuilder errorBuf = new StringBuilder(Messages.getString("MysqlIO.10"));
errorBuf.append(serverErrorMessage);
errorBuf.append("\"");
String xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
throw SQLError.createSQLException(SQLError.get(xOpen) + ", " + errorBuf.toString(), xOpen, errno, getExceptionInterceptor());
}
this.serverVersion = buf.readString("ASCII", getExceptionInterceptor());
// Parse the server version into major/minor/subminor
int point = this.serverVersion.indexOf('.');
if (point != -1) {
try {
int n = Integer.parseInt(this.serverVersion.substring(0, point));
this.serverMajorVersion = n;
} catch (NumberFormatException NFE1) {
// ignore
}
String remaining = this.serverVersion.substring(point + 1, this.serverVersion.length());
point = remaining.indexOf('.');
if (point != -1) {
try {
int n = Integer.parseInt(remaining.substring(0, point));
this.serverMinorVersion = n;
} catch (NumberFormatException nfe) {
// ignore
}
remaining = remaining.substring(point + 1, remaining.length());
int pos = 0;
while (pos < remaining.length()) {
if ((remaining.charAt(pos) < '0') || (remaining.charAt(pos) > '9')) {
break;
}
pos++;
}
try {
int n = Integer.parseInt(remaining.substring(0, pos));
this.serverSubMinorVersion = n;
} catch (NumberFormatException nfe) {
// ignore
}
}
}
if (versionMeetsMinimum(4, 0, 8)) {
this.maxThreeBytes = (256 * 256 * 256) - 1;
this.useNewLargePackets = true;
} else {
this.maxThreeBytes = 255 * 255 * 255;
this.useNewLargePackets = false;
}
this.colDecimalNeedsBump = versionMeetsMinimum(3, 23, 0);
this.colDecimalNeedsBump = !versionMeetsMinimum(3, 23, 15); // guess? Not noted in changelog
this.useNewUpdateCounts = versionMeetsMinimum(3, 22, 5);
// read connection id
this.threadId = buf.readLong();
if (this.protocolVersion > 9) {
// read auth-plugin-data-part-1 (string[8])
this.seed = buf.readString("ASCII", getExceptionInterceptor(), 8);
// read filler ([00])
buf.readByte();
} else {
// read scramble (string[NUL])
this.seed = buf.readString("ASCII", getExceptionInterceptor());
}
this.serverCapabilities = 0;
// read capability flags (lower 2 bytes)
if (buf.getPosition() < buf.getBufLength()) {
this.serverCapabilities = buf.readInt();
}
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
/* New protocol with 16 bytes to describe server characteristics */
// read character set (1 byte)
this.serverCharsetIndex = buf.readByte() & 0xff;
// read status flags (2 bytes)
this.serverStatus = buf.readInt();
checkTransactionState(0);
// read capability flags (upper 2 bytes)
this.serverCapabilities |= buf.readInt() << 16;
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
// read length of auth-plugin-data (1 byte)
this.authPluginDataLength = buf.readByte() & 0xff;
} else {
// read filler ([00])
buf.readByte();
}
// next 10 bytes are reserved (all [00])
buf.setPosition(buf.getPosition() + 10);
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
String seedPart2;
StringBuilder newSeed;
// read string[$len] auth-plugin-data-part-2 ($len=MAX(13, length of auth-plugin-data - 8))
if (this.authPluginDataLength > 0) {
// TODO: disabled the following check for further clarification
// if (this.authPluginDataLength < 21) {
// forceClose();
// throw SQLError.createSQLException(Messages.getString("MysqlIO.103"),
// SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
// }
seedPart2 = buf.readString("ASCII", getExceptionInterceptor(), this.authPluginDataLength - 8);
newSeed = new StringBuilder(this.authPluginDataLength);
} else {
seedPart2 = buf.readString("ASCII", getExceptionInterceptor());
newSeed = new StringBuilder(SEED_LENGTH);
}
newSeed.append(this.seed);
newSeed.append(seedPart2);
this.seed = newSeed.toString();
}
}
if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && this.connection.getUseCompression()) {
this.clientParam |= CLIENT_COMPRESS;
}
this.useConnectWithDb = (database != null) && (database.length() > 0) && !this.connection.getCreateDatabaseIfNotExist();
if (this.useConnectWithDb) {
this.clientParam |= CLIENT_CONNECT_WITH_DB;
}
// Changing SSL defaults for 5.7+ server: useSSL=true, requireSSL=false, verifyServerCertificate=false
if (versionMeetsMinimum(5, 7, 0) && !this.connection.getUseSSL() && !this.connection.isUseSSLExplicit()) {
this.connection.setUseSSL(true);
this.connection.setVerifyServerCertificate(false);
this.connection.getLog().logWarn(Messages.getString("MysqlIO.SSLWarning"));
}
// check SSL availability
if (((this.serverCapabilities & CLIENT_SSL) == 0) && this.connection.getUseSSL()) {
if (this.connection.getRequireSSL()) {
this.connection.close();
forceClose();
throw SQLError.createSQLException(Messages.getString("MysqlIO.15"), SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE,
getExceptionInterceptor());
}
this.connection.setUseSSL(false);
}
if ((this.serverCapabilities & CLIENT_LONG_FLAG) != 0) {
// We understand other column flags, as well
this.clientParam |= CLIENT_LONG_FLAG;
this.hasLongColumnInfo = true;
}
// return FOUND rows
if (!this.connection.getUseAffectedRows()) {
this.clientParam |= CLIENT_FOUND_ROWS;
}
if (this.connection.getAllowLoadLocalInfile()) {
this.clientParam |= CLIENT_LOCAL_FILES;
}
if (this.isInteractiveClient) {
this.clientParam |= CLIENT_INTERACTIVE;
}
if ((this.serverCapabilities & CLIENT_SESSION_TRACK) != 0) {
// TODO MYSQLCONNJ-437
// this.clientParam |= CLIENT_SESSION_TRACK;
}
if ((this.serverCapabilities & CLIENT_DEPRECATE_EOF) != 0) {
this.clientParam |= CLIENT_DEPRECATE_EOF;
}
//
// switch to pluggable authentication if available
//
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
proceedHandshakeWithPluggableAuthentication(user, password, database, buf);
return;
}
// Authenticate
if (this.protocolVersion > 9) {
this.clientParam |= CLIENT_LONG_PASSWORD; // for long passwords
} else {
this.clientParam &= ~CLIENT_LONG_PASSWORD;
}
//
// 4.1 has some differences in the protocol
//
if ((versionMeetsMinimum(4, 1, 0) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_RESERVED) != 0))) {
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
this.clientParam |= CLIENT_PROTOCOL_41;
this.has41NewNewProt = true;
// Need this to get server status values
this.clientParam |= CLIENT_TRANSACTIONS;
// We always allow multiple result sets
this.clientParam |= CLIENT_MULTI_RESULTS;
// We allow the user to configure whether
// or not they want to support multiple queries
// (by default, this is disabled).
if (this.connection.getAllowMultiQueries()) {
this.clientParam |= CLIENT_MULTI_STATEMENTS;
}
} else {
this.clientParam |= CLIENT_RESERVED;
this.has41NewNewProt = false;
}
this.use41Extensions = true;
}
int passwordLength = 16;
int userLength = (user != null) ? user.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD;
Buffer packet = null;
if (!this.connection.getUseSSL()) {
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
this.clientParam |= CLIENT_SECURE_CONNECTION;
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
secureAuth411(null, packLength, user, password, database, true);
} else {
secureAuth(null, packLength, user, password, database, true);
}
} else {
// Passwords can be 16 chars long
packet = new Buffer(packLength);
if ((this.clientParam & CLIENT_RESERVED) != 0) {
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
// charset, JDBC will connect as 'latin1', and use 'SET NAMES' to change to the desired charset after the connection is established.
packet.writeByte((byte) 8);
// Set of bytes reserved for future use.
packet.writeBytesNoNull(new byte[23]);
} else {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
}
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
// User/Password data
packet.writeString(user, CODE_PAGE_1252, this.connection);
if (this.protocolVersion > 9) {
packet.writeString(Util.newCrypt(password, this.seed, this.connection.getPasswordCharacterEncoding()), CODE_PAGE_1252, this.connection);
} else {
packet.writeString(Util.oldCrypt(password, this.seed), CODE_PAGE_1252, this.connection);
}
if (this.useConnectWithDb) {
packet.writeString(database, CODE_PAGE_1252, this.connection);
}
send(packet, packet.getPosition());
}
} else {
negotiateSSLConnection(user, password, database, packLength);
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
if (versionMeetsMinimum(4, 1, 1)) {
secureAuth411(null, packLength, user, password, database, true);
} else {
secureAuth411(null, packLength, user, password, database, true);
}
} else {
packet = new Buffer(packLength);
if (this.use41Extensions) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
// User/Password data
packet.writeString(user);
if (this.protocolVersion > 9) {
packet.writeString(Util.newCrypt(password, this.seed, this.connection.getPasswordCharacterEncoding()));
} else {
packet.writeString(Util.oldCrypt(password, this.seed));
}
if (((this.serverCapabilities & CLIENT_CONNECT_WITH_DB) != 0) && (database != null) && (database.length() > 0)) {
packet.writeString(database);
}
send(packet, packet.getPosition());
}
}
// Check for errors, not for 4.1.1 or newer, as the new auth protocol doesn't work that way (see secureAuth411() for more details...)
if (!(versionMeetsMinimum(4, 1, 1)) || !((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0)) {
checkErrorPacket();
}
//
// Can't enable compression until after handshake
//
if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && this.connection.getUseCompression() && !(this.mysqlInput instanceof CompressedInputStream)) {
// The following matches with ZLIB's compress()
this.deflater = new Deflater();
this.useCompression = true;
this.mysqlInput = new CompressedInputStream(this.connection, this.mysqlInput);
}
if (!this.useConnectWithDb) {
changeDatabaseTo(database);
}
try {
this.mysqlConnection = this.socketFactory.afterHandshake();
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* Contains instances of authentication plugins which implements {@link AuthenticationPlugin} interface. Key values are mysql
* protocol plugin names, for example "mysql_native_password" and
* "mysql_old_password" for built-in plugins.
*/
private Map<String, AuthenticationPlugin> authenticationPlugins = null;
/**
* Contains names of classes or mechanisms ("mysql_native_password"
* for example) of authentication plugins which must be disabled.
*/
private List<String> disabledAuthenticationPlugins = null;
/**
* Name of class for default authentication plugin in client
*/
private String clientDefaultAuthenticationPlugin = null;
/**
* Protocol name of default authentication plugin in client
*/
private String clientDefaultAuthenticationPluginName = null;
/**
* Protocol name of default authentication plugin in server
*/
private String serverDefaultAuthenticationPluginName = null;
/**
* Fill the {@link MysqlIO#authenticationPlugins} map.
* First this method fill the map with instances of {@link MysqlOldPasswordPlugin}, {@link MysqlNativePasswordPlugin}, {@link MysqlClearPasswordPlugin} and
* {@link Sha256PasswordPlugin}.
* Then it gets instances of plugins listed in "authenticationPlugins" connection property by
* {@link Util#loadExtensions(Connection, Properties, String, String, ExceptionInterceptor)} call and adds them to the map too.
*
* The key for the map entry is getted by {@link AuthenticationPlugin#getProtocolPluginName()}.
* Thus it is possible to replace built-in plugin with custom one, to do it custom plugin should return value
* "mysql_native_password", "mysql_old_password", "mysql_clear_password" or "sha256_password" from it's own getProtocolPluginName() method.
*
* All plugin instances in the map are initialized by {@link Extension#init(Connection, Properties)} call
* with this.connection and this.connection.getProperties() values.
*
* @throws SQLException
*/
private void loadAuthenticationPlugins() throws SQLException {
// default plugin
this.clientDefaultAuthenticationPlugin = this.connection.getDefaultAuthenticationPlugin();
if (this.clientDefaultAuthenticationPlugin == null || "".equals(this.clientDefaultAuthenticationPlugin.trim())) {
throw SQLError.createSQLException(
Messages.getString("Connection.BadDefaultAuthenticationPlugin", new Object[] { this.clientDefaultAuthenticationPlugin }),
getExceptionInterceptor());
}
// disabled plugins
String disabledPlugins = this.connection.getDisabledAuthenticationPlugins();
if (disabledPlugins != null && !"".equals(disabledPlugins)) {
this.disabledAuthenticationPlugins = new ArrayList<String>();
List<String> pluginsToDisable = StringUtils.split(disabledPlugins, ",", true);
Iterator<String> iter = pluginsToDisable.iterator();
while (iter.hasNext()) {
this.disabledAuthenticationPlugins.add(iter.next());
}
}
this.authenticationPlugins = new HashMap<String, AuthenticationPlugin>();
// embedded plugins
AuthenticationPlugin plugin = new MysqlOldPasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
boolean defaultIsFound = addAuthenticationPlugin(plugin);
plugin = new MysqlNativePasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
plugin = new MysqlClearPasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
plugin = new Sha256PasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
// plugins from authenticationPluginClasses connection parameter
String authenticationPluginClasses = this.connection.getAuthenticationPlugins();
if (authenticationPluginClasses != null && !"".equals(authenticationPluginClasses)) {
List<Extension> plugins = Util.loadExtensions(this.connection, this.connection.getProperties(), authenticationPluginClasses,
"Connection.BadAuthenticationPlugin", getExceptionInterceptor());
for (Extension object : plugins) {
plugin = (AuthenticationPlugin) object;
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
}
}
// check if default plugin is listed
if (!defaultIsFound) {
throw SQLError.createSQLException(
Messages.getString("Connection.DefaultAuthenticationPluginIsNotListed", new Object[] { this.clientDefaultAuthenticationPlugin }),
getExceptionInterceptor());
}
}
/**
* Add plugin to {@link MysqlIO#authenticationPlugins} if it is not disabled by
* "disabledAuthenticationPlugins" property, check is it a default plugin.
*
* @param plugin
* Instance of AuthenticationPlugin
* @return True if plugin is default, false if plugin is not default.
* @throws SQLException
* if plugin is default but disabled.
*/
private boolean addAuthenticationPlugin(AuthenticationPlugin plugin) throws SQLException {
boolean isDefault = false;
String pluginClassName = plugin.getClass().getName();
String pluginProtocolName = plugin.getProtocolPluginName();
boolean disabledByClassName = this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginClassName);
boolean disabledByMechanism = this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginProtocolName);
if (disabledByClassName || disabledByMechanism) {
// if disabled then check is it default
if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
throw SQLError.createSQLException(Messages.getString("Connection.BadDisabledAuthenticationPlugin",
new Object[] { disabledByClassName ? pluginClassName : pluginProtocolName }), getExceptionInterceptor());
}
} else {
this.authenticationPlugins.put(pluginProtocolName, plugin);
if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
this.clientDefaultAuthenticationPluginName = pluginProtocolName;
isDefault = true;
}
}
return isDefault;
}
/**
* Get authentication plugin instance from {@link MysqlIO#authenticationPlugins} map by
* pluginName key. If such plugin is found it's {@link AuthenticationPlugin#isReusable()} method
* is checked, when it's false this method returns a new instance of plugin
* and the same instance otherwise.
*
* If plugin is not found method returns null, in such case the subsequent behavior
* of handshake process depends on type of last packet received from server:
* if it was Auth Challenge Packet then handshake will proceed with default plugin,
* if it was Auth Method Switch Request Packet then handshake will be interrupted with exception.
*
* @param pluginName
* mysql protocol plugin names, for example "mysql_native_password" and "mysql_old_password" for built-in plugins
* @return null if plugin is not found or authentication plugin instance initialized with current connection properties
* @throws SQLException
*/
private AuthenticationPlugin getAuthenticationPlugin(String pluginName) throws SQLException {
AuthenticationPlugin plugin = this.authenticationPlugins.get(pluginName);
if (plugin != null && !plugin.isReusable()) {
try {
plugin = plugin.getClass().newInstance();
plugin.init(this.connection, this.connection.getProperties());
} catch (Throwable t) {
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("Connection.BadAuthenticationPlugin", new Object[] { plugin.getClass().getName() }), getExceptionInterceptor());
sqlEx.initCause(t);
throw sqlEx;
}
}
return plugin;
}
/**
* Check if given plugin requires confidentiality, but connection is without SSL
*
* @param plugin
* @throws SQLException
*/
private void checkConfidentiality(AuthenticationPlugin plugin) throws SQLException {
if (plugin.requiresConfidentiality() && !isSSLEstablished()) {
throw SQLError.createSQLException(Messages.getString("Connection.AuthenticationPluginRequiresSSL", new Object[] { plugin.getProtocolPluginName() }),
getExceptionInterceptor());
}
}
/**
* Performs an authentication handshake to authorize connection to a
* given database as a given MySQL user. This can happen upon initial
* connection to the server, after receiving Auth Challenge Packet, or
* at any moment during the connection life-time via a Change User
* request.
*
* This method is aware of pluggable authentication and will use
* registered authentication plugins as requested by the server.
*
* @param user
* the MySQL user account to log into
* @param password
* authentication data for the user account (depends
* on authentication method used - can be empty)
* @param database
* database to connect to (can be empty)
* @param challenge
* the Auth Challenge Packet received from server if
* this method is used during the initial connection.
* Otherwise null.
*
* @throws SQLException
*/
private void proceedHandshakeWithPluggableAuthentication(String user, String password, String database, Buffer challenge) throws SQLException {
if (this.authenticationPlugins == null) {
loadAuthenticationPlugins();
}
boolean skipPassword = false;
int passwordLength = 16;
int userLength = (user != null) ? user.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD;
AuthenticationPlugin plugin = null;
Buffer fromServer = null;
ArrayList<Buffer> toServer = new ArrayList<Buffer>();
boolean done = false;
Buffer last_sent = null;
boolean old_raw_challenge = false;
int counter = 100;
while (0 < counter--) {
if (!done) {
if (challenge != null) {
if (challenge.isOKPacket()) {
throw SQLError.createSQLException(
Messages.getString("Connection.UnexpectedAuthenticationApproval", new Object[] { plugin.getProtocolPluginName() }),
getExceptionInterceptor());
}
// read Auth Challenge Packet
this.clientParam |= CLIENT_PLUGIN_AUTH | CLIENT_LONG_PASSWORD | CLIENT_PROTOCOL_41 | CLIENT_TRANSACTIONS // Need this to get server status values
| CLIENT_MULTI_RESULTS // We always allow multiple result sets
| CLIENT_SECURE_CONNECTION; // protocol with pluggable authentication always support this
// We allow the user to configure whether or not they want to support multiple queries (by default, this is disabled).
if (this.connection.getAllowMultiQueries()) {
this.clientParam |= CLIENT_MULTI_STATEMENTS;
}
if (((this.serverCapabilities & CLIENT_CAN_HANDLE_EXPIRED_PASSWORD) != 0) && !this.connection.getDisconnectOnExpiredPasswords()) {
this.clientParam |= CLIENT_CAN_HANDLE_EXPIRED_PASSWORD;
}
if (((this.serverCapabilities & CLIENT_CONNECT_ATTRS) != 0) && !NONE.equals(this.connection.getConnectionAttributes())) {
this.clientParam |= CLIENT_CONNECT_ATTRS;
}
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) {
this.clientParam |= CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA;
}
this.has41NewNewProt = true;
this.use41Extensions = true;
if (this.connection.getUseSSL()) {
negotiateSSLConnection(user, password, database, packLength);
}
String pluginName = null;
// Due to Bug#59453 the auth-plugin-name is missing the terminating NUL-char in versions prior to 5.5.10 and 5.6.2.
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
if (!versionMeetsMinimum(5, 5, 10) || versionMeetsMinimum(5, 6, 0) && !versionMeetsMinimum(5, 6, 2)) {
pluginName = challenge.readString("ASCII", getExceptionInterceptor(), this.authPluginDataLength);
} else {
pluginName = challenge.readString("ASCII", getExceptionInterceptor());
}
}
plugin = getAuthenticationPlugin(pluginName);
if (plugin == null) {
/*
* Use default if there is no plugin for pluginName.
*/
plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
} else if (pluginName.equals(Sha256PasswordPlugin.PLUGIN_NAME) && !isSSLEstablished() && this.connection.getServerRSAPublicKeyFile() == null
&& !this.connection.getAllowPublicKeyRetrieval()) {
/*
* Fall back to default if plugin is 'sha256_password' but required conditions for this to work aren't met. If default is other than
* 'sha256_password' this will result in an immediate authentication switch request, allowing for other plugins to authenticate
* successfully. If default is 'sha256_password' then the authentication will fail as expected. In both cases user's password won't be
* sent to avoid subjecting it to lesser security levels.
*/
plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
skipPassword = !this.clientDefaultAuthenticationPluginName.equals(pluginName);
}
this.serverDefaultAuthenticationPluginName = plugin.getProtocolPluginName();
checkConfidentiality(plugin);
fromServer = new Buffer(StringUtils.getBytes(this.seed));
} else {
// no challenge so this is a changeUser call
plugin = getAuthenticationPlugin(this.serverDefaultAuthenticationPluginName == null ? this.clientDefaultAuthenticationPluginName
: this.serverDefaultAuthenticationPluginName);
checkConfidentiality(plugin);
// Servers not affected by Bug#70865 expect the Change User Request containing a correct answer
// to seed sent by the server during the initial handshake, thus we reuse it here.
// Servers affected by Bug#70865 will just ignore it and send the Auth Switch.
fromServer = new Buffer(StringUtils.getBytes(this.seed));
}
} else {
// read packet from server and check if it's an ERROR packet
challenge = checkErrorPacket();
old_raw_challenge = false;
this.packetSequence++;
this.compressedPacketSequence++;
if (plugin == null) {
// this shouldn't happen in normal handshake packets exchange,
// we do it just to ensure that we don't get NPE in other case
plugin = getAuthenticationPlugin(this.serverDefaultAuthenticationPluginName != null ? this.serverDefaultAuthenticationPluginName
: this.clientDefaultAuthenticationPluginName);
}
if (challenge.isOKPacket()) {
// if OK packet then finish handshake
plugin.destroy();
break;
} else if (challenge.isAuthMethodSwitchRequestPacket()) {
skipPassword = false;
// read Auth Method Switch Request Packet
String pluginName = challenge.readString("ASCII", getExceptionInterceptor());
// get new plugin
if (!plugin.getProtocolPluginName().equals(pluginName)) {
plugin.destroy();
plugin = getAuthenticationPlugin(pluginName);
// if plugin is not found for pluginName throw exception
if (plugin == null) {
throw SQLError.createSQLException(Messages.getString("Connection.BadAuthenticationPlugin", new Object[] { pluginName }),
getExceptionInterceptor());
}
}
checkConfidentiality(plugin);
fromServer = new Buffer(StringUtils.getBytes(challenge.readString("ASCII", getExceptionInterceptor())));
} else {
// read raw packet
if (versionMeetsMinimum(5, 5, 16)) {
fromServer = new Buffer(challenge.getBytes(challenge.getPosition(), challenge.getBufLength() - challenge.getPosition()));
} else {
old_raw_challenge = true;
fromServer = new Buffer(challenge.getBytes(challenge.getPosition() - 1, challenge.getBufLength() - challenge.getPosition() + 1));
}
}
}
// call plugin
try {
plugin.setAuthenticationParameters(user, skipPassword ? null : password);
done = plugin.nextAuthenticationStep(fromServer, toServer);
} catch (SQLException e) {
throw SQLError.createSQLException(e.getMessage(), e.getSQLState(), e, getExceptionInterceptor());
}
// send response
if (toServer.size() > 0) {
if (challenge == null) {
String enc = getEncodingForHandshake();
// write COM_CHANGE_USER Packet
last_sent = new Buffer(packLength + 1);
last_sent.writeByte((byte) MysqlDefs.COM_CHANGE_USER);
// User/Password data
last_sent.writeString(user, enc, this.connection);
// 'auth-response-len' is limited to one Byte but, in case of success, COM_CHANGE_USER will be followed by an AuthSwitchRequest anyway
if (toServer.get(0).getBufLength() < 256) {
// non-mysql servers may use this information to authenticate without requiring another round-trip
last_sent.writeByte((byte) toServer.get(0).getBufLength());
last_sent.writeBytesNoNull(toServer.get(0).getByteBuffer(), 0, toServer.get(0).getBufLength());
} else {
last_sent.writeByte((byte) 0);
}
if (this.useConnectWithDb) {
last_sent.writeString(database, enc, this.connection);
} else {
/* For empty database */
last_sent.writeByte((byte) 0);
}
appendCharsetByteForHandshake(last_sent, enc);
// two (little-endian) bytes for charset in this packet
last_sent.writeByte((byte) 0);
// plugin name
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
last_sent.writeString(plugin.getProtocolPluginName(), enc, this.connection);
}
// connection attributes
if ((this.clientParam & CLIENT_CONNECT_ATTRS) != 0) {
sendConnectionAttributes(last_sent, enc, this.connection);
last_sent.writeByte((byte) 0);
}
send(last_sent, last_sent.getPosition());
} else if (challenge.isAuthMethodSwitchRequestPacket()) {
// write Auth Method Switch Response Packet
last_sent = new Buffer(toServer.get(0).getBufLength() + HEADER_LENGTH);
last_sent.writeBytesNoNull(toServer.get(0).getByteBuffer(), 0, toServer.get(0).getBufLength());
send(last_sent, last_sent.getPosition());
} else if (challenge.isRawPacket() || old_raw_challenge) {
// write raw packet(s)
for (Buffer buffer : toServer) {
last_sent = new Buffer(buffer.getBufLength() + HEADER_LENGTH);
last_sent.writeBytesNoNull(buffer.getByteBuffer(), 0, toServer.get(0).getBufLength());
send(last_sent, last_sent.getPosition());
}
} else {
// write Auth Response Packet
String enc = getEncodingForHandshake();
last_sent = new Buffer(packLength);
last_sent.writeLong(this.clientParam);
last_sent.writeLong(this.maxThreeBytes);
appendCharsetByteForHandshake(last_sent, enc);
last_sent.writeBytesNoNull(new byte[23]); // Set of bytes reserved for future use.
// User/Password data
last_sent.writeString(user, enc, this.connection);
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) {
// send lenenc-int length of auth-response and string[n] auth-response
last_sent.writeLenBytes(toServer.get(0).getBytes(toServer.get(0).getBufLength()));
} else {
// send 1 byte length of auth-response and string[n] auth-response
last_sent.writeByte((byte) toServer.get(0).getBufLength());
last_sent.writeBytesNoNull(toServer.get(0).getByteBuffer(), 0, toServer.get(0).getBufLength());
}
if (this.useConnectWithDb) {
last_sent.writeString(database, enc, this.connection);
} else {
/* For empty database */
last_sent.writeByte((byte) 0);
}
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
last_sent.writeString(plugin.getProtocolPluginName(), enc, this.connection);
}
// connection attributes
if (((this.clientParam & CLIENT_CONNECT_ATTRS) != 0)) {
sendConnectionAttributes(last_sent, enc, this.connection);
}
send(last_sent, last_sent.getPosition());
}
}
}
if (counter == 0) {
throw SQLError.createSQLException(Messages.getString("CommunicationsException.TooManyAuthenticationPluginNegotiations"), getExceptionInterceptor());
}
//
// Can't enable compression until after handshake
//
if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && this.connection.getUseCompression() && !(this.mysqlInput instanceof CompressedInputStream)) {
// The following matches with ZLIB's compress()
this.deflater = new Deflater();
this.useCompression = true;
this.mysqlInput = new CompressedInputStream(this.connection, this.mysqlInput);
}
if (!this.useConnectWithDb) {
changeDatabaseTo(database);
}
try {
this.mysqlConnection = this.socketFactory.afterHandshake();
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
private Properties getConnectionAttributesAsProperties(String atts) throws SQLException {
Properties props = new Properties();
if (atts != null) {
String[] pairs = atts.split(",");
for (String pair : pairs) {
int keyEnd = pair.indexOf(":");
if (keyEnd > 0 && (keyEnd + 1) < pair.length()) {
props.setProperty(pair.substring(0, keyEnd), pair.substring(keyEnd + 1));
}
}
}
// Leaving disabled until standard values are defined
// props.setProperty("_os", NonRegisteringDriver.OS);
// props.setProperty("_platform", NonRegisteringDriver.PLATFORM);
props.setProperty("_client_name", NonRegisteringDriver.NAME);
props.setProperty("_client_version", NonRegisteringDriver.VERSION);
props.setProperty("_runtime_vendor", NonRegisteringDriver.RUNTIME_VENDOR);
props.setProperty("_runtime_version", NonRegisteringDriver.RUNTIME_VERSION);
props.setProperty("_client_license", NonRegisteringDriver.LICENSE);
return props;
}
private void sendConnectionAttributes(Buffer buf, String enc, MySQLConnection conn) throws SQLException {
String atts = conn.getConnectionAttributes();
Buffer lb = new Buffer(100);
try {
Properties props = getConnectionAttributesAsProperties(atts);
for (Object key : props.keySet()) {
lb.writeLenString((String) key, enc, conn.getServerCharset(), null, conn.parserKnowsUnicode(), conn);
lb.writeLenString(props.getProperty((String) key), enc, conn.getServerCharset(), null, conn.parserKnowsUnicode(), conn);
}
} catch (UnsupportedEncodingException e) {
}
buf.writeByte((byte) (lb.getPosition() - 4));
buf.writeBytesNoNull(lb.getByteBuffer(), 4, lb.getBufLength() - 4);
}
private void changeDatabaseTo(String database) throws SQLException {
if (database == null || database.length() == 0) {
return;
}
try {
sendCommand(MysqlDefs.INIT_DB, database, null, false, null, 0);
} catch (Exception ex) {
if (this.connection.getCreateDatabaseIfNotExist()) {
sendCommand(MysqlDefs.QUERY, "CREATE DATABASE IF NOT EXISTS " + database, null, false, null, 0);
sendCommand(MysqlDefs.INIT_DB, database, null, false, null, 0);
} else {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ex,
getExceptionInterceptor());
}
}
}
/**
* Retrieve one row from the MySQL server. Note: this method is not
* thread-safe, but it is only called from methods that are guarded by
* synchronizing on this object.
*
* @param fields
* @param columnCount
* @param isBinaryEncoded
* @param resultSetConcurrency
* @param b
*
* @throws SQLException
*/
final ResultSetRow nextRow(Field[] fields, int columnCount, boolean isBinaryEncoded, int resultSetConcurrency, boolean useBufferRowIfPossible,
boolean useBufferRowExplicit, boolean canReuseRowPacketForBufferRow, Buffer existingRowPacket) throws SQLException {
if (this.useDirectRowUnpack && existingRowPacket == null && !isBinaryEncoded && !useBufferRowIfPossible && !useBufferRowExplicit) {
return nextRowFast(fields, columnCount, isBinaryEncoded, resultSetConcurrency, useBufferRowIfPossible, useBufferRowExplicit,
canReuseRowPacketForBufferRow);
}
Buffer rowPacket = null;
if (existingRowPacket == null) {
rowPacket = checkErrorPacket();
if (!useBufferRowExplicit && useBufferRowIfPossible) {
if (rowPacket.getBufLength() > this.useBufferRowSizeThreshold) {
useBufferRowExplicit = true;
}
}
} else {
// We attempted to do nextRowFast(), but the packet was a multipacket, so we couldn't unpack it directly
rowPacket = existingRowPacket;
checkErrorPacket(existingRowPacket);
}
if (!isBinaryEncoded) {
//
// Didn't read an error, so re-position to beginning of packet in order to read result set data
//
rowPacket.setPosition(rowPacket.getPosition() - 1);
if (!(!isEOFDeprecated() && rowPacket.isEOFPacket() || isEOFDeprecated() && rowPacket.isResultSetOKPacket())) {
if (resultSetConcurrency == ResultSet.CONCUR_UPDATABLE || (!useBufferRowIfPossible && !useBufferRowExplicit)) {
byte[][] rowData = new byte[columnCount][];
for (int i = 0; i < columnCount; i++) {
rowData[i] = rowPacket.readLenByteArray(0);
}
return new ByteArrayRow(rowData, getExceptionInterceptor());
}
if (!canReuseRowPacketForBufferRow) {
this.reusablePacket = new Buffer(rowPacket.getBufLength());
}
return new BufferRow(rowPacket, fields, false, getExceptionInterceptor());
}
readServerStatusForResultSets(rowPacket);
return null;
}
//
// Handle binary-encoded data for server-side PreparedStatements...
//
if (!(!isEOFDeprecated() && rowPacket.isEOFPacket() || isEOFDeprecated() && rowPacket.isResultSetOKPacket())) {
if (resultSetConcurrency == ResultSet.CONCUR_UPDATABLE || (!useBufferRowIfPossible && !useBufferRowExplicit)) {
return unpackBinaryResultSetRow(fields, rowPacket, resultSetConcurrency);
}
if (!canReuseRowPacketForBufferRow) {
this.reusablePacket = new Buffer(rowPacket.getBufLength());
}
return new BufferRow(rowPacket, fields, true, getExceptionInterceptor());
}
rowPacket.setPosition(rowPacket.getPosition() - 1);
readServerStatusForResultSets(rowPacket);
return null;
}
final ResultSetRow nextRowFast(Field[] fields, int columnCount, boolean isBinaryEncoded, int resultSetConcurrency, boolean useBufferRowIfPossible,
boolean useBufferRowExplicit, boolean canReuseRowPacket) throws SQLException {
try {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new RuntimeException(Messages.getString("MysqlIO.43"));
}
int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
// Have we stumbled upon a multi-packet?
if (packetLength == this.maxThreeBytes) {
reuseAndReadPacket(this.reusablePacket, packetLength);
// Go back to "old" way which uses packets
return nextRow(fields, columnCount, isBinaryEncoded, resultSetConcurrency, useBufferRowIfPossible, useBufferRowExplicit, canReuseRowPacket,
this.reusablePacket);
}
// Does this go over the threshold where we should use a BufferRow?
if (packetLength > this.useBufferRowSizeThreshold) {
reuseAndReadPacket(this.reusablePacket, packetLength);
// Go back to "old" way which uses packets
return nextRow(fields, columnCount, isBinaryEncoded, resultSetConcurrency, true, true, false, this.reusablePacket);
}
int remaining = packetLength;
boolean firstTime = true;
byte[][] rowData = null;
for (int i = 0; i < columnCount; i++) {
int sw = this.mysqlInput.read() & 0xff;
remaining--;
if (firstTime) {
if (sw == Buffer.TYPE_ID_ERROR) {
// error packet - we assemble it whole for "fidelity" in case we ever need an entire packet in checkErrorPacket() but we could've gotten
// away with just writing the error code and message in it (for now).
Buffer errorPacket = new Buffer(packetLength + HEADER_LENGTH);
errorPacket.setPosition(0);
errorPacket.writeByte(this.packetHeaderBuf[0]);
errorPacket.writeByte(this.packetHeaderBuf[1]);
errorPacket.writeByte(this.packetHeaderBuf[2]);
errorPacket.writeByte((byte) 1);
errorPacket.writeByte((byte) sw);
readFully(this.mysqlInput, errorPacket.getByteBuffer(), 5, packetLength - 1);
errorPacket.setPosition(4);
checkErrorPacket(errorPacket);
}
if (sw == Buffer.TYPE_ID_EOF && packetLength < 16777215) {
// Both EOF and OK packets have the same 0xfe signature in result sets.
// OK packet length limit restricted to MAX_PACKET_LENGTH value (256L*256L*256L-1) as any length greater
// than this value will have first byte of OK packet to be 254 thus does not provide a means to identify
// if this is OK or EOF packet.
// Thus we need to check the packet length to distinguish between OK packet and ResultsetRow packet starting with 0xfe
if (this.use41Extensions) {
if (isEOFDeprecated()) {
// read OK packet
remaining -= skipLengthEncodedInteger(this.mysqlInput); // affected_rows
remaining -= skipLengthEncodedInteger(this.mysqlInput); // last_insert_id
this.oldServerStatus = this.serverStatus;
this.serverStatus = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
checkTransactionState(this.oldServerStatus);
remaining -= 2;
this.warningCount = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
remaining -= 2;
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
} else {
// read EOF packet
this.warningCount = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
remaining -= 2;
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
this.oldServerStatus = this.serverStatus;
this.serverStatus = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
checkTransactionState(this.oldServerStatus);
remaining -= 2;
}
setServerSlowQueryFlags();
if (remaining > 0) {
skipFully(this.mysqlInput, remaining);
}
}
return null; // last data packet
}
rowData = new byte[columnCount][];
firstTime = false;
}
int len = 0;
switch (sw) {
case 251:
len = NULL_LENGTH;
break;
case 252:
len = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
remaining -= 2;
break;
case 253:
len = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8) | ((this.mysqlInput.read() & 0xff) << 16);
remaining -= 3;
break;
case 254:
len = (int) ((this.mysqlInput.read() & 0xff) | ((long) (this.mysqlInput.read() & 0xff) << 8)
| ((long) (this.mysqlInput.read() & 0xff) << 16) | ((long) (this.mysqlInput.read() & 0xff) << 24)
| ((long) (this.mysqlInput.read() & 0xff) << 32) | ((long) (this.mysqlInput.read() & 0xff) << 40)
| ((long) (this.mysqlInput.read() & 0xff) << 48) | ((long) (this.mysqlInput.read() & 0xff) << 56));
remaining -= 8;
break;
default:
len = sw;
}
if (len == NULL_LENGTH) {
rowData[i] = null;
} else if (len == 0) {
rowData[i] = Constants.EMPTY_BYTE_ARRAY;
} else {
rowData[i] = new byte[len];
int bytesRead = readFully(this.mysqlInput, rowData[i], 0, len);
if (bytesRead != len) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException(Messages.getString("MysqlIO.43")), getExceptionInterceptor());
}
remaining -= bytesRead;
}
}
if (remaining > 0) {
skipFully(this.mysqlInput, remaining);
}
return new ByteArrayRow(rowData, getExceptionInterceptor());
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* Log-off of the MySQL server and close the socket.
*
* @throws SQLException
*/
final void quit() throws SQLException {
try {
// we're not going to read the response, fixes BUG#56979 Improper connection closing logic leads to TIME_WAIT sockets on server
try {
if (!this.mysqlConnection.isClosed()) {
try {
this.mysqlConnection.shutdownInput();
} catch (UnsupportedOperationException ex) {
// ignore, some sockets do not support this method
}
}
} catch (IOException ioEx) {
this.connection.getLog().logWarn("Caught while disconnecting...", ioEx);
}
Buffer packet = new Buffer(6);
this.packetSequence = -1;
this.compressedPacketSequence = -1;
packet.writeByte((byte) MysqlDefs.QUIT);
send(packet, packet.getPosition());
} finally {
forceClose();
}
}
/**
* Returns the packet used for sending data (used by PreparedStatement)
* Guarded by external synchronization on a mutex.
*
* @return A packet to send data with
*/
Buffer getSharedSendPacket() {
if (this.sharedSendPacket == null) {
this.sharedSendPacket = new Buffer(INITIAL_PACKET_SIZE);
}
return this.sharedSendPacket;
}
void closeStreamer(RowData streamer) throws SQLException {
if (this.streamingData == null) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.17") + streamer + Messages.getString("MysqlIO.18"), getExceptionInterceptor());
}
if (streamer != this.streamingData) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.19") + streamer + Messages.getString("MysqlIO.20") + Messages.getString("MysqlIO.21")
+ Messages.getString("MysqlIO.22"), getExceptionInterceptor());
}
this.streamingData = null;
}
boolean tackOnMoreStreamingResults(ResultSetImpl addingTo) throws SQLException {
if ((this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0) {
boolean moreRowSetsExist = true;
ResultSetImpl currentResultSet = addingTo;
boolean firstTime = true;
while (moreRowSetsExist) {
if (!firstTime && currentResultSet.reallyResult()) {
break;
}
firstTime = false;
Buffer fieldPacket = checkErrorPacket();
fieldPacket.setPosition(0);
java.sql.Statement owningStatement = addingTo.getStatement();
int maxRows = owningStatement.getMaxRows();
// fixme for catalog, isBinary
ResultSetImpl newResultSet = readResultsForQueryOrUpdate((StatementImpl) owningStatement, maxRows, owningStatement.getResultSetType(),
owningStatement.getResultSetConcurrency(), true, owningStatement.getConnection().getCatalog(), fieldPacket, addingTo.isBinaryEncoded,
-1L, null);
currentResultSet.setNextResultSet(newResultSet);
currentResultSet = newResultSet;
moreRowSetsExist = (this.serverStatus & MysqlIO.SERVER_MORE_RESULTS_EXISTS) != 0;
if (!currentResultSet.reallyResult() && !moreRowSetsExist) {
// special case, we can stop "streaming"
return false;
}
}
return true;
}
return false;
}
ResultSetImpl readAllResults(StatementImpl callingStatement, int maxRows, int resultSetType, int resultSetConcurrency, boolean streamResults,
String catalog, Buffer resultPacket, boolean isBinaryEncoded, long preSentColumnCount, Field[] metadataFromCache) throws SQLException {
resultPacket.setPosition(resultPacket.getPosition() - 1);
ResultSetImpl topLevelResultSet = readResultsForQueryOrUpdate(callingStatement, maxRows, resultSetType, resultSetConcurrency, streamResults, catalog,
resultPacket, isBinaryEncoded, preSentColumnCount, metadataFromCache);
ResultSetImpl currentResultSet = topLevelResultSet;
boolean checkForMoreResults = ((this.clientParam & CLIENT_MULTI_RESULTS) != 0);
boolean serverHasMoreResults = (this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0;
//
// TODO: We need to support streaming of multiple result sets
//
if (serverHasMoreResults && streamResults) {
//clearInputStream();
//
//throw SQLError.createSQLException(Messages.getString("MysqlIO.23"),
//SQLError.SQL_STATE_DRIVER_NOT_CAPABLE);
if (topLevelResultSet.getUpdateCount() != -1) {
tackOnMoreStreamingResults(topLevelResultSet);
}
reclaimLargeReusablePacket();
return topLevelResultSet;
}
boolean moreRowSetsExist = checkForMoreResults & serverHasMoreResults;
while (moreRowSetsExist) {
Buffer fieldPacket = checkErrorPacket();
fieldPacket.setPosition(0);
ResultSetImpl newResultSet = readResultsForQueryOrUpdate(callingStatement, maxRows, resultSetType, resultSetConcurrency, streamResults, catalog,
fieldPacket, isBinaryEncoded, preSentColumnCount, metadataFromCache);
currentResultSet.setNextResultSet(newResultSet);
currentResultSet = newResultSet;
moreRowSetsExist = (this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0;
}
if (!streamResults) {
clearInputStream();
}
reclaimLargeReusablePacket();
return topLevelResultSet;
}
/**
* Sets the buffer size to max-buf
*/
void resetMaxBuf() {
this.maxAllowedPacket = this.connection.getMaxAllowedPacket();
}
/**
* Send a command to the MySQL server If data is to be sent with command,
* it should be put in extraData.
*
* Raw packets can be sent by setting queryPacket to something other
* than null.
*
* @param command
* the MySQL protocol 'command' from MysqlDefs
* @param extraData
* any 'string' data for the command
* @param queryPacket
* a packet pre-loaded with data for the protocol (i.e.
* from a client-side prepared statement).
* @param skipCheck
* do not call checkErrorPacket() if true
* @param extraDataCharEncoding
* the character encoding of the extraData
* parameter.
*
* @return the response packet from the server
*
* @throws SQLException
* if an I/O error or SQL error occurs
*/
final Buffer sendCommand(int command, String extraData, Buffer queryPacket, boolean skipCheck, String extraDataCharEncoding, int timeoutMillis)
throws SQLException {
this.commandCount++;
//
// We cache these locally, per-command, as the checks for them are in very 'hot' sections of the I/O code and we save 10-15% in overall performance by
// doing this...
//
this.enablePacketDebug = this.connection.getEnablePacketDebug();
this.readPacketSequence = 0;
int oldTimeout = 0;
if (timeoutMillis != 0) {
try {
oldTimeout = this.mysqlConnection.getSoTimeout();
this.mysqlConnection.setSoTimeout(timeoutMillis);
} catch (SocketException e) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, e,
getExceptionInterceptor());
}
}
try {
checkForOutstandingStreamingData();
// Clear serverStatus...this value is guarded by an external mutex, as you can only ever be processing one command at a time
this.oldServerStatus = this.serverStatus;
this.serverStatus = 0;
this.hadWarnings = false;
this.warningCount = 0;
this.queryNoIndexUsed = false;
this.queryBadIndexUsed = false;
this.serverQueryWasSlow = false;
//
// Compressed input stream needs cleared at beginning of each command execution...
//
if (this.useCompression) {
int bytesLeft = this.mysqlInput.available();
if (bytesLeft > 0) {
this.mysqlInput.skip(bytesLeft);
}
}
try {
clearInputStream();
//
// PreparedStatements construct their own packets, for efficiency's sake.
//
// If this is a generic query, we need to re-use the sending packet.
//
if (queryPacket == null) {
int packLength = HEADER_LENGTH + COMP_HEADER_LENGTH + 1 + ((extraData != null) ? extraData.length() : 0) + 2;
if (this.sendPacket == null) {
this.sendPacket = new Buffer(packLength);
}
this.packetSequence = -1;
this.compressedPacketSequence = -1;
this.readPacketSequence = 0;
this.checkPacketSequence = true;
this.sendPacket.clear();
this.sendPacket.writeByte((byte) command);
if ((command == MysqlDefs.INIT_DB) || (command == MysqlDefs.CREATE_DB) || (command == MysqlDefs.DROP_DB) || (command == MysqlDefs.QUERY)
|| (command == MysqlDefs.COM_PREPARE)) {
if (extraDataCharEncoding == null) {
this.sendPacket.writeStringNoNull(extraData);
} else {
this.sendPacket.writeStringNoNull(extraData, extraDataCharEncoding, this.connection.getServerCharset(),
this.connection.parserKnowsUnicode(), this.connection);
}
} else if (command == MysqlDefs.PROCESS_KILL) {
long id = Long.parseLong(extraData);
this.sendPacket.writeLong(id);
}
send(this.sendPacket, this.sendPacket.getPosition());
} else {
this.packetSequence = -1;
this.compressedPacketSequence = -1;
send(queryPacket, queryPacket.getPosition()); // packet passed by PreparedStatement
}
} catch (SQLException sqlEx) {
// don't wrap SQLExceptions
throw sqlEx;
} catch (Exception ex) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ex,
getExceptionInterceptor());
}
Buffer returnPacket = null;
if (!skipCheck) {
if ((command == MysqlDefs.COM_EXECUTE) || (command == MysqlDefs.COM_RESET_STMT)) {
this.readPacketSequence = 0;
this.packetSequenceReset = true;
}
returnPacket = checkErrorPacket(command);
}
return returnPacket;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} finally {
if (timeoutMillis != 0) {
try {
this.mysqlConnection.setSoTimeout(oldTimeout);
} catch (SocketException e) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, e,
getExceptionInterceptor());
}
}
}
}
private int statementExecutionDepth = 0;
private boolean useAutoSlowLog;
protected boolean shouldIntercept() {
return this.statementInterceptors != null;
}
/**
* Send a query stored in a packet directly to the server.
*
* @param callingStatement
* @param resultSetConcurrency
* @param characterEncoding
* @param queryPacket
* @param maxRows
* @param conn
* @param resultSetType
* @param resultSetConcurrency
* @param streamResults
* @param catalog
* @param unpackFieldInfo
* should we read MYSQL_FIELD info (if available)?
*
* @throws Exception
*/
final ResultSetInternalMethods sqlQueryDirect(StatementImpl callingStatement, String query, String characterEncoding, Buffer queryPacket, int maxRows,
int resultSetType, int resultSetConcurrency, boolean streamResults, String catalog, Field[] cachedMetadata) throws Exception {
this.statementExecutionDepth++;
try {
if (this.statementInterceptors != null) {
ResultSetInternalMethods interceptedResults = invokeStatementInterceptorsPre(query, callingStatement, false);
if (interceptedResults != null) {
return interceptedResults;
}
}
long queryStartTime = 0;
long queryEndTime = 0;
String statementComment = this.connection.getStatementComment();
if (this.connection.getIncludeThreadNamesAsStatementComment()) {
statementComment = (statementComment != null ? statementComment + ", " : "") + "java thread: " + Thread.currentThread().getName();
}
if (query != null) {
// We don't know exactly how many bytes we're going to get from the query. Since we're dealing with Unicode, the max is 2, so pad it
// (2 * query) + space for headers
int packLength = HEADER_LENGTH + 1 + (query.length() * 3) + 2;
byte[] commentAsBytes = null;
if (statementComment != null) {
commentAsBytes = StringUtils.getBytes(statementComment, null, characterEncoding, this.connection.getServerCharset(),
this.connection.parserKnowsUnicode(), getExceptionInterceptor());
packLength += commentAsBytes.length;
packLength += 6; // for /*[space] [space]*/
}
if (this.sendPacket == null) {
this.sendPacket = new Buffer(packLength);
} else {
this.sendPacket.clear();
}
this.sendPacket.writeByte((byte) MysqlDefs.QUERY);
if (commentAsBytes != null) {
this.sendPacket.writeBytesNoNull(Constants.SLASH_STAR_SPACE_AS_BYTES);
this.sendPacket.writeBytesNoNull(commentAsBytes);
this.sendPacket.writeBytesNoNull(Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
}
if (characterEncoding != null) {
if (this.platformDbCharsetMatches) {
this.sendPacket.writeStringNoNull(query, characterEncoding, this.connection.getServerCharset(), this.connection.parserKnowsUnicode(),
this.connection);
} else {
if (StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) {
this.sendPacket.writeBytesNoNull(StringUtils.getBytes(query));
} else {
this.sendPacket.writeStringNoNull(query, characterEncoding, this.connection.getServerCharset(),
this.connection.parserKnowsUnicode(), this.connection);
}
}
} else {
this.sendPacket.writeStringNoNull(query);
}
queryPacket = this.sendPacket;
}
byte[] queryBuf = null;
int oldPacketPosition = 0;
if (this.needToGrabQueryFromPacket) {
queryBuf = queryPacket.getByteBuffer();
// save the packet position
oldPacketPosition = queryPacket.getPosition();
queryStartTime = getCurrentTimeNanosOrMillis();
}
if (this.autoGenerateTestcaseScript) {
String testcaseQuery = null;
if (query != null) {
if (statementComment != null) {
testcaseQuery = "/* " + statementComment + " */ " + query;
} else {
testcaseQuery = query;
}
} else {
testcaseQuery = StringUtils.toString(queryBuf, 5, (oldPacketPosition - 5));
}
StringBuilder debugBuf = new StringBuilder(testcaseQuery.length() + 32);
this.connection.generateConnectionCommentBlock(debugBuf);
debugBuf.append(testcaseQuery);
debugBuf.append(';');
this.connection.dumpTestcaseQuery(debugBuf.toString());
}
// Send query command and sql query string
Buffer resultPacket = sendCommand(MysqlDefs.QUERY, null, queryPacket, false, null, 0);
long fetchBeginTime = 0;
long fetchEndTime = 0;
String profileQueryToLog = null;
boolean queryWasSlow = false;
if (this.profileSql || this.logSlowQueries) {
queryEndTime = getCurrentTimeNanosOrMillis();
boolean shouldExtractQuery = false;
if (this.profileSql) {
shouldExtractQuery = true;
} else if (this.logSlowQueries) {
long queryTime = queryEndTime - queryStartTime;
boolean logSlow = false;
if (!this.useAutoSlowLog) {
logSlow = queryTime > this.connection.getSlowQueryThresholdMillis();
} else {
logSlow = this.connection.isAbonormallyLongQuery(queryTime);
this.connection.reportQueryTime(queryTime);
}
if (logSlow) {
shouldExtractQuery = true;
queryWasSlow = true;
}
}
if (shouldExtractQuery) {
// Extract the actual query from the network packet
boolean truncated = false;
int extractPosition = oldPacketPosition;
if (oldPacketPosition > this.connection.getMaxQuerySizeToLog()) {
extractPosition = this.connection.getMaxQuerySizeToLog() + 5;
truncated = true;
}
profileQueryToLog = StringUtils.toString(queryBuf, 5, (extractPosition - 5));
if (truncated) {
profileQueryToLog += Messages.getString("MysqlIO.25");
}
}
fetchBeginTime = queryEndTime;
}
ResultSetInternalMethods rs = readAllResults(callingStatement, maxRows, resultSetType, resultSetConcurrency, streamResults, catalog, resultPacket,
false, -1L, cachedMetadata);
if (queryWasSlow && !this.serverQueryWasSlow /* don't log slow queries twice */) {
StringBuilder mesgBuf = new StringBuilder(48 + profileQueryToLog.length());
mesgBuf.append(Messages.getString("MysqlIO.SlowQuery",
new Object[] { String.valueOf(this.useAutoSlowLog ? " 95% of all queries " : this.slowQueryThreshold), this.queryTimingUnits,
Long.valueOf(queryEndTime - queryStartTime) }));
mesgBuf.append(profileQueryToLog);
ProfilerEventHandler eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(int) (queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
mesgBuf.toString()));
if (this.connection.getExplainSlowQueries()) {
if (oldPacketPosition < MAX_QUERY_SIZE_TO_EXPLAIN) {
explainSlowQuery(queryPacket.getBytes(5, (oldPacketPosition - 5)), profileQueryToLog);
} else {
this.connection.getLog().logWarn(Messages.getString("MysqlIO.28") + MAX_QUERY_SIZE_TO_EXPLAIN + Messages.getString("MysqlIO.29"));
}
}
}
if (this.logSlowQueries) {
ProfilerEventHandler eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
if (this.queryBadIndexUsed && this.profileSql) {
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
Messages.getString("MysqlIO.33") + profileQueryToLog));
}
if (this.queryNoIndexUsed && this.profileSql) {
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
Messages.getString("MysqlIO.35") + profileQueryToLog));
}
if (this.serverQueryWasSlow && this.profileSql) {
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
Messages.getString("MysqlIO.ServerSlowQuery") + profileQueryToLog));
}
}
if (this.profileSql) {
fetchEndTime = getCurrentTimeNanosOrMillis();
ProfilerEventHandler eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()), profileQueryToLog));
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_FETCH, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(fetchEndTime - fetchBeginTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()), null));
}
if (this.hadWarnings) {
scanForAndThrowDataTruncation();
}
if (this.statementInterceptors != null) {
ResultSetInternalMethods interceptedResults = invokeStatementInterceptorsPost(query, callingStatement, rs, false, null);
if (interceptedResults != null) {
rs = interceptedResults;
}
}
return rs;
} catch (SQLException sqlEx) {
if (this.statementInterceptors != null) {
invokeStatementInterceptorsPost(query, callingStatement, null, false, sqlEx); // we don't do anything with the result set in this case
}
if (callingStatement != null) {
synchronized (callingStatement.cancelTimeoutMutex) {
if (callingStatement.wasCancelled) {
SQLException cause = null;
if (callingStatement.wasCancelledByTimeout) {
cause = new MySQLTimeoutException();
} else {
cause = new MySQLStatementCancelledException();
}
callingStatement.resetCancelledState();
throw cause;
}
}
}
throw sqlEx;
} finally {
this.statementExecutionDepth--;
}
}
ResultSetInternalMethods invokeStatementInterceptorsPre(String sql, Statement interceptedStatement, boolean forceExecute) throws SQLException {
ResultSetInternalMethods previousResultSet = null;
for (int i = 0, s = this.statementInterceptors.size(); i < s; i++) {
StatementInterceptorV2 interceptor = this.statementInterceptors.get(i);
boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);
if (shouldExecute) {
String sqlToInterceptor = sql;
//if (interceptedStatement instanceof PreparedStatement) {
// sqlToInterceptor = ((PreparedStatement) interceptedStatement)
// .asSql();
//}
ResultSetInternalMethods interceptedResultSet = interceptor.preProcess(sqlToInterceptor, interceptedStatement, this.connection);
if (interceptedResultSet != null) {
previousResultSet = interceptedResultSet;
}
}
}
return previousResultSet;
}
ResultSetInternalMethods invokeStatementInterceptorsPost(String sql, Statement interceptedStatement, ResultSetInternalMethods originalResultSet,
boolean forceExecute, SQLException statementException) throws SQLException {
for (int i = 0, s = this.statementInterceptors.size(); i < s; i++) {
StatementInterceptorV2 interceptor = this.statementInterceptors.get(i);
boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);
if (shouldExecute) {
String sqlToInterceptor = sql;
ResultSetInternalMethods interceptedResultSet = interceptor.postProcess(sqlToInterceptor, interceptedStatement, originalResultSet,
this.connection, this.warningCount, this.queryNoIndexUsed, this.queryBadIndexUsed, statementException);
if (interceptedResultSet != null) {
originalResultSet = interceptedResultSet;
}
}
}
return originalResultSet;
}
private void calculateSlowQueryThreshold() {
this.slowQueryThreshold = this.connection.getSlowQueryThresholdMillis();
if (this.connection.getUseNanosForElapsedTime()) {
long nanosThreshold = this.connection.getSlowQueryThresholdNanos();
if (nanosThreshold != 0) {
this.slowQueryThreshold = nanosThreshold;
} else {
this.slowQueryThreshold *= 1000000; // 1 million millis in a nano
}
}
}
protected long getCurrentTimeNanosOrMillis() {
if (this.useNanosForElapsedTime) {
return TimeUtil.getCurrentTimeNanosOrMillis();
}
return System.currentTimeMillis();
}
/**
* Returns the host this IO is connected to
*/
String getHost() {
return this.host;
}
/**
* Is the version of the MySQL server we are connected to the given
* version?
*
* @param major
* the major version
* @param minor
* the minor version
* @param subminor
* the subminor version
*
* @return true if the version of the MySQL server we are connected is the
* given version
*/
boolean isVersion(int major, int minor, int subminor) {
return ((major == getServerMajorVersion()) && (minor == getServerMinorVersion()) && (subminor == getServerSubMinorVersion()));
}
/**
* Does the version of the MySQL server we are connected to meet the given
* minimums?
*
* @param major
* @param minor
* @param subminor
*/
boolean versionMeetsMinimum(int major, int minor, int subminor) {
if (getServerMajorVersion() >= major) {
if (getServerMajorVersion() == major) {
if (getServerMinorVersion() >= minor) {
if (getServerMinorVersion() == minor) {
return (getServerSubMinorVersion() >= subminor);
}
// newer than major.minor
return true;
}
// older than major.minor
return false;
}
// newer than major
return true;
}
return false;
}
/**
* Returns the hex dump of the given packet, truncated to
* MAX_PACKET_DUMP_LENGTH if packetLength exceeds that value.
*
* @param packetToDump
* the packet to dump in hex
* @param packetLength
* the number of bytes to dump
*
* @return the hex dump of the given packet
*/
private final static String getPacketDumpToLog(Buffer packetToDump, int packetLength) {
if (packetLength < MAX_PACKET_DUMP_LENGTH) {
return packetToDump.dump(packetLength);
}
StringBuilder packetDumpBuf = new StringBuilder(MAX_PACKET_DUMP_LENGTH * 4);
packetDumpBuf.append(packetToDump.dump(MAX_PACKET_DUMP_LENGTH));
packetDumpBuf.append(Messages.getString("MysqlIO.36"));
packetDumpBuf.append(MAX_PACKET_DUMP_LENGTH);
packetDumpBuf.append(Messages.getString("MysqlIO.37"));
return packetDumpBuf.toString();
}
private final int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
if (len < 0) {
throw new IndexOutOfBoundsException();
}
int n = 0;
while (n < len) {
int count = in.read(b, off + n, len - n);
if (count < 0) {
throw new EOFException(Messages.getString("MysqlIO.EOF", new Object[] { Integer.valueOf(len), Integer.valueOf(n) }));
}
n += count;
}
return n;
}
private final long skipFully(InputStream in, long len) throws IOException {
if (len < 0) {
throw new IOException("Negative skip length not allowed");
}
long n = 0;
while (n < len) {
long count = in.skip(len - n);
if (count < 0) {
throw new EOFException(Messages.getString("MysqlIO.EOF", new Object[] { Long.valueOf(len), Long.valueOf(n) }));
}
n += count;
}
return n;
}
private final int skipLengthEncodedInteger(InputStream in) throws IOException {
int sw = in.read() & 0xff;
switch (sw) {
case 252:
return (int) skipFully(in, 2) + 1;
case 253:
return (int) skipFully(in, 3) + 1;
case 254:
return (int) skipFully(in, 8) + 1;
default:
return 1;
}
}
/**
* Reads one result set off of the wire, if the result is actually an
* update count, creates an update-count only result set.
*
* @param callingStatement
* @param maxRows
* the maximum rows to return in the result set.
* @param resultSetType
* scrollability
* @param resultSetConcurrency
* updatability
* @param streamResults
* should the driver leave the results on the wire,
* and read them only when needed?
* @param catalog
* the catalog in use
* @param resultPacket
* the first packet of information in the result set
* @param isBinaryEncoded
* is this result set from a prepared statement?
* @param preSentColumnCount
* do we already know the number of columns?
* @param unpackFieldInfo
* should we unpack the field information?
*
* @return a result set that either represents the rows, or an update count
*
* @throws SQLException
* if an error occurs while reading the rows
*/
protected final ResultSetImpl readResultsForQueryOrUpdate(StatementImpl callingStatement, int maxRows, int resultSetType, int resultSetConcurrency,
boolean streamResults, String catalog, Buffer resultPacket, boolean isBinaryEncoded, long preSentColumnCount, Field[] metadataFromCache)
throws SQLException {
long columnCount = resultPacket.readFieldLength();
if (columnCount == 0) {
return buildResultSetWithUpdates(callingStatement, resultPacket);
} else if (columnCount == Buffer.NULL_LENGTH) {
String charEncoding = null;
if (this.connection.getUseUnicode()) {
charEncoding = this.connection.getEncoding();
}
String fileName = null;
if (this.platformDbCharsetMatches) {
fileName = ((charEncoding != null) ? resultPacket.readString(charEncoding, getExceptionInterceptor()) : resultPacket.readString());
} else {
fileName = resultPacket.readString();
}
return sendFileToServer(callingStatement, fileName);
} else {
com.mysql.jdbc.ResultSetImpl results = getResultSet(callingStatement, columnCount, maxRows, resultSetType, resultSetConcurrency, streamResults,
catalog, isBinaryEncoded, metadataFromCache);
return results;
}
}
private int alignPacketSize(int a, int l) {
return ((((a) + (l)) - 1) & ~((l) - 1));
}
private com.mysql.jdbc.ResultSetImpl buildResultSetWithRows(StatementImpl callingStatement, String catalog, com.mysql.jdbc.Field[] fields, RowData rows,
int resultSetType, int resultSetConcurrency, boolean isBinaryEncoded) throws SQLException {
ResultSetImpl rs = null;
switch (resultSetConcurrency) {
case java.sql.ResultSet.CONCUR_READ_ONLY:
rs = com.mysql.jdbc.ResultSetImpl.getInstance(catalog, fields, rows, this.connection, callingStatement, false);
if (isBinaryEncoded) {
rs.setBinaryEncoded();
}
break;
case java.sql.ResultSet.CONCUR_UPDATABLE:
rs = com.mysql.jdbc.ResultSetImpl.getInstance(catalog, fields, rows, this.connection, callingStatement, true);
break;
default:
return com.mysql.jdbc.ResultSetImpl.getInstance(catalog, fields, rows, this.connection, callingStatement, false);
}
rs.setResultSetType(resultSetType);
rs.setResultSetConcurrency(resultSetConcurrency);
return rs;
}
private com.mysql.jdbc.ResultSetImpl buildResultSetWithUpdates(StatementImpl callingStatement, Buffer resultPacket) throws SQLException {
long updateCount = -1;
long updateID = -1;
String info = null;
try {
if (this.useNewUpdateCounts) {
updateCount = resultPacket.newReadLength();
updateID = resultPacket.newReadLength();
} else {
updateCount = resultPacket.readLength();
updateID = resultPacket.readLength();
}
if (this.use41Extensions) {
// oldStatus set in sendCommand()
this.serverStatus = resultPacket.readInt();
checkTransactionState(this.oldServerStatus);
this.warningCount = resultPacket.readInt();
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
resultPacket.readByte(); // advance pointer
setServerSlowQueryFlags();
}
if (this.connection.isReadInfoMsgEnabled()) {
info = resultPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor());
}
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(SQLError.get(SQLError.SQL_STATE_GENERAL_ERROR), SQLError.SQL_STATE_GENERAL_ERROR, -1,
getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
ResultSetInternalMethods updateRs = com.mysql.jdbc.ResultSetImpl.getInstance(updateCount, updateID, this.connection, callingStatement);
if (info != null) {
((com.mysql.jdbc.ResultSetImpl) updateRs).setServerInfo(info);
}
return (com.mysql.jdbc.ResultSetImpl) updateRs;
}
private void setServerSlowQueryFlags() {
this.queryBadIndexUsed = (this.serverStatus & SERVER_QUERY_NO_GOOD_INDEX_USED) != 0;
this.queryNoIndexUsed = (this.serverStatus & SERVER_QUERY_NO_INDEX_USED) != 0;
this.serverQueryWasSlow = (this.serverStatus & SERVER_QUERY_WAS_SLOW) != 0;
}
private void checkForOutstandingStreamingData() throws SQLException {
if (this.streamingData != null) {
boolean shouldClobber = this.connection.getClobberStreamingResults();
if (!shouldClobber) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.39") + this.streamingData + Messages.getString("MysqlIO.40")
+ Messages.getString("MysqlIO.41") + Messages.getString("MysqlIO.42"), getExceptionInterceptor());
}
// Close the result set
this.streamingData.getOwner().realClose(false);
// clear any pending data....
clearInputStream();
}
}
/**
* @param packet
* original uncompressed MySQL packet
* @param offset
* begin of MySQL packet header
* @param packetLen
* real length of packet
* @return compressed packet with header
* @throws SQLException
*/
private Buffer compressPacket(Buffer packet, int offset, int packetLen) throws SQLException {
// uncompressed payload by default
int compressedLength = packetLen;
int uncompressedLength = 0;
byte[] compressedBytes = null;
int offsetWrite = offset;
if (packetLen < MIN_COMPRESS_LEN) {
compressedBytes = packet.getByteBuffer();
} else {
byte[] bytesToCompress = packet.getByteBuffer();
compressedBytes = new byte[bytesToCompress.length * 2];
if (this.deflater == null) {
this.deflater = new Deflater();
}
this.deflater.reset();
this.deflater.setInput(bytesToCompress, offset, packetLen);
this.deflater.finish();
compressedLength = this.deflater.deflate(compressedBytes);
if (compressedLength > packetLen) {
// if compressed data is greater then uncompressed then send uncompressed
compressedBytes = packet.getByteBuffer();
compressedLength = packetLen;
} else {
uncompressedLength = packetLen;
offsetWrite = 0;
}
}
Buffer compressedPacket = new Buffer(HEADER_LENGTH + COMP_HEADER_LENGTH + compressedLength);
compressedPacket.setPosition(0);
compressedPacket.writeLongInt(compressedLength);
compressedPacket.writeByte(this.compressedPacketSequence);
compressedPacket.writeLongInt(uncompressedLength);
compressedPacket.writeBytesNoNull(compressedBytes, offsetWrite, compressedLength);
return compressedPacket;
}
private final void readServerStatusForResultSets(Buffer rowPacket) throws SQLException {
if (this.use41Extensions) {
rowPacket.readByte(); // skips the 'last packet' flag
if (isEOFDeprecated()) {
// read OK packet
rowPacket.newReadLength(); // affected_rows
rowPacket.newReadLength(); // last_insert_id
this.oldServerStatus = this.serverStatus;
this.serverStatus = rowPacket.readInt();
checkTransactionState(this.oldServerStatus);
this.warningCount = rowPacket.readInt();
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
rowPacket.readByte(); // advance pointer
if (this.connection.isReadInfoMsgEnabled()) {
rowPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor()); // info
}
} else {
// read EOF packet
this.warningCount = rowPacket.readInt();
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
this.oldServerStatus = this.serverStatus;
this.serverStatus = rowPacket.readInt();
checkTransactionState(this.oldServerStatus);
}
setServerSlowQueryFlags();
}
}
private SocketFactory createSocketFactory() throws SQLException {
try {
if (this.socketFactoryClassName == null) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.75"), SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE,
getExceptionInterceptor());
}
return (SocketFactory) (Class.forName(this.socketFactoryClassName).newInstance());
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("MysqlIO.76") + this.socketFactoryClassName + Messages.getString("MysqlIO.77"),
SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
}
private void enqueuePacketForDebugging(boolean isPacketBeingSent, boolean isPacketReused, int sendLength, byte[] header, Buffer packet)
throws SQLException {
if ((this.packetDebugRingBuffer.size() + 1) > this.connection.getPacketDebugBufferSize()) {
this.packetDebugRingBuffer.removeFirst();
}
StringBuilder packetDump = null;
if (!isPacketBeingSent) {
int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, packet.getBufLength());
Buffer packetToDump = new Buffer(4 + bytesToDump);
packetToDump.setPosition(0);
packetToDump.writeBytesNoNull(header);
packetToDump.writeBytesNoNull(packet.getBytes(0, bytesToDump));
String packetPayload = packetToDump.dump(bytesToDump);
packetDump = new StringBuilder(96 + packetPayload.length());
packetDump.append("Server ");
packetDump.append(isPacketReused ? "(re-used) " : "(new) ");
packetDump.append(packet.toSuperString());
packetDump.append(" --------------------> Client\n");
packetDump.append("\nPacket payload:\n\n");
packetDump.append(packetPayload);
if (bytesToDump == MAX_PACKET_DUMP_LENGTH) {
packetDump.append("\nNote: Packet of " + packet.getBufLength() + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + " bytes.\n");
}
} else {
int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, sendLength);
String packetPayload = packet.dump(bytesToDump);
packetDump = new StringBuilder(64 + 4 + packetPayload.length());
packetDump.append("Client ");
packetDump.append(packet.toSuperString());
packetDump.append("--------------------> Server\n");
packetDump.append("\nPacket payload:\n\n");
packetDump.append(packetPayload);
if (bytesToDump == MAX_PACKET_DUMP_LENGTH) {
packetDump.append("\nNote: Packet of " + sendLength + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + " bytes.\n");
}
}
this.packetDebugRingBuffer.addLast(packetDump);
}
private RowData readSingleRowSet(long columnCount, int maxRows, int resultSetConcurrency, boolean isBinaryEncoded, Field[] fields) throws SQLException {
RowData rowData;
ArrayList<ResultSetRow> rows = new ArrayList<ResultSetRow>();
boolean useBufferRowExplicit = useBufferRowExplicit(fields);
// Now read the data
ResultSetRow row = nextRow(fields, (int) columnCount, isBinaryEncoded, resultSetConcurrency, false, useBufferRowExplicit, false, null);
int rowCount = 0;
if (row != null) {
rows.add(row);
rowCount = 1;
}
while (row != null) {
row = nextRow(fields, (int) columnCount, isBinaryEncoded, resultSetConcurrency, false, useBufferRowExplicit, false, null);
if (row != null) {
if ((maxRows == -1) || (rowCount < maxRows)) {
rows.add(row);
rowCount++;
}
}
}
rowData = new RowDataStatic(rows);
return rowData;
}
public static boolean useBufferRowExplicit(Field[] fields) {
if (fields == null) {
return false;
}
for (int i = 0; i < fields.length; i++) {
switch (fields[i].getSQLType()) {
case Types.BLOB:
case Types.CLOB:
case Types.LONGVARBINARY:
case Types.LONGVARCHAR:
return true;
}
}
return false;
}
/**
* Don't hold on to overly-large packets
*/
private void reclaimLargeReusablePacket() {
if ((this.reusablePacket != null) && (this.reusablePacket.getCapacity() > 1048576)) {
this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE);
}
}
/**
* Re-use a packet to read from the MySQL server
*
* @param reuse
* @throws SQLException
*/
private final Buffer reuseAndReadPacket(Buffer reuse) throws SQLException {
return reuseAndReadPacket(reuse, -1);
}
private final Buffer reuseAndReadPacket(Buffer reuse, int existingPacketLength) throws SQLException {
try {
reuse.setWasMultiPacket(false);
int packetLength = 0;
if (existingPacketLength == -1) {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.43"));
}
packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
} else {
packetLength = existingPacketLength;
}
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.44"));
traceMessageBuf.append(packetLength);
traceMessageBuf.append(Messages.getString("MysqlIO.45"));
traceMessageBuf.append(StringUtils.dumpAsHex(this.packetHeaderBuf, 4));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
byte multiPacketSeq = this.packetHeaderBuf[3];
if (!this.packetSequenceReset) {
if (this.enablePacketDebug && this.checkPacketSequence) {
checkPacketSequencing(multiPacketSeq);
}
} else {
this.packetSequenceReset = false;
}
this.readPacketSequence = multiPacketSeq;
// Set the Buffer to it's original state
reuse.setPosition(0);
// Do we need to re-alloc the byte buffer?
//
// Note: We actually check the length of the buffer, rather than getBufLength(), because getBufLength() is not necesarily the actual length of the
// byte array used as the buffer
if (reuse.getByteBuffer().length <= packetLength) {
reuse.setByteBuffer(new byte[packetLength + 1]);
}
// Set the new length
reuse.setBufLength(packetLength);
// Read the data from the server
int numBytesRead = readFully(this.mysqlInput, reuse.getByteBuffer(), 0, packetLength);
if (numBytesRead != packetLength) {
throw new IOException("Short read, expected " + packetLength + " bytes, only read " + numBytesRead);
}
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.46"));
traceMessageBuf.append(getPacketDumpToLog(reuse, packetLength));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
if (this.enablePacketDebug) {
enqueuePacketForDebugging(false, true, 0, this.packetHeaderBuf, reuse);
}
boolean isMultiPacket = false;
if (packetLength == this.maxThreeBytes) {
reuse.setPosition(this.maxThreeBytes);
// it's multi-packet
isMultiPacket = true;
packetLength = readRemainingMultiPackets(reuse, multiPacketSeq);
}
if (!isMultiPacket) {
reuse.getByteBuffer()[packetLength] = 0; // Null-termination
}
if (this.connection.getMaintainTimeStats()) {
this.lastPacketReceivedTimeMs = System.currentTimeMillis();
}
return reuse;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
try {
// _Try_ this
clearInputStream();
} catch (Exception ex) {
}
try {
this.connection.realClose(false, false, true, oom);
} catch (Exception ex) {
}
throw oom;
}
}
private int readRemainingMultiPackets(Buffer reuse, byte multiPacketSeq) throws IOException, SQLException {
int packetLength = -1;
Buffer multiPacket = null;
do {
final int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.47"));
}
packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
if (multiPacket == null) {
multiPacket = new Buffer(packetLength);
}
if (!this.useNewLargePackets && (packetLength == 1)) {
clearInputStream();
break;
}
multiPacketSeq++;
if (multiPacketSeq != this.packetHeaderBuf[3]) {
throw new IOException(Messages.getString("MysqlIO.49"));
}
// Set the Buffer to it's original state
multiPacket.setPosition(0);
// Set the new length
multiPacket.setBufLength(packetLength);
// Read the data from the server
byte[] byteBuf = multiPacket.getByteBuffer();
int lengthToWrite = packetLength;
int bytesRead = readFully(this.mysqlInput, byteBuf, 0, packetLength);
if (bytesRead != lengthToWrite) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
SQLError.createSQLException(Messages.getString("MysqlIO.50") + lengthToWrite + Messages.getString("MysqlIO.51") + bytesRead + ".",
getExceptionInterceptor()),
getExceptionInterceptor());
}
reuse.writeBytesNoNull(byteBuf, 0, lengthToWrite);
} while (packetLength == this.maxThreeBytes);
reuse.setPosition(0);
reuse.setWasMultiPacket(true);
return packetLength;
}
/**
* @param multiPacketSeq
* @throws CommunicationsException
*/
private void checkPacketSequencing(byte multiPacketSeq) throws SQLException {
if ((multiPacketSeq == -128) && (this.readPacketSequence != 127)) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException("Packets out of order, expected packet # -128, but received packet # " + multiPacketSeq), getExceptionInterceptor());
}
if ((this.readPacketSequence == -1) && (multiPacketSeq != 0)) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException("Packets out of order, expected packet # -1, but received packet # " + multiPacketSeq), getExceptionInterceptor());
}
if ((multiPacketSeq != -128) && (this.readPacketSequence != -1) && (multiPacketSeq != (this.readPacketSequence + 1))) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException("Packets out of order, expected packet # " + (this.readPacketSequence + 1) + ", but received packet # " + multiPacketSeq),
getExceptionInterceptor());
}
}
void enableMultiQueries() throws SQLException {
Buffer buf = getSharedSendPacket();
buf.clear();
buf.writeByte((byte) MysqlDefs.COM_SET_OPTION);
buf.writeInt(0);
sendCommand(MysqlDefs.COM_SET_OPTION, null, buf, false, null, 0);
}
void disableMultiQueries() throws SQLException {
Buffer buf = getSharedSendPacket();
buf.clear();
buf.writeByte((byte) MysqlDefs.COM_SET_OPTION);
buf.writeInt(1);
sendCommand(MysqlDefs.COM_SET_OPTION, null, buf, false, null, 0);
}
/**
* @param packet
* @param packetLen
* length of header + payload
* @throws SQLException
*/
private final void send(Buffer packet, int packetLen) throws SQLException {
try {
if (this.maxAllowedPacket > 0 && packetLen > this.maxAllowedPacket) {
throw new PacketTooBigException(packetLen, this.maxAllowedPacket);
}
if ((this.serverMajorVersion >= 4) && (packetLen - HEADER_LENGTH >= this.maxThreeBytes
|| (this.useCompression && packetLen - HEADER_LENGTH >= this.maxThreeBytes - COMP_HEADER_LENGTH))) {
sendSplitPackets(packet, packetLen);
} else {
this.packetSequence++;
Buffer packetToSend = packet;
packetToSend.setPosition(0);
packetToSend.writeLongInt(packetLen - HEADER_LENGTH);
packetToSend.writeByte(this.packetSequence);
if (this.useCompression) {
this.compressedPacketSequence++;
int originalPacketLen = packetLen;
packetToSend = compressPacket(packetToSend, 0, packetLen);
packetLen = packetToSend.getPosition();
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.57"));
traceMessageBuf.append(getPacketDumpToLog(packetToSend, packetLen));
traceMessageBuf.append(Messages.getString("MysqlIO.58"));
traceMessageBuf.append(getPacketDumpToLog(packet, originalPacketLen));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
} else {
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.59"));
traceMessageBuf.append("host: '");
traceMessageBuf.append(this.host);
traceMessageBuf.append("' threadId: '");
traceMessageBuf.append(this.threadId);
traceMessageBuf.append("'\n");
traceMessageBuf.append(packetToSend.dump(packetLen));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
}
this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, packetLen);
this.mysqlOutput.flush();
}
if (this.enablePacketDebug) {
enqueuePacketForDebugging(true, false, packetLen + 5, this.packetHeaderBuf, packet);
}
//
// Don't hold on to large packets
//
if (packet == this.sharedSendPacket) {
reclaimLargeSharedSendPacket();
}
if (this.connection.getMaintainTimeStats()) {
this.lastPacketSentTimeMs = System.currentTimeMillis();
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* Reads and sends a file to the server for LOAD DATA LOCAL INFILE
*
* @param callingStatement
* @param fileName
* the file name to send.
*
* @throws SQLException
*/
private final ResultSetImpl sendFileToServer(StatementImpl callingStatement, String fileName) throws SQLException {
if (this.useCompression) {
this.compressedPacketSequence++;
}
Buffer filePacket = (this.loadFileBufRef == null) ? null : this.loadFileBufRef.get();
int bigPacketLength = Math.min(this.connection.getMaxAllowedPacket() - (HEADER_LENGTH * 3),
alignPacketSize(this.connection.getMaxAllowedPacket() - 16, 4096) - (HEADER_LENGTH * 3));
int oneMeg = 1024 * 1024;
int smallerPacketSizeAligned = Math.min(oneMeg - (HEADER_LENGTH * 3), alignPacketSize(oneMeg - 16, 4096) - (HEADER_LENGTH * 3));
int packetLength = Math.min(smallerPacketSizeAligned, bigPacketLength);
if (filePacket == null) {
try {
filePacket = new Buffer((packetLength + HEADER_LENGTH));
this.loadFileBufRef = new SoftReference<Buffer>(filePacket);
} catch (OutOfMemoryError oom) {
throw SQLError.createSQLException(
"Could not allocate packet of " + packetLength + " bytes required for LOAD DATA LOCAL INFILE operation."
+ " Try increasing max heap allocation for JVM or decreasing server variable 'max_allowed_packet'",
SQLError.SQL_STATE_MEMORY_ALLOCATION_FAILURE, getExceptionInterceptor());
}
}
filePacket.clear();
send(filePacket, 0);
byte[] fileBuf = new byte[packetLength];
BufferedInputStream fileIn = null;
try {
if (!this.connection.getAllowLoadLocalInfile()) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.LoadDataLocalNotAllowed"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
InputStream hookedStream = null;
if (callingStatement != null) {
hookedStream = callingStatement.getLocalInfileInputStream();
}
if (hookedStream != null) {
fileIn = new BufferedInputStream(hookedStream);
} else if (!this.connection.getAllowUrlInLocalInfile()) {
fileIn = new BufferedInputStream(new FileInputStream(fileName));
} else {
// First look for ':'
if (fileName.indexOf(':') != -1) {
try {
URL urlFromFileName = new URL(fileName);
fileIn = new BufferedInputStream(urlFromFileName.openStream());
} catch (MalformedURLException badUrlEx) {
// we fall back to trying this as a file input stream
fileIn = new BufferedInputStream(new FileInputStream(fileName));
}
} else {
fileIn = new BufferedInputStream(new FileInputStream(fileName));
}
}
int bytesRead = 0;
while ((bytesRead = fileIn.read(fileBuf)) != -1) {
filePacket.clear();
filePacket.writeBytesNoNull(fileBuf, 0, bytesRead);
send(filePacket, filePacket.getPosition());
}
} catch (IOException ioEx) {
StringBuilder messageBuf = new StringBuilder(Messages.getString("MysqlIO.60"));
if (fileName != null && !this.connection.getParanoid()) {
messageBuf.append("'");
messageBuf.append(fileName);
messageBuf.append("'");
}
messageBuf.append(Messages.getString("MysqlIO.63"));
if (!this.connection.getParanoid()) {
messageBuf.append(Messages.getString("MysqlIO.64"));
messageBuf.append(Util.stackTraceToString(ioEx));
}
throw SQLError.createSQLException(messageBuf.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
} finally {
if (fileIn != null) {
try {
fileIn.close();
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("MysqlIO.65"), SQLError.SQL_STATE_GENERAL_ERROR, ex,
getExceptionInterceptor());
throw sqlEx;
}
fileIn = null;
} else {
// file open failed, but server needs one packet
filePacket.clear();
send(filePacket, filePacket.getPosition());
checkErrorPacket(); // to clear response off of queue
}
}
// send empty packet to mark EOF
filePacket.clear();
send(filePacket, filePacket.getPosition());
Buffer resultPacket = checkErrorPacket();
return buildResultSetWithUpdates(callingStatement, resultPacket);
}
/**
* Checks for errors in the reply packet, and if none, returns the reply
* packet, ready for reading
*
* @param command
* the command being issued (if used)
*
* @throws SQLException
* if an error packet was received
* @throws CommunicationsException
*/
private Buffer checkErrorPacket(int command) throws SQLException {
//int statusCode = 0;
Buffer resultPacket = null;
this.serverStatus = 0;
try {
// Check return value, if we get a java.io.EOFException, the server has gone away. We'll pass it on up the exception chain and let someone higher up
// decide what to do (barf, reconnect, etc).
resultPacket = reuseAndReadPacket(this.reusablePacket);
} catch (SQLException sqlEx) {
// Don't wrap SQL Exceptions
throw sqlEx;
} catch (Exception fallThru) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, fallThru,
getExceptionInterceptor());
}
checkErrorPacket(resultPacket);
return resultPacket;
}
private void checkErrorPacket(Buffer resultPacket) throws SQLException {
int statusCode = resultPacket.readByte();
// Error handling
if (statusCode == (byte) 0xff) {
String serverErrorMessage;
int errno = 2000;
if (this.protocolVersion > 9) {
errno = resultPacket.readInt();
String xOpen = null;
serverErrorMessage = resultPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor());
if (serverErrorMessage.charAt(0) == '#') {
// we have an SQLState
if (serverErrorMessage.length() > 6) {
xOpen = serverErrorMessage.substring(1, 6);
serverErrorMessage = serverErrorMessage.substring(6);
if (xOpen.equals("HY000")) {
xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
}
} else {
xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
}
} else {
xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
}
clearInputStream();
StringBuilder errorBuf = new StringBuilder();
String xOpenErrorMessage = SQLError.get(xOpen);
if (!this.connection.getUseOnlyServerErrorMessages()) {
if (xOpenErrorMessage != null) {
errorBuf.append(xOpenErrorMessage);
errorBuf.append(Messages.getString("MysqlIO.68"));
}
}
errorBuf.append(serverErrorMessage);
if (!this.connection.getUseOnlyServerErrorMessages()) {
if (xOpenErrorMessage != null) {
errorBuf.append("\"");
}
}
appendDeadlockStatusInformation(xOpen, errorBuf);
if (xOpen != null && xOpen.startsWith("22")) {
throw new MysqlDataTruncation(errorBuf.toString(), 0, true, false, 0, 0, errno);
}
throw SQLError.createSQLException(errorBuf.toString(), xOpen, errno, false, getExceptionInterceptor(), this.connection);
}
serverErrorMessage = resultPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor());
clearInputStream();
if (serverErrorMessage.indexOf(Messages.getString("MysqlIO.70")) != -1) {
throw SQLError.createSQLException(SQLError.get(SQLError.SQL_STATE_COLUMN_NOT_FOUND) + ", " + serverErrorMessage,
SQLError.SQL_STATE_COLUMN_NOT_FOUND, -1, false, getExceptionInterceptor(), this.connection);
}
StringBuilder errorBuf = new StringBuilder(Messages.getString("MysqlIO.72"));
errorBuf.append(serverErrorMessage);
errorBuf.append("\"");
throw SQLError.createSQLException(SQLError.get(SQLError.SQL_STATE_GENERAL_ERROR) + ", " + errorBuf.toString(), SQLError.SQL_STATE_GENERAL_ERROR, -1,
false, getExceptionInterceptor(), this.connection);
}
}
private void appendDeadlockStatusInformation(String xOpen, StringBuilder errorBuf) throws SQLException {
if (this.connection.getIncludeInnodbStatusInDeadlockExceptions() && xOpen != null && (xOpen.startsWith("40") || xOpen.startsWith("41"))
&& this.streamingData == null) {
ResultSet rs = null;
try {
rs = sqlQueryDirect(null, "SHOW ENGINE INNODB STATUS", this.connection.getEncoding(), null, -1, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, false, this.connection.getCatalog(), null);
if (rs.next()) {
errorBuf.append("\n\n");
errorBuf.append(rs.getString("Status"));
} else {
errorBuf.append("\n\n");
errorBuf.append(Messages.getString("MysqlIO.NoInnoDBStatusFound"));
}
} catch (Exception ex) {
errorBuf.append("\n\n");
errorBuf.append(Messages.getString("MysqlIO.InnoDBStatusFailed"));
errorBuf.append("\n\n");
errorBuf.append(Util.stackTraceToString(ex));
} finally {
if (rs != null) {
rs.close();
}
}
}
if (this.connection.getIncludeThreadDumpInDeadlockExceptions()) {
errorBuf.append("\n\n*** Java threads running at time of deadlock ***\n\n");
ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadMBean.getAllThreadIds();
ThreadInfo[] threads = threadMBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
List<ThreadInfo> activeThreads = new ArrayList<ThreadInfo>();
for (ThreadInfo info : threads) {
if (info != null) {
activeThreads.add(info);
}
}
for (ThreadInfo threadInfo : activeThreads) {
// "Thread-60" daemon prio=1 tid=0x093569c0 nid=0x1b99 in Object.wait()
errorBuf.append('"');
errorBuf.append(threadInfo.getThreadName());
errorBuf.append("\" tid=");
errorBuf.append(threadInfo.getThreadId());
errorBuf.append(" ");
errorBuf.append(threadInfo.getThreadState());
if (threadInfo.getLockName() != null) {
errorBuf.append(" on lock=" + threadInfo.getLockName());
}
if (threadInfo.isSuspended()) {
errorBuf.append(" (suspended)");
}
if (threadInfo.isInNative()) {
errorBuf.append(" (running in native)");
}
StackTraceElement[] stackTrace = threadInfo.getStackTrace();
if (stackTrace.length > 0) {
errorBuf.append(" in ");
errorBuf.append(stackTrace[0].getClassName());
errorBuf.append(".");
errorBuf.append(stackTrace[0].getMethodName());
errorBuf.append("()");
}
errorBuf.append("\n");
if (threadInfo.getLockOwnerName() != null) {
errorBuf.append("\t owned by " + threadInfo.getLockOwnerName() + " Id=" + threadInfo.getLockOwnerId());
errorBuf.append("\n");
}
for (int j = 0; j < stackTrace.length; j++) {
StackTraceElement ste = stackTrace[j];
errorBuf.append("\tat " + ste.toString());
errorBuf.append("\n");
}
}
}
}
/**
* Sends a large packet to the server as a series of smaller packets
*
* @param packet
*
* @throws SQLException
* @throws CommunicationsException
*/
private final void sendSplitPackets(Buffer packet, int packetLen) throws SQLException {
try {
Buffer packetToSend = (this.splitBufRef == null) ? null : this.splitBufRef.get();
Buffer toCompress = (!this.useCompression || this.compressBufRef == null) ? null : this.compressBufRef.get();
//
// Store this packet in a soft reference...It can be re-used if not GC'd (so clients that use it frequently won't have to re-alloc the 16M buffer),
// but we don't penalize infrequent users of large packets by keeping 16M allocated all of the time
//
if (packetToSend == null) {
packetToSend = new Buffer((this.maxThreeBytes + HEADER_LENGTH));
this.splitBufRef = new SoftReference<Buffer>(packetToSend);
}
if (this.useCompression) {
int cbuflen = packetLen + ((packetLen / this.maxThreeBytes) + 1) * HEADER_LENGTH;
if (toCompress == null) {
toCompress = new Buffer(cbuflen);
this.compressBufRef = new SoftReference<Buffer>(toCompress);
} else if (toCompress.getBufLength() < cbuflen) {
toCompress.setPosition(toCompress.getBufLength());
toCompress.ensureCapacity(cbuflen - toCompress.getBufLength());
}
}
int len = packetLen - HEADER_LENGTH; // payload length left
int splitSize = this.maxThreeBytes;
int originalPacketPos = HEADER_LENGTH;
byte[] origPacketBytes = packet.getByteBuffer();
int toCompressPosition = 0;
// split to MySQL packets
while (len >= 0) {
this.packetSequence++;
if (len < splitSize) {
splitSize = len;
}
packetToSend.setPosition(0);
packetToSend.writeLongInt(splitSize);
packetToSend.writeByte(this.packetSequence);
if (len > 0) {
System.arraycopy(origPacketBytes, originalPacketPos, packetToSend.getByteBuffer(), HEADER_LENGTH, splitSize);
}
if (this.useCompression) {
System.arraycopy(packetToSend.getByteBuffer(), 0, toCompress.getByteBuffer(), toCompressPosition, HEADER_LENGTH + splitSize);
toCompressPosition += HEADER_LENGTH + splitSize;
} else {
this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, HEADER_LENGTH + splitSize);
this.mysqlOutput.flush();
}
originalPacketPos += splitSize;
len -= this.maxThreeBytes;
}
// split to compressed packets
if (this.useCompression) {
len = toCompressPosition;
toCompressPosition = 0;
splitSize = this.maxThreeBytes - COMP_HEADER_LENGTH;
while (len >= 0) {
this.compressedPacketSequence++;
if (len < splitSize) {
splitSize = len;
}
Buffer compressedPacketToSend = compressPacket(toCompress, toCompressPosition, splitSize);
packetLen = compressedPacketToSend.getPosition();
this.mysqlOutput.write(compressedPacketToSend.getByteBuffer(), 0, packetLen);
this.mysqlOutput.flush();
toCompressPosition += splitSize;
len -= (this.maxThreeBytes - COMP_HEADER_LENGTH);
}
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
private void reclaimLargeSharedSendPacket() {
if ((this.sharedSendPacket != null) && (this.sharedSendPacket.getCapacity() > 1048576)) {
this.sharedSendPacket = new Buffer(INITIAL_PACKET_SIZE);
}
}
boolean hadWarnings() {
return this.hadWarnings;
}
void scanForAndThrowDataTruncation() throws SQLException {
if ((this.streamingData == null) && versionMeetsMinimum(4, 1, 0) && this.connection.getJdbcCompliantTruncation() && this.warningCount > 0) {
SQLError.convertShowWarningsToSQLWarnings(this.connection, this.warningCount, true);
}
}
/**
* Secure authentication for 4.1 and newer servers.
*
* @param packet
* @param packLength
* @param user
* @param password
* @param database
* @param writeClientParams
*
* @throws SQLException
*/
private void secureAuth(Buffer packet, int packLength, String user, String password, String database, boolean writeClientParams) throws SQLException {
// Passwords can be 16 chars long
if (packet == null) {
packet = new Buffer(packLength);
}
if (writeClientParams) {
if (this.use41Extensions) {
if (versionMeetsMinimum(4, 1, 1)) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
// charset, JDBC will connect as 'latin1', and use 'SET NAMES' to change to the desired charset after the connection is established.
packet.writeByte((byte) 8);
// Set of bytes reserved for future use.
packet.writeBytesNoNull(new byte[23]);
} else {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
}
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
}
// User/Password data
packet.writeString(user, CODE_PAGE_1252, this.connection);
if (password.length() != 0) {
/* Prepare false scramble */
packet.writeString(FALSE_SCRAMBLE, CODE_PAGE_1252, this.connection);
} else {
/* For empty password */
packet.writeString("", CODE_PAGE_1252, this.connection);
}
if (this.useConnectWithDb) {
packet.writeString(database, CODE_PAGE_1252, this.connection);
}
send(packet, packet.getPosition());
//
// Don't continue stages if password is empty
//
if (password.length() > 0) {
Buffer b = readPacket();
b.setPosition(0);
byte[] replyAsBytes = b.getByteBuffer();
if ((replyAsBytes.length == 24) && (replyAsBytes[0] != 0)) {
// Old passwords will have '*' at the first byte of hash */
if (replyAsBytes[0] != '*') {
try {
/* Build full password hash as it is required to decode scramble */
byte[] buff = Security.passwordHashStage1(password);
/* Store copy as we'll need it later */
byte[] passwordHash = new byte[buff.length];
System.arraycopy(buff, 0, passwordHash, 0, buff.length);
/* Finally hash complete password using hash we got from server */
passwordHash = Security.passwordHashStage2(passwordHash, replyAsBytes);
byte[] packetDataAfterSalt = new byte[replyAsBytes.length - 4];
System.arraycopy(replyAsBytes, 4, packetDataAfterSalt, 0, replyAsBytes.length - 4);
byte[] mysqlScrambleBuff = new byte[SEED_LENGTH];
/* Decypt and store scramble 4 = hash for stage2 */
Security.xorString(packetDataAfterSalt, mysqlScrambleBuff, passwordHash, SEED_LENGTH);
/* Encode scramble with password. Recycle buffer */
Security.xorString(mysqlScrambleBuff, buff, buff, SEED_LENGTH);
Buffer packet2 = new Buffer(25);
packet2.writeBytesNoNull(buff);
this.packetSequence++;
send(packet2, 24);
} catch (NoSuchAlgorithmException nse) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
} else {
try {
/* Create password to decode scramble */
byte[] passwordHash = Security.createKeyFromOldPassword(password);
/* Decypt and store scramble 4 = hash for stage2 */
byte[] netReadPos4 = new byte[replyAsBytes.length - 4];
System.arraycopy(replyAsBytes, 4, netReadPos4, 0, replyAsBytes.length - 4);
byte[] mysqlScrambleBuff = new byte[SEED_LENGTH];
/* Decypt and store scramble 4 = hash for stage2 */
Security.xorString(netReadPos4, mysqlScrambleBuff, passwordHash, SEED_LENGTH);
/* Finally scramble decoded scramble with password */
String scrambledPassword = Util.scramble(StringUtils.toString(mysqlScrambleBuff), password);
Buffer packet2 = new Buffer(packLength);
packet2.writeString(scrambledPassword, CODE_PAGE_1252, this.connection);
this.packetSequence++;
send(packet2, 24);
} catch (NoSuchAlgorithmException nse) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
}
}
}
}
/**
* Secure authentication for 4.1.1 and newer servers.
*
* @param packet
* @param packLength
* @param user
* @param password
* @param database
* @param writeClientParams
*
* @throws SQLException
*/
void secureAuth411(Buffer packet, int packLength, String user, String password, String database, boolean writeClientParams) throws SQLException {
String enc = getEncodingForHandshake();
// SERVER: public_seed=create_random_string()
// send(public_seed)
//
// CLIENT: recv(public_seed)
// hash_stage1=sha1("password")
// hash_stage2=sha1(hash_stage1)
// reply=xor(hash_stage1, sha1(public_seed,hash_stage2)
//
// // this three steps are done in scramble()
//
// send(reply)
//
//
// SERVER: recv(reply)
// hash_stage1=xor(reply, sha1(public_seed,hash_stage2))
// candidate_hash2=sha1(hash_stage1)
// check(candidate_hash2==hash_stage2)
// Passwords can be 16 chars long
if (packet == null) {
packet = new Buffer(packLength);
}
if (writeClientParams) {
if (this.use41Extensions) {
if (versionMeetsMinimum(4, 1, 1)) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
appendCharsetByteForHandshake(packet, enc);
// Set of bytes reserved for future use.
packet.writeBytesNoNull(new byte[23]);
} else {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
}
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
}
// User/Password data
if (user != null) {
packet.writeString(user, enc, this.connection);
}
if (password.length() != 0) {
packet.writeByte((byte) 0x14);
try {
packet.writeBytesNoNull(Security.scramble411(password, this.seed, this.connection.getPasswordCharacterEncoding()));
} catch (NoSuchAlgorithmException nse) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
} catch (UnsupportedEncodingException e) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
} else {
/* For empty password */
packet.writeByte((byte) 0);
}
if (this.useConnectWithDb) {
packet.writeString(database, enc, this.connection);
} else {
/* For empty database */
packet.writeByte((byte) 0);
}
// connection attributes
if ((this.serverCapabilities & CLIENT_CONNECT_ATTRS) != 0) {
sendConnectionAttributes(packet, enc, this.connection);
}
send(packet, packet.getPosition());
byte savePacketSequence = this.packetSequence++;
Buffer reply = checkErrorPacket();
if (reply.isAuthMethodSwitchRequestPacket()) {
/*
* By sending this very specific reply server asks us to send scrambled password in old format. The reply contains scramble_323.
*/
this.packetSequence = ++savePacketSequence;
packet.clear();
String seed323 = this.seed.substring(0, 8);
packet.writeString(Util.newCrypt(password, seed323, this.connection.getPasswordCharacterEncoding()));
send(packet, packet.getPosition());
/* Read what server thinks about out new auth message report */
checkErrorPacket();
}
}
/**
* Un-packs binary-encoded result set data for one row
*
* @param fields
* @param binaryData
* @param resultSetConcurrency
*
* @return byte[][]
*
* @throws SQLException
*/
private final ResultSetRow unpackBinaryResultSetRow(Field[] fields, Buffer binaryData, int resultSetConcurrency) throws SQLException {
int numFields = fields.length;
byte[][] unpackedRowData = new byte[numFields][];
//
// Unpack the null bitmask, first
//
int nullCount = (numFields + 9) / 8;
int nullMaskPos = binaryData.getPosition();
binaryData.setPosition(nullMaskPos + nullCount);
int bit = 4; // first two bits are reserved for future use
//
// TODO: Benchmark if moving check for updatable result sets out of loop is worthwhile?
//
for (int i = 0; i < numFields; i++) {
if ((binaryData.readByte(nullMaskPos) & bit) != 0) {
unpackedRowData[i] = null;
} else {
if (resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) {
extractNativeEncodedColumn(binaryData, fields, i, unpackedRowData);
} else {
unpackNativeEncodedColumn(binaryData, fields, i, unpackedRowData);
}
}
if (((bit <<= 1) & 255) == 0) {
bit = 1; /* To next byte */
nullMaskPos++;
}
}
return new ByteArrayRow(unpackedRowData, getExceptionInterceptor());
}
private final void extractNativeEncodedColumn(Buffer binaryData, Field[] fields, int columnIndex, byte[][] unpackedRowData) throws SQLException {
Field curField = fields[columnIndex];
switch (curField.getMysqlType()) {
case MysqlDefs.FIELD_TYPE_NULL:
break; // for dummy binds
case MysqlDefs.FIELD_TYPE_TINY:
unpackedRowData[columnIndex] = new byte[] { binaryData.readByte() };
break;
case MysqlDefs.FIELD_TYPE_SHORT:
case MysqlDefs.FIELD_TYPE_YEAR:
unpackedRowData[columnIndex] = binaryData.getBytes(2);
break;
case MysqlDefs.FIELD_TYPE_LONG:
case MysqlDefs.FIELD_TYPE_INT24:
unpackedRowData[columnIndex] = binaryData.getBytes(4);
break;
case MysqlDefs.FIELD_TYPE_LONGLONG:
unpackedRowData[columnIndex] = binaryData.getBytes(8);
break;
case MysqlDefs.FIELD_TYPE_FLOAT:
unpackedRowData[columnIndex] = binaryData.getBytes(4);
break;
case MysqlDefs.FIELD_TYPE_DOUBLE:
unpackedRowData[columnIndex] = binaryData.getBytes(8);
break;
case MysqlDefs.FIELD_TYPE_TIME:
int length = (int) binaryData.readFieldLength();
unpackedRowData[columnIndex] = binaryData.getBytes(length);
break;
case MysqlDefs.FIELD_TYPE_DATE:
length = (int) binaryData.readFieldLength();
unpackedRowData[columnIndex] = binaryData.getBytes(length);
break;
case MysqlDefs.FIELD_TYPE_DATETIME:
case MysqlDefs.FIELD_TYPE_TIMESTAMP:
length = (int) binaryData.readFieldLength();
unpackedRowData[columnIndex] = binaryData.getBytes(length);
break;
case MysqlDefs.FIELD_TYPE_TINY_BLOB:
case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB:
case MysqlDefs.FIELD_TYPE_LONG_BLOB:
case MysqlDefs.FIELD_TYPE_BLOB:
case MysqlDefs.FIELD_TYPE_VAR_STRING:
case MysqlDefs.FIELD_TYPE_VARCHAR:
case MysqlDefs.FIELD_TYPE_STRING:
case MysqlDefs.FIELD_TYPE_DECIMAL:
case MysqlDefs.FIELD_TYPE_NEW_DECIMAL:
case MysqlDefs.FIELD_TYPE_GEOMETRY:
case MysqlDefs.FIELD_TYPE_BIT:
case MysqlDefs.FIELD_TYPE_JSON:
unpackedRowData[columnIndex] = binaryData.readLenByteArray(0);
break;
default:
throw SQLError.createSQLException(
Messages.getString("MysqlIO.97") + curField.getMysqlType() + Messages.getString("MysqlIO.98") + columnIndex
+ Messages.getString("MysqlIO.99") + fields.length + Messages.getString("MysqlIO.100"),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
}
private final void unpackNativeEncodedColumn(Buffer binaryData, Field[] fields, int columnIndex, byte[][] unpackedRowData) throws SQLException {
Field curField = fields[columnIndex];
switch (curField.getMysqlType()) {
case MysqlDefs.FIELD_TYPE_NULL:
break; // for dummy binds
case MysqlDefs.FIELD_TYPE_TINY:
byte tinyVal = binaryData.readByte();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(tinyVal));
} else {
short unsignedTinyVal = (short) (tinyVal & 0xff);
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(unsignedTinyVal));
}
break;
case MysqlDefs.FIELD_TYPE_SHORT:
case MysqlDefs.FIELD_TYPE_YEAR:
short shortVal = (short) binaryData.readInt();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(shortVal));
} else {
int unsignedShortVal = shortVal & 0xffff;
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(unsignedShortVal));
}
break;
case MysqlDefs.FIELD_TYPE_LONG:
case MysqlDefs.FIELD_TYPE_INT24:
int intVal = (int) binaryData.readLong();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(intVal));
} else {
long longVal = intVal & 0xffffffffL;
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(longVal));
}
break;
case MysqlDefs.FIELD_TYPE_LONGLONG:
long longVal = binaryData.readLongLong();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(longVal));
} else {
BigInteger asBigInteger = ResultSetImpl.convertLongToUlong(longVal);
unpackedRowData[columnIndex] = StringUtils.getBytes(asBigInteger.toString());
}
break;
case MysqlDefs.FIELD_TYPE_FLOAT:
float floatVal = Float.intBitsToFloat(binaryData.readIntAsLong());
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(floatVal));
break;
case MysqlDefs.FIELD_TYPE_DOUBLE:
double doubleVal = Double.longBitsToDouble(binaryData.readLongLong());
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(doubleVal));
break;
case MysqlDefs.FIELD_TYPE_TIME:
int length = (int) binaryData.readFieldLength();
int hour = 0;
int minute = 0;
int seconds = 0;
if (length != 0) {
binaryData.readByte(); // skip tm->neg
binaryData.readLong(); // skip daysPart
hour = binaryData.readByte();
minute = binaryData.readByte();
seconds = binaryData.readByte();
if (length > 8) {
binaryData.readLong(); // ignore 'secondsPart'
}
}
byte[] timeAsBytes = new byte[8];
timeAsBytes[0] = (byte) Character.forDigit(hour / 10, 10);
timeAsBytes[1] = (byte) Character.forDigit(hour % 10, 10);
timeAsBytes[2] = (byte) ':';
timeAsBytes[3] = (byte) Character.forDigit(minute / 10, 10);
timeAsBytes[4] = (byte) Character.forDigit(minute % 10, 10);
timeAsBytes[5] = (byte) ':';
timeAsBytes[6] = (byte) Character.forDigit(seconds / 10, 10);
timeAsBytes[7] = (byte) Character.forDigit(seconds % 10, 10);
unpackedRowData[columnIndex] = timeAsBytes;
break;
case MysqlDefs.FIELD_TYPE_DATE:
length = (int) binaryData.readFieldLength();
int year = 0;
int month = 0;
int day = 0;
hour = 0;
minute = 0;
seconds = 0;
if (length != 0) {
year = binaryData.readInt();
month = binaryData.readByte();
day = binaryData.readByte();
}
if ((year == 0) && (month == 0) && (day == 0)) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals(this.connection.getZeroDateTimeBehavior())) {
unpackedRowData[columnIndex] = null;
break;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals(this.connection.getZeroDateTimeBehavior())) {
throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
getExceptionInterceptor());
}
year = 1;
month = 1;
day = 1;
}
byte[] dateAsBytes = new byte[10];
dateAsBytes[0] = (byte) Character.forDigit(year / 1000, 10);
int after1000 = year % 1000;
dateAsBytes[1] = (byte) Character.forDigit(after1000 / 100, 10);
int after100 = after1000 % 100;
dateAsBytes[2] = (byte) Character.forDigit(after100 / 10, 10);
dateAsBytes[3] = (byte) Character.forDigit(after100 % 10, 10);
dateAsBytes[4] = (byte) '-';
dateAsBytes[5] = (byte) Character.forDigit(month / 10, 10);
dateAsBytes[6] = (byte) Character.forDigit(month % 10, 10);
dateAsBytes[7] = (byte) '-';
dateAsBytes[8] = (byte) Character.forDigit(day / 10, 10);
dateAsBytes[9] = (byte) Character.forDigit(day % 10, 10);
unpackedRowData[columnIndex] = dateAsBytes;
break;
case MysqlDefs.FIELD_TYPE_DATETIME:
case MysqlDefs.FIELD_TYPE_TIMESTAMP:
length = (int) binaryData.readFieldLength();
year = 0;
month = 0;
day = 0;
hour = 0;
minute = 0;
seconds = 0;
int nanos = 0;
if (length != 0) {
year = binaryData.readInt();
month = binaryData.readByte();
day = binaryData.readByte();
if (length > 4) {
hour = binaryData.readByte();
minute = binaryData.readByte();
seconds = binaryData.readByte();
}
//if (length > 7) {
// nanos = (int)binaryData.readLong();
//}
}
if ((year == 0) && (month == 0) && (day == 0)) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals(this.connection.getZeroDateTimeBehavior())) {
unpackedRowData[columnIndex] = null;
break;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals(this.connection.getZeroDateTimeBehavior())) {
throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Timestamp",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
year = 1;
month = 1;
day = 1;
}
int stringLength = 19;
byte[] nanosAsBytes = StringUtils.getBytes(Integer.toString(nanos));
stringLength += (1 + nanosAsBytes.length); // '.' + # of digits
byte[] datetimeAsBytes = new byte[stringLength];
datetimeAsBytes[0] = (byte) Character.forDigit(year / 1000, 10);
after1000 = year % 1000;
datetimeAsBytes[1] = (byte) Character.forDigit(after1000 / 100, 10);
after100 = after1000 % 100;
datetimeAsBytes[2] = (byte) Character.forDigit(after100 / 10, 10);
datetimeAsBytes[3] = (byte) Character.forDigit(after100 % 10, 10);
datetimeAsBytes[4] = (byte) '-';
datetimeAsBytes[5] = (byte) Character.forDigit(month / 10, 10);
datetimeAsBytes[6] = (byte) Character.forDigit(month % 10, 10);
datetimeAsBytes[7] = (byte) '-';
datetimeAsBytes[8] = (byte) Character.forDigit(day / 10, 10);
datetimeAsBytes[9] = (byte) Character.forDigit(day % 10, 10);
datetimeAsBytes[10] = (byte) ' ';
datetimeAsBytes[11] = (byte) Character.forDigit(hour / 10, 10);
datetimeAsBytes[12] = (byte) Character.forDigit(hour % 10, 10);
datetimeAsBytes[13] = (byte) ':';
datetimeAsBytes[14] = (byte) Character.forDigit(minute / 10, 10);
datetimeAsBytes[15] = (byte) Character.forDigit(minute % 10, 10);
datetimeAsBytes[16] = (byte) ':';
datetimeAsBytes[17] = (byte) Character.forDigit(seconds / 10, 10);
datetimeAsBytes[18] = (byte) Character.forDigit(seconds % 10, 10);
datetimeAsBytes[19] = (byte) '.';
final int nanosOffset = 20;
System.arraycopy(nanosAsBytes, 0, datetimeAsBytes, nanosOffset, nanosAsBytes.length);
unpackedRowData[columnIndex] = datetimeAsBytes;
break;
case MysqlDefs.FIELD_TYPE_TINY_BLOB:
case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB:
case MysqlDefs.FIELD_TYPE_LONG_BLOB:
case MysqlDefs.FIELD_TYPE_BLOB:
case MysqlDefs.FIELD_TYPE_VAR_STRING:
case MysqlDefs.FIELD_TYPE_STRING:
case MysqlDefs.FIELD_TYPE_VARCHAR:
case MysqlDefs.FIELD_TYPE_DECIMAL:
case MysqlDefs.FIELD_TYPE_NEW_DECIMAL:
case MysqlDefs.FIELD_TYPE_BIT:
unpackedRowData[columnIndex] = binaryData.readLenByteArray(0);
break;
default:
throw SQLError.createSQLException(
Messages.getString("MysqlIO.97") + curField.getMysqlType() + Messages.getString("MysqlIO.98") + columnIndex
+ Messages.getString("MysqlIO.99") + fields.length + Messages.getString("MysqlIO.100"),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
}
/**
* Negotiates the SSL communications channel used when connecting
* to a MySQL server that understands SSL.
*
* @param user
* @param password
* @param database
* @param packLength
* @throws SQLException
* @throws CommunicationsException
*/
private void negotiateSSLConnection(String user, String password, String database, int packLength) throws SQLException {
if (!ExportControlled.enabled()) {
throw new ConnectionFeatureNotAvailableException(this.connection, this.lastPacketSentTimeMs, null);
}
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
this.clientParam |= CLIENT_SECURE_CONNECTION;
}
this.clientParam |= CLIENT_SSL;
Buffer packet = new Buffer(packLength);
if (this.use41Extensions) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
appendCharsetByteForHandshake(packet, getEncodingForHandshake());
packet.writeBytesNoNull(new byte[23]); // Set of bytes reserved for future use.
} else {
packet.writeInt((int) this.clientParam);
}
send(packet, packet.getPosition());
ExportControlled.transformSocketToSSLSocket(this);
}
public boolean isSSLEstablished() {
return ExportControlled.enabled() && ExportControlled.isSSLEstablished(this);
}
protected int getServerStatus() {
return this.serverStatus;
}
protected List<ResultSetRow> fetchRowsViaCursor(List<ResultSetRow> fetchedRows, long statementId, Field[] columnTypes, int fetchSize,
boolean useBufferRowExplicit) throws SQLException {
if (fetchedRows == null) {
fetchedRows = new ArrayList<ResultSetRow>(fetchSize);
} else {
fetchedRows.clear();
}
this.sharedSendPacket.clear();
this.sharedSendPacket.writeByte((byte) MysqlDefs.COM_FETCH);
this.sharedSendPacket.writeLong(statementId);
this.sharedSendPacket.writeLong(fetchSize);
sendCommand(MysqlDefs.COM_FETCH, null, this.sharedSendPacket, true, null, 0);
ResultSetRow row = null;
while ((row = nextRow(columnTypes, columnTypes.length, true, ResultSet.CONCUR_READ_ONLY, false, useBufferRowExplicit, false, null)) != null) {
fetchedRows.add(row);
}
return fetchedRows;
}
protected long getThreadId() {
return this.threadId;
}
protected boolean useNanosForElapsedTime() {
return this.useNanosForElapsedTime;
}
protected long getSlowQueryThreshold() {
return this.slowQueryThreshold;
}
protected String getQueryTimingUnits() {
return this.queryTimingUnits;
}
protected int getCommandCount() {
return this.commandCount;
}
private void checkTransactionState(int oldStatus) throws SQLException {
boolean previouslyInTrans = ((oldStatus & SERVER_STATUS_IN_TRANS) != 0);
boolean currentlyInTrans = ((this.serverStatus & SERVER_STATUS_IN_TRANS) != 0);
if (previouslyInTrans && !currentlyInTrans) {
this.connection.transactionCompleted();
} else if (!previouslyInTrans && currentlyInTrans) {
this.connection.transactionBegun();
}
}
protected void setStatementInterceptors(List<StatementInterceptorV2> statementInterceptors) {
this.statementInterceptors = statementInterceptors.isEmpty() ? null : statementInterceptors;
}
protected ExceptionInterceptor getExceptionInterceptor() {
return this.exceptionInterceptor;
}
protected void setSocketTimeout(int milliseconds) throws SQLException {
try {
this.mysqlConnection.setSoTimeout(milliseconds);
} catch (SocketException e) {
SQLException sqlEx = SQLError.createSQLException("Invalid socket timeout value or state", SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
getExceptionInterceptor());
sqlEx.initCause(e);
throw sqlEx;
}
}
protected void releaseResources() {
if (this.deflater != null) {
this.deflater.end();
this.deflater = null;
}
}
/**
* Get the Java encoding to be used for the handshake
* response. Defaults to UTF-8.
*/
String getEncodingForHandshake() {
String enc = this.connection.getEncoding();
if (enc == null) {
enc = "UTF-8";
}
return enc;
}
/**
* Append the MySQL collation index to the handshake packet. A
* single byte will be added to the packet corresponding to the
* collation index found for the requested Java encoding name.
*
* If the index is > 255 which may be valid at some point in
* the future, an exception will be thrown. At the time of this
* implementation the index cannot be > 255 and only the
* COM_CHANGE_USER rpc, not the handshake response, can handle a
* value > 255.
*
* @param packet
* to append to
* @param end
* The Java encoding name used to lookup the collation index
*/
private void appendCharsetByteForHandshake(Buffer packet, String enc) throws SQLException {
int charsetIndex = 0;
if (enc != null) {
charsetIndex = CharsetMapping.getCollationIndexForJavaEncoding(enc, this.connection);
}
if (charsetIndex == 0) {
charsetIndex = CharsetMapping.MYSQL_COLLATION_INDEX_utf8;
}
if (charsetIndex > 255) {
throw SQLError.createSQLException("Invalid character set index for encoding: " + enc, SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
getExceptionInterceptor());
}
packet.writeByte((byte) charsetIndex);
}
public boolean isEOFDeprecated() {
return (this.clientParam & CLIENT_DEPRECATE_EOF) != 0;
}
}