-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn.go
1612 lines (1452 loc) · 54 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.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package pgwire
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"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/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/lib/pq/oid"
)
// 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
// res is used to avoid allocations in the conn's ClientComm implementation.
res commandResult
// 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
// alwaysLogAuthActivity is used force-enables logging of authn events.
alwaysLogAuthActivity bool
}
// 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 encounters an error. This error can come from various fatal
// conditions encountered 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 IsDraining
// closure passed to serveImpl. 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 signals 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 (s *Server) serveConn(
ctx context.Context,
netConn net.Conn,
sArgs sql.SessionArgs,
reserved mon.BoundAccount,
authOpt authOptions,
) {
if log.V(2) {
log.Infof(ctx, "new connection with options: %+v", sArgs)
}
c := newConn(netConn, sArgs, &s.metrics, &s.execCfg.Settings.SV)
c.alwaysLogAuthActivity = alwaysLogAuthActivity || atomic.LoadInt32(&s.testingAuthLogEnabled) > 0
// Do the reading of commands from the network.
c.serveImpl(ctx, s.IsDraining, s.SQLServer, reserved, authOpt)
}
// alwaysLogAuthActivity makes it possible to unconditionally enable
// authentication logging when cluster settings do not work reliably,
// e.g. in multi-tenant setups in v20.2. This override mechanism
// can be removed after all of CC is moved to use v21.1 or a version
// which supports cluster settings.
var alwaysLogAuthActivity = envutil.EnvOrDefaultBool("COCKROACH_ALWAYS_LOG_AUTHN_EVENTS", false)
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,
readBuf: pgwirebase.MakeReadBuffer(pgwirebase.ReadBufferOptionWithClusterSettings(sv)),
}
c.stmtBuf.Init()
c.res.released = true
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
}
func (c *conn) authLogEnabled() bool {
return c.alwaysLogAuthActivity || logSessionAuth.Get(c.sv)
}
// 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,
) {
defer func() { _ = c.conn.Close() }()
if c.sessionArgs.User == security.RootUser || c.sessionArgs.User == security.NodeUser {
ctx = logtags.AddTag(ctx, "user", log.Safe(c.sessionArgs.User))
} else {
ctx = logtags.AddTag(ctx, "user", c.sessionArgs.User)
}
inTestWithoutSQL := sqlServer == nil
var authLogger *log.SecondaryLogger
if !inTestWithoutSQL {
authLogger = sqlServer.GetExecutorConfig().AuthLogger
sessionStart := timeutil.Now()
defer func() {
if c.authLogEnabled() {
authLogger.Logf(ctx, "session terminated; duration: %s", timeutil.Now().Sub(sessionStart))
}
}()
}
// 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() 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)
// the authPipe below logs authentication messages iff its auth
// logger is non-nil. We define this here.
var sessionAuthLogger *log.SecondaryLogger
if !inTestWithoutSQL && c.authLogEnabled() {
sessionAuthLogger = authLogger
}
// We'll build an authPipe to communicate with the authentication process.
authPipe := newAuthPipe(c, sessionAuthLogger)
var authenticator authenticatorIO = 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 {
err = c.sendParamStatus(param, value)
if err != nil {
break
}
}
if err != nil {
reserved.Close(ctx)
return
}
var ac AuthConn = authPipe
// Simulate auth succeeding.
ac.AuthOK(fixedIntSizer{size: types.Int})
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 terminateSeen 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: types.Int}
var authDone bool
for {
if breakLoop, err := func() (breakLoop bool, err error) {
var typ pgwirebase.ClientMessageType
var n int
typ, n, err = c.readBuf.ReadTypedMsg(&c.rd)
c.metrics.BytesInCount.Inc(int64(n))
if err != nil {
// Only perform this logic on ClientMsgSimpleQuery for v20.2.
// We cannot safely do the rest of this (i.e. for portals) without doing
// the todo message by jordan regarding error in extended protocol state
// below.
if pgwirebase.IsMessageTooBigError(err) && typ == pgwirebase.ClientMsgSimpleQuery {
log.VInfof(ctx, 1, "pgwire: found big error message; attempting to slurp bytes and return error: %s", err)
// Slurp the remaining bytes.
slurpN, slurpErr := c.readBuf.SlurpBytes(&c.rd, pgwirebase.GetMessageTooBigSize(err))
c.metrics.BytesInCount.Inc(int64(slurpN))
if slurpErr != nil {
return false, errors.Newf("pgwire: error slurping remaining bytes: %s", slurpErr)
}
// Write out the error over pgwire.
if err := writeErr(
ctx,
&sqlServer.GetExecutorConfig().Settings.SV,
err,
&c.msgBuilder,
&c.writerState.buf,
); err != nil {
return false, errors.New("pgwire: error writing too big error message to the client")
}
// We have to send the sync message back as well.
if err = c.stmtBuf.Push(ctx, sql.Sync{}); err != nil {
return false, errors.New("pgwire: error writing sync to the client whilst message is too big")
}
// We need to continue processing here for pgwire clients to be able to
// successfully read the error message off pgwire.
//
// If break here, we terminate the connection. The client will instead see that
// we terminated the connection prematurely (as opposed to seeing a ClientMsgTerminate
// packet) and instead return a broken pipe or io.EOF error message.
return false, nil
}
return false, errors.Newf("pgwire: error reading input: %s", err)
}
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 {
return false, err
}
// 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 {
return false, err
}
return false, nil
}
// Wait for the auth result.
if intSizer, err = authenticator.authResult(); err != nil {
// The error has already been sent to the client.
return true, nil //nolint:returnerrcheck
}
authDone = true
}
// TODO(jordan): there's one big missing piece of implementation here.
// In Postgres, if an error is encountered during extended protocol mode,
// the protocol skips all messages until a Sync is received to "regain
// protocol synchronization". We don't do this. If this becomes a problem,
// we should copy their behavior.
switch typ {
case pgwirebase.ClientMsgPassword:
// This messages are only acceptable during the auth phase, handled above.
err = pgwirebase.NewProtocolViolationErrorf("unexpected authentication data")
return true, writeErr(
ctx, &sqlServer.GetExecutorConfig().Settings.SV, err,
&c.msgBuilder, &c.writerState.buf)
case pgwirebase.ClientMsgSimpleQuery:
if err = c.handleSimpleQuery(
ctx, &c.readBuf, timeReceived, intSizer.GetUnqualifiedIntSize(),
); err != nil {
return false, err
}
return false, c.stmtBuf.Push(ctx, sql.Sync{})
case pgwirebase.ClientMsgExecute:
return false, c.handleExecute(ctx, &c.readBuf, timeReceived)
case pgwirebase.ClientMsgParse:
return false, c.handleParse(ctx, &c.readBuf, intSizer.GetUnqualifiedIntSize())
case pgwirebase.ClientMsgDescribe:
return false, c.handleDescribe(ctx, &c.readBuf)
case pgwirebase.ClientMsgBind:
return false, c.handleBind(ctx, &c.readBuf)
case pgwirebase.ClientMsgClose:
return false, c.handleClose(ctx, &c.readBuf)
case pgwirebase.ClientMsgTerminate:
terminateSeen = true
return true, nil
case pgwirebase.ClientMsgSync:
// 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
return false, c.stmtBuf.Push(ctx, sql.Sync{})
case pgwirebase.ClientMsgFlush:
return false, 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
return false, nil
default:
return false, c.stmtBuf.Push(
ctx,
sql.SendError{Err: pgwirebase.NewUnrecognizedMsgTypeErr(typ)})
}
}(); err != nil {
log.VEventf(ctx, 1, "pgwire: error processing message: %s", err)
break
} else if breakLoop {
break
}
}
// 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() *types.T
}
type fixedIntSizer struct {
size *types.T
}
func (f fixedIntSizer) GetUnqualifiedIntSize() *types.T {
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
var connCloseAuthHandler func()
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.
if err, ok := r.(error); ok {
// Mask the cause but keep the details.
retErr = errors.Handled(err)
} else {
retErr = errors.Newf("%+v", r)
}
retErr = pgerror.WithCandidateCode(retErr, pgcode.CrashShutdown)
// Add a prefix. This also adds a stack trace.
retErr = errors.Wrap(retErr, "caught fatal error")
_ = 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)
}
if connCloseAuthHandler != nil {
connCloseAuthHandler()
}
// Inform the connection goroutine of success or failure.
retCh <- retErr
}()
// Authenticate the connection.
if connCloseAuthHandler, retErr = c.handleAuthentication(
ctx, ac, authOpt, sqlServer.GetExecutorConfig(),
); retErr != nil {
// Auth failed or some other error.
return
}
// Inform the client of the default session settings.
connHandler, retErr = c.sendInitialConnData(ctx, sqlServer)
if retErr != nil {
return
}
// Signal the connection was established to the authenticator.
ac.AuthOK(connHandler)
// Mark the authentication as succeeded in case a panic
// is thrown below and we need to report to the client
// using the defer above.
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) sendParamStatus(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) bufferParamStatus(param, value string) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgParameterStatus)
c.msgBuilder.writeTerminatedString(param)
c.msgBuilder.writeTerminatedString(value)
return c.msgBuilder.finishMsg(&c.writerState.buf)
}
func (c *conn) bufferNotice(ctx context.Context, noticeErr error) error {
c.msgBuilder.initMsg(pgwirebase.ServerMsgNoticeResponse)
return writeErrFields(ctx, c.sv, noticeErr, &c.msgBuilder, &c.writerState.buf)
}
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 {
param := param
value := connHandler.GetParamStatus(ctx, param)
if err := c.sendParamStatus(param, value); err != nil {
return sql.ConnectionHandler{}, err
}
}
// The two following status parameters have no equivalent session
// variable.
if err := c.sendParamStatus("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.sendParamStatus("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 *types.T,
) 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 *types.T,
) error {
telemetry.Inc(sqltelemetry.ParseRequestCounter)
name, err := buf.GetString()
if err != 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.WrongNumberOfPreparedStatements(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
}
// If the OID is user defined, then write nil into the type hints and let
// the consumer of the PrepareStmt resolve the types.
if types.IsOIDUserDefinedType(t) {
sqlTypeHints[i] = nil
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 {
telemetry.Inc(sqltelemetry.DescribeRequestCounter)
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 {
telemetry.Inc(sqltelemetry.CloseRequestCounter)
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,
})
}
// If no format codes are provided then all arguments/result-columns use
// the default format, text.
var formatCodesAllText = []pgwirebase.FormatCode{pgwirebase.FormatText}
// 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 {
telemetry.Inc(sqltelemetry.BindRequestCounter)
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})
}
var qArgFormatCodes []pgwirebase.FormatCode
switch numQArgFormatCodes {
case 0:
// No format codes means all arguments are passed as text.
qArgFormatCodes = formatCodesAllText
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})
}
code := pgwirebase.FormatCode(ch)
if code == pgwirebase.FormatText {
qArgFormatCodes = formatCodesAllText
} else {
qArgFormatCodes = []pgwirebase.FormatCode{code}
}
default:
qArgFormatCodes = make([]pgwirebase.FormatCode, numQArgFormatCodes)
// Read one format code for each argument and apply it to that argument.
for i := range qArgFormatCodes {
ch, err := buf.GetUint16()
if err != nil {
return c.stmtBuf.Push(ctx, sql.SendError{Err: err})
}
qArgFormatCodes[i] = pgwirebase.FormatCode(ch)
}
}
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()