-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmysql-protocol.r
1117 lines (1029 loc) · 28.2 KB
/
mysql-protocol.r
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
REBOL [
Title: "MySQL Protocol"
Author: "Nenad Rakocevic / SOFTINNOV"
Email: [email protected]
Web: http://softinnov.org/rebol/mysql.shtml
Date: 03/12/2008
File: %mysql-protocol.r
Version: 1.3.0
Purpose: "MySQL Driver for REBOL"
Note: "Special experimental version supporting protocol 4.1"
History: {
- Fixed the multiple result sets issue. Now an extra COPY will return none
marking the end of the data stream.
- Fixed error message parsing for protocol 4.1.
- Added SQL request delimiter property to port/locals/delimiter (default: #";") for
older server (pre-4.1)
- Fixed parsing bug with \\. Now expression like "'\\', 'wo;rd'" will be parsed correctly.
- Fixed a regression bug appearing when trying to open a connection without a database name.
- Fixed "port not open" error after automatic reconnection.
}
]
make root-protocol [
scheme: 'MySQL
port-id: 3306
port-flags: system/standard/port-flags/pass-thru or 32 ; /binary
sql-buffer: make string! 1024
not-squote: complement charset "'"
not-dquote: complement charset {"}
copy*: get in system/words 'copy
insert*: get in system/words 'insert
pick*: get in system/words 'pick
close*: get in system/words 'close
set-modes*: get in system/words 'set-modes
net-log: get in net-utils 'net-log
std-header-length: 4
std-comp-header-length: 3
end-marker: 254
throws: [closed "closed"]
;------ Internals --------
defs: [
cmd [
;sleep 0
quit 1
init-db 2
query 3
;field-list 4
create-db 5
drop-db 6
reload 7
shutdown 8
statistics 9
;process-info 10
;connect 11
process-kill 12
debug 13
ping 14
;time 15
;delayed-insert 16
change-user 17
]
refresh [
grant 1 ; Refresh grant tables
log 2 ; Start on new log file
tables 4 ; Close all tables
hosts 8 ; Flush host cache
status 16 ; Flush status variables
threads 32 ; Flush status variables
slave 64 ; Reset master info and restart slave thread
master 128 ; Remove all bin logs in the index
] ; and truncate the index
types [
0 decimal
1 tiny
2 short
3 long
4 float
5 double
6 null
7 timestamp
8 longlong
9 int24
10 date
11 time
12 datetime
13 year
14 newdate
15 var-char
16 bit
246 new-decimal
247 enum
248 set
249 tiny-blob
250 medium-blob
251 long-blob
252 blob
253 var-string
254 string
255 geometry
]
flag [
not-null 1 ; field can't be NULL
primary-key 2 ; field is part of a primary key
unique-key 4 ; field is part of a unique key
multiple-key 8 ; field is part of a key
blob 16
unsigned 32
zero-fill 64
binary 128
enum 256 ; field is an enum
auto-increment 512 ; field is a autoincrement field
timestamp 1024 ; field is a timestamp
set 2048 ; field is a set
num 32768 ; field is num (for clients)
]
client [
long-password 1 ; new more secure passwords
found-rows 2 ; Found instead of affected rows
long-flag 4 ; Get all column flags
connect-with-db 8 ; One can specify db on connect
no-schema 16 ; Don't allow db.table.column
compress 32 ; Can use compression protcol
odbc 64 ; Odbc client
local-files 128 ; Can use LOAD DATA LOCAL
ignore-space 256 ; Ignore spaces before '('
protocol-41 512 ; Use new protocol (was "Support the mysql_change_user()")
interactive 1024 ; This is an interactive client
ssl 2048 ; Switch to SSL after handshake
ignore-sigpipe 4096 ; IGNORE sigpipes
transactions 8196 ; Client knows about transactions
reserved 16384 ; for 4.1.0 only
secure-connection 32768 ; use new hashing algorithm
multi-queries 65536 ; enable/disable multiple queries support
multi-results 131072 ; enable/disable multiple result sets
]
]
locals-class: make object! [
;--- Internals (do not touch!)---
seq-num: 0
buf-size: cache-size: 10000
last-status:
stream-end?:
more-results?:
expecting: none
buffer: none
cache: none
;-------
auto-commit: on ; not used, just reserved for /Command compatibility.
rows: 10 ; not used, just reserved for /Command compatibility.
auto-conv?: on
auto-ping?: on
flat?: off
delimiter: #";"
newlines?: value? 'new-line
init:
matched-rows:
columns:
protocol:
version:
thread-id:
crypt-seed:
capabilities:
error-code:
error-msg:
conv-list:
character-set:
server-status:
auth-v11: none
]
column-class: make object! [
table: name: length: type: flags: decimals: none
]
my-to-date: func [v][any [attempt [to date! v] 1-jan-0000]]
my-to-datetime: func [v][any [attempt [to date! v] 1-jan-0000/00:00]]
conv-model: [
decimal [to decimal!]
tiny [to integer!]
short [to integer!]
long [to integer!]
float [to decimal!]
double none
null none
timestamp none
longlong none
int24 [to integer!]
date [my-to-date]
time [to time!]
datetime [my-to-datetime]
year [to integer!]
newdate none
var-char none
bit none
new-decimal [to decimal!]
enum none
set none
tiny-blob none
medium-blob none
long-blob none
blob none
var-string none
string none
geometry none
]
set 'change-type-handler func [p [port!] type [word!] blk [block!]][
head change/only next find p/locals/conv-list type blk
]
convert-types: func [
p [port!]
rows [block!]
/local row i convert-body action cols col conv-func tmp
][
cols: p/locals/columns
convert-body: make block! 1
action: [if tmp: pick* row (i)]
foreach col cols [
i: index? find cols col
if 'none <> conv-func: select p/locals/conv-list col/type [
append convert-body append/only compose action head
insert* at compose [change at row (i) :tmp] 5 conv-func
]
]
if not empty? convert-body [
either p/locals/flat? [
while [not tail? rows][
row: rows
do convert-body
rows: skip rows length? cols
]
][
foreach row rows :convert-body
]
]
]
decode: func [int [integer!] /features /flags /type /local list name value][
either type [
any [select defs/types int 'unknown]
][
list: make block! 10
foreach [name value] either flags [defs/flag][defs/client][
if value = (int and value) [append list :name]
]
list
]
]
encode-refresh: func [blk [block!] /local total name value][
total: 0
foreach name blk [
either value: select defs/refresh :name [
total: total + value
][
net-error reform ["Unknown argument:" :name]
]
]
total
]
sql-chars: charset sql-want: {^(00)^/^-^M^(08)'"\}
sql-no-chars: complement sql-chars
escaped: make hash! [
#"^(00)" "\0"
#"^/" "\n"
#"^-" "\t"
#"^M" "\r"
#"^(08)" "\b"
#"'" "\'"
#"^"" {\"}
#"\" "\\"
]
set 'sql-escape func [value [string!] /local c][
parse/all value [
any [
c: sql-chars (c: change/part c select escaped c/1 1) :c
| sql-no-chars
]
]
value
]
set 'to-sql func [value /local res][
switch/default type?/word value [
none! ["NULL"]
date! [
rejoin ["'" value/year "-" value/month "-" value/day
either value: value/time [
rejoin [" " value/hour ":" value/minute ":" value/second]
][""] "'"
]
]
time! [join "'" [value/hour ":" value/minute ":" value/second "'"]]
money! [head remove find mold value "$"]
string! [join "'" [sql-escape copy* value "'"]]
binary! [to-sql to string! value]
block! [
if empty? value: reduce value [return "()"]
res: append make string! 100 #"("
forall value [repend res [to-sql value/1 #","]]
head change back tail res #")"
]
][
either any-string? value [to-sql form value][form value]
]
]
map-rebol-values: func [data [block!] /local args sql mark][
args: reduce next data
sql: copy* pick* data 1
mark: sql
while [mark: find mark #"?"][
mark: insert* remove mark either tail? args ["NULL"][to-sql args/1]
if not tail? args [args: next args]
]
net-log sql
sql
]
show-server: func [obj [object!]][
net-log reform [ newline
"----- Server ------" newline
"Version:" obj/version newline
"Protocol version:" obj/protocol newline
"Thread ID:" obj/thread-id newline
"Crypt Seed:" obj/crypt-seed newline
"Capabilities:" mold obj/capabilities newline
"-------------------"
]
]
;------ Encryption support functions ------
scrambler: make object! [
to-pair: func [value [integer!]][system/words/to-pair reduce [value 1]]
xor-pair: func [p1 p2][to-pair p1/x xor p2/x]
or-pair: func [p1 p2][to-pair p1/x or p2/x]
and-pair: func [p1 p2][to-pair p1/x and p2/x]
remainder-pair: func [val1 val2 /local new][
val1: either negative? val1/x [abs val1/x + 2147483647.0][val1/x]
val2: either negative? val2/x [abs val2/x + 2147483647.0][val2/x]
to-pair to-integer val1 // val2
]
floor: func [value][
value: to-integer either negative? value [value - .999999999999999][value]
either negative? value [complement value][value]
]
hash-v9: func [data [string!] /local nr nr2 byte][
nr: 1345345333x1
nr2: 7x1
foreach byte data [
if all [byte <> #" " byte <> #"^(tab)"][
byte: to-pair to-integer byte
nr: xor-pair nr (((and-pair 63x1 nr) + nr2) * byte) + (nr * 256x1)
nr2: nr2 + byte
]
]
nr
]
hash-v10: func [data [string!] /local nr nr2 adding byte][
nr: 1345345333x1
adding: 7x1
nr2: to-pair to-integer #12345671
foreach byte data [
if all [byte <> #" " byte <> #"^(tab)"][
byte: to-pair to-integer byte
nr: xor-pair nr (((and-pair 63x1 nr) + adding) * byte) + (nr * 256x1)
nr2: nr2 + xor-pair nr (nr2 * 256x1)
adding: adding + byte
]
]
nr: and-pair nr to-pair to-integer #7FFFFFFF
nr2: and-pair nr2 to-pair to-integer #7FFFFFFF
reduce [nr nr2]
]
crypt-v9: func [data [string!] seed [string!] /local
new max-value clip-max hp hm nr seed1 seed2 d b i
][
new: make string! length? seed
max-value: to-pair to-integer #01FFFFFF
clip-max: func [value][remainder-pair value max-value]
hp: hash-v9 seed
hm: hash-v9 data
nr: clip-max xor-pair hp hm
seed1: nr
seed2: nr / 2x1
foreach i seed [
seed1: clip-max ((seed1 * 3x1) + seed2)
seed2: clip-max (seed1 + seed2 + 33x1)
d: seed1/x / to-decimal max-value/x
append new to-char floor (d * 31) + 64
]
new
]
crypt-v10: func [data [string!] seed [string!] /local
new max-value clip-max pw msg seed1 seed2 d b i
][
new: make string! length? seed
max-value: to-pair to-integer #3FFFFFFF
clip-max: func [value][remainder-pair value max-value]
pw: hash-v10 seed
msg: hash-v10 data
seed1: clip-max xor-pair pw/1 msg/1
seed2: clip-max xor-pair pw/2 msg/2
foreach i seed [
seed1: clip-max ((seed1 * 3x1) + seed2)
seed2: clip-max (seed1 + seed2 + 33x1)
d: seed1/x / to-decimal max-value/x
append new to-char floor (d * 31) + 64
]
seed1: clip-max (seed1 * 3x1) + seed2
seed2: clip-max seed1 + seed2 + 33x0
d: seed1/x / to-decimal max-value/x
b: to-char floor (d * 31)
forall new [new/1: new/1 xor b]
head new
]
;--- New 4.1.0+ authentication scheme ---
crypt-v11: func [data [string!] seed [string!] /local key1 key2][
key1: checksum/secure data
key2: checksum/secure key1
to string! key1 xor checksum/secure join seed key2
]
scramble: func [data [string!] port [port!] /v10 /local seed][
if any [none? data empty? data][return ""]
seed: port/locals/crypt-seed
if v10 [return crypt-v10 data copy*/part seed 8]
either port/locals/protocol > 9 [
either port/locals/auth-v11 [
crypt-v11 data seed
][
crypt-v10 data seed
]
][
crypt-v9 data seed
]
]
]
scramble: get in scrambler 'scramble
;------ Data reading ------
b0: b1: b2: b3: int: int24: long: string: field: len: byte: s: none
byte-char: complement charset []
null: to-char 0
null-flag: false
ws: charset " ^-^M^/"
read-string: [[copy string to null null] | [copy string to end]]
read-byte: [copy byte byte-char (byte: to integer! to char! :byte)]
read-int: [
read-byte (b0: byte)
read-byte (b1: byte int: b0 + (256 * b1))
]
read-int24: [
read-byte (b0: byte)
read-byte (b1: byte)
read-byte (b2: byte int24: b0 + (256 * b1) + (65536 * b2))
]
read-long: [
read-byte (b0: byte)
read-byte (b1: byte)
read-byte (b2: byte)
read-byte (
b3: byte
long: any [attempt [to integer! b0 + (256 * b1) + (65536 * b2) + (16777216.0 * b3)] -1]
)
]
read-long64: [
read-long
skip 4 byte (net-log "Warning: long64 type detected !")
]
read-length: [
#"^(FB)" (len: 0 null-flag: true)
| #"^(FC)" read-int (len: int)
| #"^(FD)" read-int24 (len: int24)
| #"^(FE)" read-long (len: long)
| read-byte (len: byte)
]
read-nbytes: [
#"^(01)" read-byte (len: byte)
| #"^(02)" read-int (len: int)
| #"^(03)" read-int24 (len: int24)
| #"^(04)" read-long (len: long)
| none (len: 255)
]
read-field: [
(null-flag: false)
read-length s: (either null-flag [field: none]
[field: copy*/part s len s: skip s len]) :s
]
read: func [[throw] port [port!] data [binary!] size [integer!] /local len][
len: read-io port/sub-port data size
if any [zero? len negative? len][
close* port/sub-port
throw throws/closed
]
net-log reform ["low level read of" len "bytes"]
len
]
defrag-read: func [port [port!] buf [binary!] expected [integer!]][
clear buf
while [expected > length? buf][
read port buf expected - length? buf
]
]
read-packet: func [port [port!] /local packet-len pl status][
pl: port/locals
pl/stream-end?: false
;--- reading header ---
defrag-read port pl/buffer std-header-length
parse/all pl/buffer [
read-int24 (packet-len: int24)
read-byte (pl/seq-num: byte)
]
;--- reading data ---
if packet-len > pl/buf-size [
net-log reform ["Expanding buffer, old:" pl/buf-size "new:" packet-len]
tmp: pl/cache
pl/buffer: make binary! pl/buf-size: packet-len + (length? tmp) + length? pl/buffer
pl/cache: make binary! pl/cache-size: pl/buf-size
insert* tail pl/cache tmp
]
defrag-read port pl/buffer packet-len
if packet-len <> length? pl/buffer [
net-error "Error: inconsistent packet length !"
]
pl/last-status: status: to integer! pl/buffer/1
pl/error-code: pl/error-msg: none
do select [
255 [
parse/all next pl/buffer case [
find pl/capabilities 'protocol-41 [
[
read-int (pl/error-code: int)
6 skip
read-string (pl/error-msg: string)
]
]
any [none? pl/protocol pl/protocol > 9][
[
read-int (pl/error-code: int)
read-string (pl/error-msg: string)
]
]
true [
pl/error-code: 0
[read-string (pl/error-msg: string)]
]
]
pl/stream-end?: true
net-error reform ["ERROR" any [pl/error-code ""]":" pl/error-msg]
]
254 [
case [
packet-len = 5 [
pl/more-results?: not zero? pl/buffer/4 and 8
pl/stream-end?: true
]
packet-len = 1 [pl/stream-end?: true]
]
]
0 [
if none? pl/expecting [
parse/all/case next pl/buffer [
read-length (pl/matched-rows: len)
read-length
read-int (pl/more-results?: not zero? int and 8)
]
pl/stream-end?: true
]
]
] status
pl/buffer
]
read-packet-via: func [port [port!] /local pl tmp][
pl: port/locals
if empty? pl/cache [
read-packet port
if pl/stream-end? [return #{}] ; empty set !
]
tmp: pl/cache ; swap cache<=>buffer
pl/cache: pl/buffer
pl/buffer: :tmp
tmp: pl/cache-size
pl/cache-size: pl/buf-size
pl/buf-size: :tmp
read-packet port
pl/cache
]
read-columns-number: func [port [port!] /local colnb pl][
pl: port/locals
parse/all/case read-packet port [
read-length (if zero? colnb: len [pl/stream-end?: true])
read-length (pl/matched-rows: len)
read-length
read-int (pl/more-results?: not zero? int and 8)
]
if not zero? colnb [pl/matched-rows: none]
colnb
]
read-columns-headers: func [port [port!] cols [integer!] /local pl col][
pl: port/locals
pl/columns: make block! cols
loop cols [
col: make column-class []
parse/all/case read-packet port [
read-field ; catalog
read-field ; db
read-field (col/table: field)
read-field ; org-table
read-field (col/name: field)
read-field ; org-name
read-byte ; filler
read-int ; charsetnr
read-long (col/length: long)
read-byte (col/type: decode/type byte)
read-field (
col/flags: decode/flags to integer! field/1
col/decimals: to integer! field/2
)
read-int ; filler
read-nbytes ; default
]
append pl/columns :col
]
read-packet port ; check the ending flag
if not pl/stream-end? [
flush-pending-data port
net-error "Error: end of columns stream not found"
]
pl/expecting: 'rows
pl/stream-end?: false ; prepare correct state for
clear pl/cache ; rows reading.
]
read-rows: func [port [port!] /part n [integer!]
/local pl row-data row rows cols count
][
pl: port/locals
rows: make block! max any [n 0] pl/rows
cols: length? pl/columns
count: 0
forever [
row-data: read-packet-via port
if empty? row-data [return rows] ; empty set
row: make block! cols
parse/all/case row-data [any [read-field (append row field)]]
either pl/flat? [
insert* tail rows row
][
insert*/only tail rows row
]
if pl/stream-end? or all [part n = count: count + 1][break] ; end of stream or rows # reached
]
if pl/auto-conv? [convert-types port rows]
if pl/newlines? [
either pl/flat? [
new-line/skip rows true cols
][
new-line/all rows true
]
]
pl/expecting: none
rows
]
read-cmd: func [port [port!] cmd [integer!] /local res][
either cmd = defs/cmd/statistics [
to-string read-packet port
][
res: read-packet port
either all [cmd = defs/cmd/ping zero? port/locals/last-status][true][none]
]
]
flush-pending-data: func [port [port!] /local pl len EOF?][
if throws/closed = catch [
pl: port/locals
if any [not pl/stream-end? pl/more-results?][
net-log "flushing unread data..."
until [
clear pl/buffer
len: read port pl/buffer pl/buf-size
all [
pl/buf-size > len
either find pl/capabilities 'protocol-41 [
all [
any [
EOF?: end-marker = pick* tail pl/buffer -5 ; EOF packet
0 = pick* tail pl/buffer -7 ; OK packet
]
zero? (pick* tail pl/buffer pick* [-2 -4] EOF?) and 8 ; no more results
]
][
end-marker = last pl/buffer
]
]
]
net-log "flush end."
pl/stream-end?: true
]
][
try-reconnect port
]
]
;------ Data sending ------
write-byte: func [value [integer!]][to char! value]
write-int: func [value [integer!]][
join to char! value // 256 to char! value / 256
]
write-int24: func [value [integer!]][
join to char! value // 256 [
to char! (to integer! value / 256) and 255
to char! (to integer! value / 65536) and 255
]
]
write-long: func [value [integer!]][
join to char! value // 256 [
to char! (to integer! value / 256) and 255
to char! (to integer! value / 65536) and 255
to char! (to integer! value / 16777216) and 255
]
]
write-string: func [value [string!]][
join value to char! 0
]
send-packet: func [port [port!] data [string!]][
data: to-binary rejoin [
write-int24 length? data
write-byte port/locals/seq-num: port/locals/seq-num + 1
data
]
write-io port/sub-port data length? data
port/locals/stream-end?: false
]
send-cmd: func [port [port!] cmd [integer!] cmd-data] compose/deep [
port/locals/seq-num: -1
send-packet port rejoin [
write-byte cmd
switch/default cmd [
(defs/cmd/quit) [""]
(defs/cmd/shutdown) [""]
(defs/cmd/statistics) [""]
(defs/cmd/debug) [""]
(defs/cmd/ping) [""]
(defs/cmd/reload) [write-byte encode-refresh cmd-data]
(defs/cmd/process-kill) [write-long pick* cmd-data 1]
(defs/cmd/change-user) [
rejoin [
write-string pick* cmd-data 1
write-string scramble pick* cmd-data 2 port
write-string pick* cmd-data 3
]
]
][either string? cmd-data [cmd-data][pick* cmd-data 1]]
]
]
insert-query: func [port [port!] data [string! block!] /local colnb][
net-log data
send-cmd port defs/cmd/query data
colnb: read-columns-number port
if not any [zero? colnb port/locals/stream-end?][
read-columns-headers port colnb
]
none
]
insert-all-queries: func [port [port!] data [string!] /local s e res d][
d: port/locals/delimiter
parse/all s: data [
any [
#"#" thru newline
| #"'" any ["\\" | "\'" | "''" | not-squote] #"'"
|{"} any [{\"} | {""} | not-dquote] {"}
| #"`" thru #"`"
| "begin" thru "end"
| e: d (
clear sql-buffer
insert*/part sql-buffer s e
res: insert-query port sql-buffer
) any [ws] s:
| skip
]
]
if not tail? s [res: insert-query port s]
res
]
insert-cmd: func [port [port!] data [block!] /local type res][
type: select defs/cmd data/1
either type [
send-cmd port type next data
res: read-cmd port type
port/locals/stream-end?: true
res
][
port/locals/stream-end?: true
net-error reform ["Unknown command" data/1]
]
]
try-reconnect: func [port [port!]][
net-log "Connection closed by server! Reconnecting..."
port/state/flags: port/state/flags or 1024 or 2 ; avoid triggering READ special actions + reset closed flag
if throws/closed = catch [open port][net-error "Server down!"]
]
check-opened: func [port [port!]][
if not zero? port/sub-port/state/flags and 1024 [
try-reconnect port
]
]
do-handshake: func [port [port!] /local pl client-param key err data][
either pl: port/locals [
clear pl/cache
clear pl/buffer
pl/seq-num: 0
pl/last-status:
pl/stream-end?: none
][
pl: port/locals: make locals-class []
pl/buffer: make binary! pl/buf-size
pl/cache: make binary! pl/buf-size
pl/conv-list: copy*/deep conv-model
pl/capabilities: make block! 1
]
parse/all read-packet port [
read-byte (pl/protocol: byte)
read-string (pl/version: string)
read-long (pl/thread-id: long)
read-string (pl/crypt-seed: string)
read-int (pl/capabilities: decode/features int)
read-byte (pl/character-set: byte)
read-int (pl/server-status: int)
13 skip ; reserved for future use
read-string (
if string [
pl/crypt-seed: join copy* pl/crypt-seed string
pl/auth-v11: yes
]
)
to end ; skipping data for pre4.1.x protocols
]
if pl/protocol = -1 [
close* port/sub-port
net-error "Server configuration denies access to locals source^/Port closed!"
]
show-server pl
client-param: defs/client/found-rows or defs/client/connect-with-db
client-param: either pl/protocol > 9 [
client-param or defs/client/long-password
][
client-param and complement defs/client/long-password
]
either find pl/capabilities 'protocol-41 [
client-param: client-param
or defs/client/protocol-41
or defs/client/multi-queries
or defs/client/multi-results
or defs/client/long-password
or defs/client/secure-connection
send-packet port rejoin [
write-long client-param
write-long (length? port/user) + (length? port/pass)
+ 7 + std-header-length
write-byte pl/character-set
{^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@}
write-string port/user
write-byte length? key: scramble port/pass port
key
;"^@"
write-string any [port/path "^@"]
]
][
send-packet port rejoin [
write-int client-param
write-int24 (length? port/user) + (length? port/pass)
+ 7 + std-header-length
write-string port/user
write-string key: scramble port/pass port
write-string any [port/path ""]
]
]
either error? set/any 'err try [data: read-packet port][
any [all [find key #{00} pl/error-code] err] ; -- detect the flaw in the protocol
][
if all [1 = length? data data/1 = #"^(FE)"][
net-log "Switching to old password mode!"
send-packet port write-string scramble/v10 port/pass port
read-packet port
]
net-log "Connected to server. Handshake OK"
none
]
]
;------ Public interface ------
init: func [port [port!] spec /local scheme args][
if url? spec [net-utils/url-parser/parse-url port spec]
scheme: port/scheme
port/url: spec
if none? port/host [
net-error reform ["No network server for" scheme "is specified"]
]
if none? port/port-id [
net-error reform ["No port address for" scheme "is specified"]
]
if all [none? port/path port/target][
port/path: port/target
port/target: none
]
if all [port/path slash = last port/path][
remove back tail port/path
]
if none? port/user [port/user: make string! 0]
if none? port/pass [port/pass: make string! 0]
if port/pass = "?" [port/pass: ask/hide "Password: "]
]
open: func [port [port!] /local retry q sql][
retry: 10
until [
open-proto port
set-modes* port/sub-port [keep-alive: true]
port/sub-port/state/flags: 524835 ; force /direct/binary mode
retry: retry - 1
if res: do-handshake port [close* port/sub-port]
any [none? res zero? retry]
]
if zero? retry [net-error "Cannot handshake with server"]
port/locals/stream-end?: true ; force stream-end, so 'copy won't timeout !
if zero? port/state/flags and 2 [
either sql: port/state/custom [
if not string? sql: first sql [net-error "invalid query"]
insert port sql
][
insert port either port/target [
join "DESC " port/target
][
port/locals/flat?: on
join "SHOW " pick* ["DATABASES" "TABLES"] not port/path