-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn.go
1932 lines (1750 loc) · 61.5 KB
/
conn.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
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
// Copyright 2018 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package pgwire
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"runtime/debug"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/coltypes"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/hba"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logtags"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
)
const (
authOK int32 = 0
authCleartextPassword int32 = 3
)
// conn implements a pgwire network connection (version 3 of the protocol,
// implemented by Postgres v7.4 and later). conn.serve() reads protocol
// messages, transforms them into commands that it pushes onto a StmtBuf (where
// they'll be picked up and executed by the connExecutor).
// The connExecutor produces results for the commands, which are delivered to
// the client through the sql.ClientComm interface, implemented by this conn
// (code is in command_result.go).
type conn struct {
conn net.Conn
sessionArgs sql.SessionArgs
metrics *ServerMetrics
// rd is a buffered reader consuming conn. All reads from conn go through
// this.
rd bufio.Reader
// parser is used to avoid allocating a parser each time.
parser parser.Parser
// stmtBuf is populated with commands queued for execution by this conn.
stmtBuf sql.StmtBuf
// err is an error, accessed atomically. It represents any error encountered
// while accessing the underlying network connection. This can read via
// GetErr() by anybody. If it is found to be != nil, the conn is no longer to
// be used.
err atomic.Value
// writerState groups together all aspects of the write-side state of the
// connection.
writerState struct {
fi flushInfo
// buf contains command results (rows, etc.) until they're flushed to the
// network connection.
buf bytes.Buffer
tagBuf [64]byte
}
readBuf pgwirebase.ReadBuffer
msgBuilder writeBuffer
sv *settings.Values
}
type authOptions struct {
skipAuth bool // test-only
authHook func(ctx context.Context) error // test-only
insecure bool
auth *hba.Conf
ie *sql.InternalExecutor
}
// serveConn creates a conn that will serve the netConn. It returns once the
// network connection is closed.
//
// Internally, a connExecutor will be created to execute commands. Commands read
// from the network are buffered in a stmtBuf which is consumed by the
// connExecutor. The connExecutor produces results which are buffered and
// sometimes synchronously flushed to the network.
//
// The reader goroutine (this one) outlives the connExecutor's goroutine (the
// "processor goroutine").
// However, they can both signal each other to stop. Here's how the different
// cases work:
// 1) The reader receives a ClientMsgTerminate protocol packet: the reader
// closes the stmtBuf and also cancels the command processing context. These
// actions will prompt the command processor to finish.
// 2) The reader gets a read error from the network connection: like above, the
// reader closes the command processor.
// 3) The reader's context is canceled (happens when the server is draining but
// the connection was busy and hasn't quit yet): the reader notices the canceled
// context and, like above, closes the processor.
// 4) The processor encouters an error. This error can come from various fatal
// conditions encoutered internally by the processor, or from a network
// communication error encountered while flushing results to the network.
// The processor will cancel the reader's context and terminate.
// Note that query processing errors are different; they don't cause the
// termination of the connection.
//
// Draining notes:
//
// The reader notices that the server is draining by polling the draining()
// closure passed to serveConn. At that point, the reader delegates the
// responsibility of closing the connection to the statement processor: it will
// push a DrainRequest to the stmtBuf which signal the processor to quit ASAP.
// The processor will quit immediately upon seeing that command if it's not
// currently in a transaction. If it is in a transaction, it will wait until the
// first time a Sync command is processed outside of a transaction - the logic
// being that we want to stop when we're both outside transactions and outside
// batches.
func serveConn(
ctx context.Context,
netConn net.Conn,
sArgs sql.SessionArgs,
metrics *ServerMetrics,
reserved mon.BoundAccount,
sqlServer *sql.Server,
draining func() bool,
authOpt authOptions,
stopper *stop.Stopper,
) {
sArgs.RemoteAddr = netConn.RemoteAddr()
if log.V(2) {
log.Infof(ctx, "new connection with options: %+v", sArgs)
}
c := newConn(netConn, sArgs, metrics, &sqlServer.GetExecutorConfig().Settings.SV)
// Do the reading of commands from the network.
c.serveImpl(ctx, draining, sqlServer, reserved, authOpt, stopper)
}
func newConn(
netConn net.Conn, sArgs sql.SessionArgs, metrics *ServerMetrics, sv *settings.Values,
) *conn {
c := &conn{
conn: netConn,
sessionArgs: sArgs,
metrics: metrics,
rd: *bufio.NewReader(netConn),
sv: sv,
}
c.stmtBuf.Init()
c.writerState.fi.buf = &c.writerState.buf
c.writerState.fi.lastFlushed = -1
c.writerState.fi.cmdStarts = make(map[sql.CmdPos]int)
c.msgBuilder.init(metrics.BytesOutCount)
return c
}
func (c *conn) setErr(err error) {
c.err.Store(err)
}
func (c *conn) GetErr() error {
err := c.err.Load()
if err != nil {
return err.(error)
}
return nil
}
// serveImpl continuously reads from the network connection and pushes execution
// instructions into a sql.StmtBuf, from where they'll be processed by a command
// "processor" goroutine (a connExecutor).
// The method returns when the pgwire termination message is received, when
// network communication fails, when the server is draining or when ctx is
// canceled (which also happens when draining (but not from the get-go), and
// when the processor encounters a fatal error).
//
// serveImpl always closes the network connection before returning.
//
// sqlServer is used to create the command processor. As a special facility for
// tests, sqlServer can be nil, in which case the command processor and the
// write-side of the connection will not be created.
func (c *conn) serveImpl(
ctx context.Context,
draining func() bool,
sqlServer *sql.Server,
reserved mon.BoundAccount,
authOpt authOptions,
stopper *stop.Stopper,
) {
defer func() { _ = c.conn.Close() }()
ctx = logtags.AddTag(ctx, "user", c.sessionArgs.User)
// NOTE: We're going to write a few messages to the connection in this method,
// for the handshake. After that, all writes are done async, in the
// startWriter() goroutine.
ctx, cancelConn := context.WithCancel(ctx)
defer cancelConn() // This calms the linter that wants these callbacks to always be called.
var sentDrainSignal bool
// The net.Conn is switched to a conn that exits if the ctx is canceled.
c.conn = newReadTimeoutConn(c.conn, func(tc *readTimeoutConn) error {
// If the context was canceled, it's time to stop reading. Either a
// higher-level server or the command processor have canceled us.
if ctx.Err() != nil {
return ctx.Err()
}
// If the server is draining, we'll let the processor know by pushing a
// DrainRequest. This will make the processor quit whenever it finds a good
// time.
if !sentDrainSignal && draining() {
_ /* err */ = c.stmtBuf.Push(ctx, sql.DrainRequest{})
sentDrainSignal = true
}
return nil
})
c.rd = *bufio.NewReader(c.conn)
// We'll build an authPipe to communicate with the authentication process.
authPipe := newAuthPipe(c)
var authenticator authenticator = authPipe
// procCh is the channel on which we'll receive the termination signal from
// the command processor.
var procCh <-chan error
if sqlServer != nil {
// Spawn the command processing goroutine, which also handles connection
// authentication). It will notify us when it's done through procCh, and
// we'll also interact with the authentication process through ac.
var ac AuthConn = authPipe
procCh = c.processCommandsAsync(ctx, authOpt, ac, sqlServer, reserved, cancelConn)
} else {
// sqlServer == nil means we are in a local test. In this case
// we only need the minimum to make pgx happy.
var err error
for param, value := range testingStatusReportParams {
if err := c.sendStatusParam(param, value); err != nil {
break
}
}
if err != nil {
reserved.Close(ctx)
return
}
var ac AuthConn = authPipe
// Simulate auth succeeding.
ac.AuthOK(fixedIntSizer{size: coltypes.Int8})
dummyCh := make(chan error)
close(dummyCh)
procCh = dummyCh
// An initial readyForQuery message is part of the handshake.
c.msgBuilder.initMsg(pgwirebase.ServerMsgReady)
c.msgBuilder.writeByte(byte(sql.IdleTxnBlock))
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
reserved.Close(ctx)
return
}
}
var err error
var terminateSeen bool
var doingExtendedQueryMessage bool
// We need an intSizer, which we're ultimately going to get from the
// authenticator once authentication succeeds (because it will actually be a
// ConnectionHandler). Until then, we unfortunately still need some intSizer
// because we technically might enqueue parsed statements in the statement
// buffer even before authentication succeeds (because we need this go routine
// to keep reading from the network connection while authentication is in
// progress in order to react to the connection closing).
var intSizer unqualifiedIntSizer = fixedIntSizer{size: coltypes.Int8}
var authDone bool
Loop:
for {
var typ pgwirebase.ClientMessageType
var n int
typ, n, err = c.readBuf.ReadTypedMsg(&c.rd)
c.metrics.BytesInCount.Inc(int64(n))
if err != nil {
break Loop
}
timeReceived := timeutil.Now()
log.VEventf(ctx, 2, "pgwire: processing %s", typ)
if !authDone {
if typ == pgwirebase.ClientMsgPassword {
var pwd []byte
if pwd, err = c.readBuf.GetBytes(n - 4); err != nil {
break Loop
}
// Pass the data to the authenticator. This hopefully causes it to finish
// authentication in the background and give us an intSizer when we loop
// around.
if err = authenticator.sendPwdData(pwd); err != nil {
break Loop
}
continue
}
// Wait for the auth result.
intSizer, err = authenticator.authResult()
if err != nil {
// The error has already been sent to the client.
break Loop
} else {
authDone = true
}
}
switch typ {
case pgwirebase.ClientMsgPassword:
// This messages are only acceptable during the auth phase, handled above.
err = pgwirebase.NewProtocolViolationErrorf("unexpected authentication data")
_ /* err */ = writeErr(
ctx, &sqlServer.GetExecutorConfig().Settings.SV, err,
&c.msgBuilder, &c.writerState.buf)
break Loop
case pgwirebase.ClientMsgSimpleQuery:
if doingExtendedQueryMessage {
if err = c.stmtBuf.Push(
ctx,
sql.SendError{
Err: pgwirebase.NewProtocolViolationErrorf(
"SimpleQuery not allowed while in extended protocol mode"),
},
); err != nil {
break
}
}
if err = c.handleSimpleQuery(
ctx, &c.readBuf, timeReceived, intSizer.GetUnqualifiedIntSize(),
); err != nil {
break
}
err = c.stmtBuf.Push(ctx, sql.Sync{})
case pgwirebase.ClientMsgExecute:
doingExtendedQueryMessage = true
err = c.handleExecute(ctx, &c.readBuf, timeReceived)
case pgwirebase.ClientMsgParse:
doingExtendedQueryMessage = true
err = c.handleParse(ctx, &c.readBuf, intSizer.GetUnqualifiedIntSize())
case pgwirebase.ClientMsgDescribe:
doingExtendedQueryMessage = true
err = c.handleDescribe(ctx, &c.readBuf)
case pgwirebase.ClientMsgBind:
doingExtendedQueryMessage = true
err = c.handleBind(ctx, &c.readBuf)
case pgwirebase.ClientMsgClose:
doingExtendedQueryMessage = true
err = c.handleClose(ctx, &c.readBuf)
case pgwirebase.ClientMsgTerminate:
terminateSeen = true
break Loop
case pgwirebase.ClientMsgSync:
doingExtendedQueryMessage = false
// We're starting a batch here. If the client continues using the extended
// protocol and encounters an error, everything until the next sync
// message has to be skipped. See:
// https://www.postgresql.org/docs/current/10/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
err = c.stmtBuf.Push(ctx, sql.Sync{})
case pgwirebase.ClientMsgFlush:
doingExtendedQueryMessage = true
err = c.handleFlush(ctx)
case pgwirebase.ClientMsgCopyData, pgwirebase.ClientMsgCopyDone, pgwirebase.ClientMsgCopyFail:
// We're supposed to ignore these messages, per the protocol spec. This
// state will happen when an error occurs on the server-side during a copy
// operation: the server will send an error and a ready message back to
// the client, and must then ignore further copy messages. See:
// https://github.com/postgres/postgres/blob/6e1dd2773eb60a6ab87b27b8d9391b756e904ac3/src/backend/tcop/postgres.c#L4295
default:
err = c.stmtBuf.Push(
ctx,
sql.SendError{Err: pgwirebase.NewUnrecognizedMsgTypeErr(typ)})
}
if err != nil {
break Loop
}
}
// We're done reading data from the client, so make the communication
// goroutine stop. Depending on what that goroutine is currently doing (or
// blocked on), we cancel and close all the possible channels to make sure we
// tickle it in the right way.
// Signal command processing to stop. It might be the case that the processor
// canceled our context and that's how we got here; in that case, this will
// be a no-op.
c.stmtBuf.Close()
// Cancel the processor's context.
cancelConn()
// In case the authenticator is blocked on waiting for data from the client,
// tell it that there's no more data coming. This is a no-op if authentication
// was completed already.
authenticator.noMorePwdData()
// Wait for the processor goroutine to finish, if it hasn't already. We're
// ignoring the error we get from it, as we have no use for it. It might be a
// connection error, or a context cancelation error case this goroutine is the
// one that triggered the execution to stop.
<-procCh
if terminateSeen {
return
}
// If we're draining, let the client know by piling on an AdminShutdownError
// and flushing the buffer.
if draining() {
// TODO(andrei): I think sending this extra error to the client if we also
// sent another error for the last query (like a context canceled) is a bad
// idead; see #22630. I think we should find a way to return the
// AdminShutdown error as the only result of the query.
_ /* err */ = writeErr(ctx, &sqlServer.GetExecutorConfig().Settings.SV,
newAdminShutdownErr(ErrDrainingExistingConn), &c.msgBuilder, &c.writerState.buf)
_ /* n */, _ /* err */ = c.writerState.buf.WriteTo(c.conn)
}
}
// unqualifiedIntSizer is used by a conn to get the SQL session's current int size
// setting.
//
// It's a restriction on the ConnectionHandler type.
type unqualifiedIntSizer interface {
// GetUnqualifiedIntSize returns the size that the parser should consider for an
// unqualified INT.
GetUnqualifiedIntSize() *coltypes.TInt
}
type fixedIntSizer struct {
size *coltypes.TInt
}
func (f fixedIntSizer) GetUnqualifiedIntSize() *coltypes.TInt {
return f.size
}
// processCommandsAsync spawns a goroutine that authenticates the connection and
// then processes commands from c.stmtBuf.
//
// It returns a channel that will be signaled when this goroutine is done.
// Whatever error is returned on that channel has already been written to the
// client connection, if applicable.
//
// If authentication fails, this goroutine finishes and, as always, cancelConn
// is called.
//
// Args:
// ac: An interface used by the authentication process to receive password data
// and to ultimately declare the authentication successful.
// reserved: Reserved memory. This method takes ownership.
// cancelConn: A function to be called when this goroutine exits. Its goal is to
// cancel the connection's context, thus stopping the connection's goroutine.
// The returned channel is also closed before this goroutine dies, but the
// connection's goroutine is not expected to be reading from that channel
// (instead, it's expected to always be monitoring the network connection).
func (c *conn) processCommandsAsync(
ctx context.Context,
authOpt authOptions,
ac AuthConn,
sqlServer *sql.Server,
reserved mon.BoundAccount,
cancelConn func(),
) <-chan error {
// reservedOwned is true while we own reserved, false when we pass ownership
// away.
reservedOwned := true
retCh := make(chan error, 1)
go func() {
var retErr error
var connHandler sql.ConnectionHandler
var authOK bool
defer func() {
// Release resources, if we still own them.
if reservedOwned {
reserved.Close(ctx)
}
// Notify the connection's goroutine that we're terminating. The
// connection might know already, as it might have triggered this
// goroutine's finish, but it also might be us that we're triggering the
// connection's death. This context cancelation serves to interrupt a
// network read on the connection's goroutine.
cancelConn()
pgwireKnobs := sqlServer.GetExecutorConfig().PGWireTestingKnobs
if pgwireKnobs != nil && pgwireKnobs.CatchPanics {
if r := recover(); r != nil {
// Catch the panic and return it to the client as an error.
pge := pgerror.NewErrorf(pgerror.CodeCrashShutdownError, "caught fatal error: %v", r)
pge.Detail = string(debug.Stack())
retErr = pge
_ = writeErr(
ctx, &sqlServer.GetExecutorConfig().Settings.SV, retErr,
&c.msgBuilder, &c.writerState.buf)
_ /* n */, _ /* err */ = c.writerState.buf.WriteTo(c.conn)
c.stmtBuf.Close()
// Send a ready for query to make sure the client can react.
// TODO(andrei, jordan): Why are we sending this exactly?
c.bufferReadyForQuery('I')
}
}
if !authOK {
ac.AuthFail(retErr)
}
// Inform the connection goroutine of success or failure.
retCh <- retErr
}()
// Authenticate the connection.
if !authOpt.skipAuth {
if authOpt.authHook != nil {
if retErr = authOpt.authHook(ctx); retErr != nil {
return
}
} else {
if retErr = c.handleAuthentication(
ctx, ac, authOpt.insecure, authOpt.ie, authOpt.auth,
sqlServer.GetExecutorConfig(),
); retErr != nil {
return
}
}
}
connHandler, retErr = c.sendInitialConnData(ctx, sqlServer)
if retErr != nil {
return
}
ac.AuthOK(connHandler)
authOK = true
// Now actually process commands.
reservedOwned = false // We're about to pass ownership away.
retErr = sqlServer.ServeConn(ctx, connHandler, reserved, cancelConn)
}()
return retCh
}
func (c *conn) sendStatusParam(param, value string) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgParameterStatus)
c.msgBuilder.writeTerminatedString(param)
c.msgBuilder.writeTerminatedString(value)
return c.msgBuilder.finishMsg(c.conn)
}
func (c *conn) sendInitialConnData(
ctx context.Context, sqlServer *sql.Server,
) (sql.ConnectionHandler, error) {
connHandler, err := sqlServer.SetupConn(
ctx, c.sessionArgs, &c.stmtBuf, c, c.metrics.SQLMemMetrics)
if err != nil {
_ /* err */ = writeErr(
ctx, &sqlServer.GetExecutorConfig().Settings.SV, err, &c.msgBuilder, c.conn)
return sql.ConnectionHandler{}, err
}
// Send the initial "status parameters" to the client. This
// overlaps partially with session variables. The client wants to
// see the values that result from the combination of server-side
// defaults with client-provided values.
// For details see: https://www.postgresql.org/docs/10/static/libpq-status.html
for _, param := range statusReportParams {
value := connHandler.GetStatusParam(ctx, param)
if err := c.sendStatusParam(param, value); err != nil {
return sql.ConnectionHandler{}, err
}
}
// The two following status parameters have no equivalent session
// variable.
if err := c.sendStatusParam("session_authorization", c.sessionArgs.User); err != nil {
return sql.ConnectionHandler{}, err
}
// TODO(knz): this should retrieve the admin status during
// authentication using the roles table, instead of using a
// simple/naive username match.
isSuperUser := c.sessionArgs.User == security.RootUser
superUserVal := "off"
if isSuperUser {
superUserVal = "on"
}
if err := c.sendStatusParam("is_superuser", superUserVal); err != nil {
return sql.ConnectionHandler{}, err
}
// An initial readyForQuery message is part of the handshake.
c.msgBuilder.initMsg(pgwirebase.ServerMsgReady)
c.msgBuilder.writeByte(byte(sql.IdleTxnBlock))
if err := c.msgBuilder.finishMsg(c.conn); err != nil {
return sql.ConnectionHandler{}, err
}
return connHandler, nil
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleSimpleQuery(
ctx context.Context,
buf *pgwirebase.ReadBuffer,
timeReceived time.Time,
unqualifiedIntSize *coltypes.TInt,
) error {
query, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
tracing.AnnotateTrace()
startParse := timeutil.Now()
stmts, err := c.parser.ParseWithInt(query, unqualifiedIntSize)
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
endParse := timeutil.Now()
if len(stmts) == 0 {
return c.stmtBuf.Push(
ctx, sql.ExecStmt{
Statement: parser.Statement{},
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
})
}
for i := range stmts {
// The CopyFrom statement is special. We need to detect it so we can hand
// control of the connection, through the stmtBuf, to a copyMachine, and
// block this network routine until control is passed back.
if cp, ok := stmts[i].AST.(*tree.CopyFrom); ok {
if len(stmts) != 1 {
// NOTE(andrei): I don't know if Postgres supports receiving a COPY
// together with other statements in the "simple" protocol, but I'd
// rather not worry about it since execution of COPY is special - it
// takes control over the connection.
return c.stmtBuf.Push(
ctx,
sql.SendError{
Err: pgwirebase.NewProtocolViolationErrorf(
"COPY together with other statements in a query string is not supported"),
})
}
copyDone := sync.WaitGroup{}
copyDone.Add(1)
if err := c.stmtBuf.Push(ctx, sql.CopyIn{Conn: c, Stmt: cp, CopyDone: ©Done}); err != nil {
return err
}
copyDone.Wait()
return nil
}
if err := c.stmtBuf.Push(
ctx,
sql.ExecStmt{
Statement: stmts[i],
TimeReceived: timeReceived,
ParseStart: startParse,
ParseEnd: endParse,
}); err != nil {
return err
}
}
return nil
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleParse(
ctx context.Context, buf *pgwirebase.ReadBuffer, nakedIntSize *coltypes.TInt,
) error {
// protocolErr is set if a protocol error has to be sent to the client. A
// stanza at the bottom of the function pushes instructions for sending this
// error.
var protocolErr *pgerror.Error
name, err := buf.GetString()
if protocolErr != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
query, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
// The client may provide type information for (some of) the placeholders.
numQArgTypes, err := buf.GetUint16()
if err != nil {
return err
}
inTypeHints := make([]oid.Oid, numQArgTypes)
for i := range inTypeHints {
typ, err := buf.GetUint32()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
inTypeHints[i] = oid.Oid(typ)
}
startParse := timeutil.Now()
stmts, err := c.parser.ParseWithInt(query, nakedIntSize)
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
if len(stmts) > 1 {
err := pgerror.NewWrongNumberOfPreparedStatements(len(stmts))
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var stmt parser.Statement
if len(stmts) == 1 {
stmt = stmts[0]
}
// len(stmts) == 0 results in a nil (empty) statement.
if len(inTypeHints) > stmt.NumPlaceholders {
err := pgwirebase.NewProtocolViolationErrorf(
"received too many type hints: %d vs %d placeholders in query",
len(inTypeHints), stmt.NumPlaceholders,
)
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var sqlTypeHints tree.PlaceholderTypes
if len(inTypeHints) > 0 {
// Prepare the mapping of SQL placeholder names to types. Pre-populate it with
// the type hints received from the client, if any.
sqlTypeHints = make(tree.PlaceholderTypes, stmt.NumPlaceholders)
for i, t := range inTypeHints {
if t == 0 {
continue
}
v, ok := types.OidToType[t]
if !ok {
err := pgwirebase.NewProtocolViolationErrorf("unknown oid type: %v", t)
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
sqlTypeHints[i] = v
}
}
endParse := timeutil.Now()
if _, ok := stmt.AST.(*tree.CopyFrom); ok {
// We don't support COPY in extended protocol because it'd be complicated:
// it wouldn't be the preparing, but the execution that would need to
// execute the copyMachine.
// Also note that COPY FROM in extended mode seems to be quite broken in
// Postgres too:
// https://www.postgresql.org/message-id/flat/CAMsr%2BYGvp2wRx9pPSxaKFdaObxX8DzWse%2BOkWk2xpXSvT0rq-g%40mail.gmail.com#CAMsr+YGvp2wRx9pPSxaKFdaObxX8DzWse+OkWk2xpXSvT0rq-g@mail.gmail.com
return c.stmtBuf.Push(ctx, sql.SendError{Err: fmt.Errorf("CopyFrom not supported in extended protocol mode")})
}
return c.stmtBuf.Push(
ctx,
sql.PrepareStmt{
Name: name,
Statement: stmt,
TypeHints: sqlTypeHints,
RawTypeHints: inTypeHints,
ParseStart: startParse,
ParseEnd: endParse,
})
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleDescribe(ctx context.Context, buf *pgwirebase.ReadBuffer) error {
typ, err := buf.GetPrepareType()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
name, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
return c.stmtBuf.Push(
ctx,
sql.DescribeStmt{
Name: name,
Type: typ,
})
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleClose(ctx context.Context, buf *pgwirebase.ReadBuffer) error {
typ, err := buf.GetPrepareType()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
name, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
return c.stmtBuf.Push(
ctx,
sql.DeletePreparedStmt{
Name: name,
Type: typ,
})
}
// handleBind queues instructions for creating a portal from a prepared
// statement.
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleBind(ctx context.Context, buf *pgwirebase.ReadBuffer) error {
portalName, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
statementName, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
// From the docs on number of argument format codes to bind:
// This can be zero to indicate that there are no arguments or that the
// arguments all use the default format (text); or one, in which case the
// specified format code is applied to all arguments; or it can equal the
// actual number of arguments.
// http://www.postgresql.org/docs/current/static/protocol-message-formats.html
numQArgFormatCodes, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
lenCodes := numQArgFormatCodes
if lenCodes == 0 {
lenCodes = 1
}
qArgFormatCodes := make([]pgwirebase.FormatCode, lenCodes)
switch numQArgFormatCodes {
case 0:
// No format codes means all arguments are passed as text.
qArgFormatCodes[0] = pgwirebase.FormatText
case 1:
// `1` means read one code and apply it to every argument.
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
fmtCode := pgwirebase.FormatCode(ch)
qArgFormatCodes[0] = fmtCode
default:
// Read one format code for each argument and apply it to that argument.
for i := range qArgFormatCodes {
code, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qArgFormatCodes[i] = pgwirebase.FormatCode(code)
}
}
numValues, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qargs := make([][]byte, numValues)
for i := 0; i < int(numValues); i++ {
plen, err := buf.GetUint32()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
if int32(plen) == -1 {
// The argument is a NULL value.
qargs[i] = nil
continue
}
b, err := buf.GetBytes(int(plen))
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qargs[i] = b
}
// From the docs on number of result-column format codes to bind:
// This can be zero to indicate that there are no result columns or that
// the result columns should all use the default format (text); or one, in
// which case the specified format code is applied to all result columns
// (if any); or it can equal the actual number of result columns of the
// query.
// http://www.postgresql.org/docs/current/static/protocol-message-formats.html
numColumnFormatCodes, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
var columnFormatCodes []pgwirebase.FormatCode
switch numColumnFormatCodes {
case 0:
// All columns will use the text format.
columnFormatCodes = make([]pgwirebase.FormatCode, 1)
columnFormatCodes[0] = pgwirebase.FormatText
case 1:
// All columns will use the one specficied format.
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
fmtCode := pgwirebase.FormatCode(ch)
columnFormatCodes = make([]pgwirebase.FormatCode, 1)
columnFormatCodes[0] = fmtCode
default:
columnFormatCodes = make([]pgwirebase.FormatCode, numColumnFormatCodes)
// Read one format code for each column and apply it to that column.
for i := range columnFormatCodes {
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
columnFormatCodes[i] = pgwirebase.FormatCode(ch)
}
}
return c.stmtBuf.Push(
ctx,
sql.BindStmt{
PreparedStatementName: statementName,
PortalName: portalName,
Args: qargs,
ArgFormatCodes: qArgFormatCodes,
OutFormats: columnFormatCodes,
})
}
// An error is returned iff the statement buffer has been closed. In that case,
// the connection should be considered toast.
func (c *conn) handleExecute(
ctx context.Context, buf *pgwirebase.ReadBuffer, timeReceived time.Time,
) error {
portalName, err := buf.GetString()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
limit, err := buf.GetUint32()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
return c.stmtBuf.Push(ctx, sql.ExecPortal{
Name: portalName,
TimeReceived: timeReceived,
Limit: int(limit),
})
}
func (c *conn) handleFlush(ctx context.Context) error {
return c.stmtBuf.Push(ctx, sql.Flush{})
}
// BeginCopyIn is part of the pgwirebase.Conn interface.
func (c *conn) BeginCopyIn(ctx context.Context, columns []sqlbase.ResultColumn) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgCopyInResponse)
c.msgBuilder.writeByte(byte(pgwirebase.FormatText))
c.msgBuilder.putInt16(int16(len(columns)))
for range columns {
c.msgBuilder.putInt16(int16(pgwirebase.FormatText))