-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
486 lines (391 loc) · 9.45 KB
/
connection.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
package tinydriver
import (
"bufio"
"context"
"database/sql/driver"
"errors"
"fmt"
"log"
"net"
"strconv"
"strings"
"time"
"mellium.im/sasl"
)
// https://www.postgresql.org/docs/current/protocol-message-formats.html
// Message format
const (
msgAuthenticationOk = 'R'
msgBackendKeyData = 'K'
msgReadyForQuery = 'Z'
msgParameterStatus = 'S'
msgSASLInitialResponse = 'p'
msgSASLResponse = 'p'
msgAuthenticationSASLContinue = 'R'
msgAuthenticationSASLFinal = 'R'
msgErrorResponse = 'E'
msgRowDescription = 'T'
msgCommandComplete = 'C'
msgNoticeResponse = 'N'
msgDataRow = 'D'
msgQuery = 'Q'
kindAuthenticationOk int32 = 10
)
type Connection struct {
cfg *Config
conn net.Conn
reader *Reader
processID int32
secretKey int32
}
func (c *Connection) Begin() (driver.Tx, error) {
//TODO implement me
panic("implement me")
}
const protocolVersion int32 = 196608
func NewConnection(ctx context.Context, cfg *Config) (*Connection, error) {
netDialer := &net.Dialer{
Timeout: time.Second,
KeepAlive: 5 * time.Minute,
}
nConn, err := netDialer.DialContext(ctx, cfg.Network, cfg.Addr())
if err != nil {
return nil, fmt.Errorf("dial: %w", err)
}
reader := NewReader(bufio.NewReader(nConn))
conn := Connection{conn: nConn, reader: reader, cfg: cfg}
if err := conn.handshake(ctx); err != nil {
return nil, fmt.Errorf("handshake: %w", err)
}
return &conn, nil
}
func (c *Connection) Prepare(query string) (driver.Stmt, error) {
//TODO implement me
panic("implement me")
}
func (c *Connection) Close() error {
return c.conn.Close()
}
func (c *Connection) handshake(ctx context.Context) error {
data := c.prepareStartupMsg()
if _, err := c.conn.Write(data); err != nil {
return err
}
for {
msgType, err := c.reader.ReadMessageType()
if err != nil {
return err
}
msgLen, err := c.reader.MsgLen()
if err != nil {
return err
}
switch msgType {
case msgAuthenticationOk:
// STEP 1: AUTH
kind, err := c.reader.Int32()
if err != nil {
return fmt.Errorf("get auth kind: %w", err)
}
switch kind {
case kindAuthenticationOk:
if err := c.authSASL(ctx, c.reader); err != nil {
return fmt.Errorf("auth: %w", err)
}
default:
return fmt.Errorf("auth kind not implemented: %d", kind)
}
case msgReadyForQuery:
return c.reader.Discard(msgLen)
case msgBackendKeyData:
// STEP 3: BackendKeyData
processID, err := c.reader.Int32()
if err != nil {
return err
}
secretKey, err := c.reader.Int32()
if err != nil {
return err
}
c.processID = processID
c.secretKey = secretKey
case msgParameterStatus:
// STEP 2: parameterStatus
if err := c.reader.Discard(msgLen); err != nil {
return err
}
default:
return fmt.Errorf("not implemented: %s", string(msgType))
}
}
}
func (c *Connection) writeQuery(ctx context.Context, query string) error {
var b Buffer
b.WriteStartMsg(msgQuery)
b.WriteString(query)
b.CalculateSize(1)
_, err := c.conn.Write(b.Data())
return err
}
func (c *Connection) authSASL(ctx context.Context, reader *Reader) error {
var saslMech sasl.Mechanism
mech, err := reader.String()
if err != nil {
return err
}
switch mech {
case sasl.ScramSha256.Name:
saslMech = sasl.ScramSha256
default:
return fmt.Errorf("mechanism not implemented: %s", mech)
}
// extra zero
_, err = reader.String()
if err != nil {
return err
}
creds := sasl.Credentials(func() (Username, Password, Identity []byte) {
return []byte(c.cfg.Username), []byte(c.cfg.Password), nil
})
client := sasl.NewClient(saslMech, creds)
_, resp, err := client.Step(nil)
if err != nil {
return fmt.Errorf("client.Step 1 failed: %w", err)
}
data := c.saslFirstMsg(saslMech, resp)
_, err = c.conn.Write(data)
if err != nil {
return err
}
msgType, err := reader.ReadMessageType()
if err != nil {
return err
}
switch msgType {
case msgAuthenticationSASLContinue:
msgLen, err := reader.MsgLen()
if err != nil {
return err
}
challenge, err := reader.Int32()
if err != nil {
return err
}
if challenge != 11 {
return errors.New("challenge failed")
}
const challengeLen = 4 // int32
payload, err := reader.ReadNumBytes(int(msgLen - challengeLen))
if err != nil {
return err
}
_, resp, err = client.Step(payload)
if err != nil {
return fmt.Errorf("client.Step 2 failed: %w", err)
}
var b Buffer
b.WriteStartMsg(msgSASLResponse)
b.WriteBytes(resp)
b.CalculateSize(1)
if _, err = c.conn.Write(b.Data()); err != nil {
return err
}
default:
return fmt.Errorf("not implemented: %s", string(msgType))
}
msgType, err = reader.ReadMessageType()
if err != nil {
return err
}
msgLen, err := reader.MsgLen()
if err != nil {
return err
}
switch msgType {
case msgAuthenticationSASLFinal:
challenge, err := reader.Int32()
if err != nil {
return err
}
if challenge != 12 {
return errors.New("challenge failed")
}
resp, err := reader.ReadNumBytes(int(msgLen - 4))
if err != nil {
return err
}
msgType, err := reader.ReadMessageType()
if err != nil {
return err
}
_, err = reader.MsgLen()
if err != nil {
return err
}
switch msgType {
case msgAuthenticationOk:
n, err := reader.Int32()
if err != nil {
return err
}
if n != 0 {
return errors.New("invalid auth code")
}
default:
return fmt.Errorf("not implemented: %s", string(msgType))
}
if _, _, err := client.Step(resp); err != nil {
return fmt.Errorf("client.Step 3 failed: %w", err)
}
if client.State() != sasl.ValidServerResponse {
return fmt.Errorf("got state=%q, wanted %q", client.State(), sasl.ValidServerResponse)
}
case msgErrorResponse:
dErr, err := c.reader.parseError()
if err != nil {
return err
}
return dErr
default:
return fmt.Errorf("not implemented: %s", string(msgType))
}
log.Println("authentication was successful")
return nil
}
func (c *Connection) prepareStartupMsg() []byte {
var b Buffer
// size of data (4 byte) without first byte (message type)
b.WriteBytes([]byte{0, 0, 0, 0})
b.WriteInt32(protocolVersion)
b.WriteString("user")
b.WriteString(c.cfg.Username)
b.WriteString("database")
b.WriteString(c.cfg.Database)
b.WriteBytes([]byte{0})
b.CalculateSize(0)
return b.Data()
}
func (c *Connection) saslFirstMsg(mech sasl.Mechanism, resp []byte) []byte {
var b Buffer
b.WriteBytes([]byte{msgSASLInitialResponse})
b.WriteBytes([]byte{0, 0, 0, 0})
b.WriteString(mech.Name)
b.WriteInt32(int32(len(resp)))
b.WriteBytes(resp)
b.CalculateSize(1)
return b.Data()
}
func (c *Connection) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
q, err := formatQuery(query, args)
if err != nil {
return nil, fmt.Errorf("format query: %w", err)
}
if err := c.writeQuery(ctx, q); err != nil {
return nil, fmt.Errorf("write query: %w", err)
}
rows, err := c.readQueryData(ctx)
if err != nil {
return nil, fmt.Errorf("read query data: %w", err)
}
return rows, nil
}
func (c *Connection) readQueryData(ctx context.Context) (*rows, error) {
for {
msgType, err := c.reader.ReadMessageType()
if err != nil {
return nil, fmt.Errorf("read message type: %w", err)
}
msgLen, err := c.reader.Int32()
if err != nil {
return nil, fmt.Errorf("read int32: %w", err)
}
switch msgType {
case msgRowDescription:
rowsDesc, err := c.rowDescription(ctx)
if err != nil {
return nil, fmt.Errorf("read row description: %w", err)
}
return newRows(c, rowsDesc), nil
case msgCommandComplete, msgNoticeResponse, msgParameterStatus:
if err := c.reader.Discard(msgLen); err != nil {
return nil, fmt.Errorf("discard: %w", err)
}
case msgErrorResponse:
dErr, err := c.reader.parseError()
if err != nil {
return nil, fmt.Errorf("parse error: %w", err)
}
return nil, dErr
default:
return nil, fmt.Errorf("not implemented: %s", string(msgType))
}
}
}
func (c *Connection) rowDescription(ctx context.Context) ([]*rowDescription, error) {
numCol, err := c.reader.int16()
if err != nil {
return nil, fmt.Errorf("read int16: %w", err)
}
var descs []*rowDescription
for i := 0; i < int(numCol); i++ {
columnName, err := c.reader.String()
if err != nil {
return nil, err
}
objID, err := c.reader.Int32()
if err != nil {
return nil, err
}
attrID, err := c.reader.int16()
if err != nil {
return nil, err
}
oid, err := c.reader.Int32()
if err != nil {
return nil, err
}
typLen, err := c.reader.int16()
if err != nil {
return nil, err
}
attTypMod, err := c.reader.Int32()
if err != nil {
return nil, err
}
format, err := c.reader.int16()
if err != nil {
return nil, err
}
log.Printf(
"column name: %s, object id: %d attr id: %d, oid: %d, type len: %d , att type mod: %d format: %d",
columnName,
objID,
attrID,
oid,
typLen,
attTypMod,
format,
)
desc := rowDescription{
name: columnName,
oid: oid,
}
descs = append(descs, &desc)
}
return descs, nil
}
func formatQuery(query string, args []driver.NamedValue) (string, error) {
switch len(args) {
case 0:
return query, nil
case 1:
val, ok := args[0].Value.(int64)
if !ok {
return query, errors.New("type casting error")
}
id := strconv.Itoa(int(val))
return strings.Replace(query, "$1", id, 1), nil
default:
return query, errors.New("not implemented: only one arg")
}
}