This repository has been archived by the owner on Jan 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpackets.go
514 lines (422 loc) · 11.6 KB
/
packets.go
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
// Copyright 2013 Julien Schmidt. All rights reserved.
// http://www.julienschmidt.com
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package sphinxql
import (
"bytes"
"database/sql/driver"
"encoding/binary"
"errors"
"fmt"
"io"
)
// Packets documentation:
// http://dev.mysql.com/doc/internals/en/client-server-protocol.html
// Read packet to buffer 'data'
func (mc *sphinxqlConn) readPacket() (data []byte, err error) {
// Read packet header
data = make([]byte, 4)
err = mc.buf.read(data)
if err != nil {
errLog.Print(err.Error())
return nil, driver.ErrBadConn
}
// Packet Length [24 bit]
pktLen := uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16
if pktLen < 1 {
errLog.Print(errMalformPkt.Error())
return nil, driver.ErrBadConn
}
// Check Packet Sync [8 bit]
if data[3] != mc.sequence {
if data[3] > mc.sequence {
return nil, errPktSyncMul
} else {
return nil, errPktSync
}
}
mc.sequence++
// Read packet body [pktLen bytes]
data = make([]byte, pktLen)
err = mc.buf.read(data)
if err == nil {
return data, nil
}
errLog.Print(err.Error())
return nil, driver.ErrBadConn
}
// Write packet buffer 'data'
// The packet header must be already included
func (mc *sphinxqlConn) writePacket(data []byte) error {
// Write packet
n, err := mc.netConn.Write(data)
if err == nil && n == len(data) {
mc.sequence++
return nil
}
if err == nil { // n != len(data)
errLog.Print(errMalformPkt.Error())
} else {
errLog.Print(err.Error())
}
return driver.ErrBadConn
}
/******************************************************************************
* Initialisation Process *
******************************************************************************/
// Handshake Initialization Packet
// http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::Handshake
func (mc *sphinxqlConn) readInitPacket() (err error) {
data, err := mc.readPacket()
if err != nil {
return
}
if data[0] == 255 {
return mc.handleErrorPacket(data)
}
// protocol version [1 byte]
if data[0] < minProtocolVersion {
err = fmt.Errorf(
"Unsupported MySQL Protocol Version %d. Protocol Version %d or higher is required",
data[0],
minProtocolVersion)
}
// server version [null terminated string]
// connection id [4 bytes]
pos := 1 + bytes.IndexByte(data[1:], 0x00) + 1 + 4
// first part of the password cipher [8 bytes]
mc.cipher = append(mc.cipher, data[pos:pos+8]...)
// (filler) always 0x00 [1 byte]
pos += 8 + 1
// capability flags (lower 2 bytes) [2 bytes]
mc.flags = clientFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
if mc.flags&clientProtocol41 == 0 {
err = errors.New("SphinxQL-Server does not support required Protocol 41+")
}
pos += 2
if len(data) > pos {
// character set [1 byte]
mc.charset = data[pos]
// status flags [2 bytes]
// capability flags (upper 2 bytes) [2 bytes]
// length of auth-plugin-data [1 byte]
// reserved (all [00]) [10 byte]
pos += 1 + 2 + 2 + 1 + 10
// second part of the password cipher [12? bytes]
// The documentation is ambiguous about the length.
// The official Python library uses the fixed length 12
// which is not documented but seems to work.
mc.cipher = append(mc.cipher, data[pos:pos+12]...)
if data[len(data)-1] == 0 {
return
}
return errMalformPkt
}
return
}
// Client Authentication Packet
// http://dev.mysql.com/doc/internals/en/connection-phase.html#packet-Protocol::HandshakeResponse
func (mc *sphinxqlConn) writeAuthPacket() error {
// Adjust client flags based on server support
clientFlags := uint32(
clientProtocol41 |
clientSecureConn |
clientLongPassword |
clientTransactions,
)
if mc.flags&clientLongFlag > 0 {
clientFlags |= uint32(clientLongFlag)
}
// User Password
scrambleBuff := scramblePassword(mc.cipher, []byte(mc.cfg.passwd))
mc.cipher = nil
pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff)
// To specify a db name
if len(mc.cfg.dbname) > 0 {
clientFlags |= uint32(clientConnectWithDB)
pktLen += len(mc.cfg.dbname) + 1
}
// Calculate packet length and make buffer with that size
data := make([]byte, pktLen+4)
// Add the packet header [24bit length + 1 byte sequence]
data[0] = byte(pktLen)
data[1] = byte(pktLen >> 8)
data[2] = byte(pktLen >> 16)
data[3] = mc.sequence
// ClientFlags [32 bit]
data[4] = byte(clientFlags)
data[5] = byte(clientFlags >> 8)
data[6] = byte(clientFlags >> 16)
data[7] = byte(clientFlags >> 24)
// MaxPacketSize [32 bit] (1<<24 - 1)
data[8] = 0xff
data[9] = 0xff
data[10] = 0xff
//data[11] = 0x00
// Charset [1 byte]
data[12] = mc.charset
// Filler [23 byte] (all 0x00)
pos := 13 + 23
// User [null terminated string]
if len(mc.cfg.user) > 0 {
pos += copy(data[pos:], mc.cfg.user)
}
//data[pos] = 0x00
pos++
// ScrambleBuffer [length encoded integer]
data[pos] = byte(len(scrambleBuff))
pos += 1 + copy(data[pos+1:], scrambleBuff)
// Databasename [null terminated string]
if len(mc.cfg.dbname) > 0 {
pos += copy(data[pos:], mc.cfg.dbname)
//data[pos] = 0x00
}
// Send Auth packet
return mc.writePacket(data)
}
/******************************************************************************
* Command Packets *
******************************************************************************/
func (mc *sphinxqlConn) writeCommandPacket(command commandType) error {
// Reset Packet Sequence
mc.sequence = 0
// Send CMD packet
return mc.writePacket([]byte{
// Add the packet header [24bit length + 1 byte sequence]
0x05, // 5 bytes long
0x00,
0x00,
mc.sequence,
// Add command byte
byte(command),
})
}
func (mc *sphinxqlConn) writeCommandPacketStr(command commandType, arg string) error {
// Reset Packet Sequence
mc.sequence = 0
pktLen := 1 + len(arg)
data := make([]byte, pktLen+4)
// Add the packet header [24bit length + 1 byte sequence]
data[0] = byte(pktLen)
data[1] = byte(pktLen >> 8)
data[2] = byte(pktLen >> 16)
data[3] = mc.sequence
// Add command byte
data[4] = byte(command)
// Add arg
copy(data[5:], arg)
// Send CMD packet
return mc.writePacket(data)
}
func (mc *sphinxqlConn) writeCommandPacketUint32(command commandType, arg uint32) error {
// Reset Packet Sequence
mc.sequence = 0
// Send CMD packet
return mc.writePacket([]byte{
// Add the packet header [24bit length + 1 byte sequence]
0x05, // 5 bytes long
0x00,
0x00,
mc.sequence,
// Add command byte
byte(command),
// Add arg [32 bit]
byte(arg),
byte(arg >> 8),
byte(arg >> 16),
byte(arg >> 24),
})
}
/******************************************************************************
* Result Packets *
******************************************************************************/
// Returns error if Packet is not an 'Result OK'-Packet
func (mc *sphinxqlConn) readResultOK() error {
data, err := mc.readPacket()
if err == nil {
switch data[0] {
// OK
case 0:
mc.handleOkPacket(data)
return nil
// EOF, someone is using old_passwords
case 254:
return errOldPassword
}
// ERROR
return mc.handleErrorPacket(data)
}
return err
}
// Result Set Header Packet
// http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::Resultset
func (mc *sphinxqlConn) readResultSetHeaderPacket() (int, error) {
data, err := mc.readPacket()
if err == nil {
if data[0] == 0 {
mc.handleOkPacket(data)
return 0, nil
} else if data[0] == 255 {
return 0, mc.handleErrorPacket(data)
}
// column count
num, _, n := readLengthEncodedInteger(data)
if n-len(data) == 0 {
return int(num), nil
}
return 0, errMalformPkt
}
return 0, err
}
// Error Packet
// http://dev.mysql.com/doc/internals/en/overview.html#packet-ERR_Packet
func (mc *sphinxqlConn) handleErrorPacket(data []byte) error {
if data[0] != 255 {
return errMalformPkt
}
// 0xff [1 byte]
// Error Number [16 bit uint]
errno := binary.LittleEndian.Uint16(data[1:3])
pos := 3
// SQL State [optional: # + 5bytes string]
//sqlstate := string(data[pos : pos+6])
if data[pos] == 0x23 {
pos = 9
}
// Error Message [string]
return fmt.Errorf("Error %d: %s", errno, string(data[pos:]))
}
// Ok Packet
// http://dev.mysql.com/doc/internals/en/overview.html#packet-OK_Packet
func (mc *sphinxqlConn) handleOkPacket(data []byte) {
var n int
// 0x00 [1 byte]
// Affected rows [Length Coded Binary]
mc.affectedRows, _, n = readLengthEncodedInteger(data[1:])
// Insert id [Length Coded Binary]
mc.insertId, _, _ = readLengthEncodedInteger(data[1+n:])
// server_status [2 bytes]
// warning count [2 bytes]
// message [until end of packet]
}
// Read Packets as Field Packets until EOF-Packet or an Error appears
// http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-Protocol::ColumnDefinition41
func (mc *sphinxqlConn) readColumns(count int) (columns []sphinxqlField, err error) {
var data []byte
var i, pos, n int
var name []byte
columns = make([]sphinxqlField, count)
for {
data, err = mc.readPacket()
if err != nil {
return
}
// EOF Packet
if data[0] == 254 && len(data) == 5 {
if i != count {
err = fmt.Errorf("ColumnsCount mismatch n:%d len:%d", count, len(columns))
}
return
}
// Catalog
pos, err = skipLengthEnodedString(data)
if err != nil {
return
}
// Database [len coded string]
n, err = skipLengthEnodedString(data[pos:])
if err != nil {
return
}
pos += n
// Table [len coded string]
n, err = skipLengthEnodedString(data[pos:])
if err != nil {
return
}
pos += n
// Original table [len coded string]
n, err = skipLengthEnodedString(data[pos:])
if err != nil {
return
}
pos += n
// Name [len coded string]
name, _, n, err = readLengthEnodedString(data[pos:])
if err != nil {
return
}
columns[i].name = string(name)
pos += n
// Original name [len coded string]
n, err = skipLengthEnodedString(data[pos:])
if err != nil {
return
}
// Filler [1 byte]
// Charset [16 bit uint]
// Length [32 bit uint]
pos += n + 1 + 2 + 4
// Field type [byte]
columns[i].fieldType = data[pos]
pos++
// Flags [16 bit uint]
columns[i].flags = fieldFlag(binary.LittleEndian.Uint16(data[pos : pos+2]))
//pos += 2
// Decimals [8 bit uint]
//pos++
// Default value [len coded binary]
//if pos < len(data) {
// defaultVal, _, err = bytesToLengthCodedBinary(data[pos:])
//}
i++
}
return
}
// Read Packets as Field Packets until EOF-Packet or an Error appears
// http://dev.mysql.com/doc/internals/en/text-protocol.html#packet-ProtocolText::ResultsetRow
func (rows *sphinxqlRows) readRow(dest []driver.Value) (err error) {
data, err := rows.mc.readPacket()
if err != nil {
return
}
// EOF Packet
if data[0] == 254 && len(data) == 5 {
return io.EOF
}
// RowSet Packet
var n int
var isNull bool
pos := 0
for i := range dest {
// Read bytes and convert to string
dest[i], isNull, n, err = readLengthEnodedString(data[pos:])
pos += n
if err == nil {
if !isNull {
continue
} else {
dest[i] = nil
continue
}
}
return // err
}
return
}
// Reads Packets until EOF-Packet or an Error appears. Returns count of Packets read
func (mc *sphinxqlConn) readUntilEOF() (err error) {
var data []byte
for {
data, err = mc.readPacket()
// No Err and no EOF Packet
if err == nil && (data[0] != 254 || len(data) != 5) {
continue
}
return // Err or EOF
}
return
}