Debian Codegraph @

tools/remotecommand/websocket.go

raw symbols SCIP
1 /*
2 Copyright 2023 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package remotecommand
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "io"
24 "net"
25 "net/http"
26 "sync"
27 "time"
28
29 gwebsocket "github.com/gorilla/websocket"
30
31 v1 "k8s.io/api/core/v1"
32 "k8s.io/apimachinery/pkg/util/httpstream"
33 "k8s.io/apimachinery/pkg/util/remotecommand"
34 restclient "k8s.io/client-go/rest"
35 "k8s.io/client-go/transport/websocket"
36 "k8s.io/klog/v2"
37 )
38
39 // writeDeadline defines the time that a client-side write to the websocket
40 // connection must complete before an i/o timeout occurs.
41 const writeDeadline = 60 * time.Second
42
43 var (
44 _ Executor = &wsStreamExecutor{}
45 _ streamCreator = &wsStreamCreator{}
46 _ httpstream.Stream = &stream{}
47
48 streamType2streamID = map[string]byte{
49 v1.StreamTypeStdin: remotecommand.StreamStdIn,
50 v1.StreamTypeStdout: remotecommand.StreamStdOut,
51 v1.StreamTypeStderr: remotecommand.StreamStdErr,
52 v1.StreamTypeError: remotecommand.StreamErr,
53 v1.StreamTypeResize: remotecommand.StreamResize,
54 }
55 )
56
57 const (
58 // pingPeriod defines how often a heartbeat "ping" message is sent.
59 pingPeriod = 5 * time.Second
60 // pingReadDeadline defines the time waiting for a response heartbeat
61 // "pong" message before a timeout error occurs for websocket reading.
62 // This duration must always be greater than the "pingPeriod". By defining
63 // this deadline in terms of the ping period, we are essentially saying
64 // we can drop "X" (e.g. 12) pings before firing the timeout.
65 pingReadDeadline = (pingPeriod * 12) + (1 * time.Second)
66 )
67
68 // wsStreamExecutor handles transporting standard shell streams over an httpstream connection.
69 type wsStreamExecutor struct {
70 transport http.RoundTripper
71 upgrader websocket.ConnectionHolder
72 method string
73 url string
74 // requested protocols in priority order (e.g. v5.channel.k8s.io before v4.channel.k8s.io).
75 protocols []string
76 // selected protocol from the handshake process; could be empty string if handshake fails.
77 negotiated string
78 // period defines how often a "ping" heartbeat message is sent to the other endpoint.
79 heartbeatPeriod time.Duration
80 // deadline defines the amount of time before "pong" response must be received.
81 heartbeatDeadline time.Duration
82 }
83
84 func NewWebSocketExecutor(config *restclient.Config, method, url string) (Executor, error) {
85 // Only supports V5 protocol for correct version skew functionality.
86 // Previous api servers will proxy upgrade requests to legacy websocket
87 // servers on container runtimes which support V1-V4. These legacy
88 // websocket servers will not handle the new CLOSE signal.
89 return NewWebSocketExecutorForProtocols(config, method, url, remotecommand.StreamProtocolV5Name)
90 }
91
92 // NewWebSocketExecutorForProtocols allows to execute commands via a WebSocket connection.
93 func NewWebSocketExecutorForProtocols(config *restclient.Config, method, url string, protocols ...string) (Executor, error) {
94 transport, upgrader, err := websocket.RoundTripperFor(config)
95 if err != nil {
96 return nil, fmt.Errorf("error creating websocket transports: %v", err)
97 }
98 return &wsStreamExecutor{
99 transport: transport,
100 upgrader: upgrader,
101 method: method,
102 url: url,
103 protocols: protocols,
104 heartbeatPeriod: pingPeriod,
105 heartbeatDeadline: pingReadDeadline,
106 }, nil
107 }
108
109 // Deprecated: use StreamWithContext instead to avoid possible resource leaks.
110 // See https://github.com/kubernetes/kubernetes/pull/103177 for details.
111 func (e *wsStreamExecutor) Stream(options StreamOptions) error {
112 return e.StreamWithContext(context.Background(), options)
113 }
114
115 // StreamWithContext upgrades an HTTPRequest to a WebSocket connection, and starts the various
116 // goroutines to implement the necessary streams over the connection. The "options" parameter
117 // defines which streams are requested. Returns an error if one occurred. This method is NOT
118 // safe to run concurrently with the same executor (because of the state stored in the upgrader).
119 func (e *wsStreamExecutor) StreamWithContext(ctx context.Context, options StreamOptions) error {
120 req, err := http.NewRequestWithContext(ctx, e.method, e.url, nil)
121 if err != nil {
122 return err
123 }
124 conn, err := websocket.Negotiate(e.transport, e.upgrader, req, e.protocols...)
125 if err != nil {
126 return err
127 }
128 if conn == nil {
129 panic(fmt.Errorf("websocket connection is nil"))
130 }
131 defer conn.Close()
132 e.negotiated = conn.Subprotocol()
133 klog.V(4).Infof("The subprotocol is %s", e.negotiated)
134
135 var streamer streamProtocolHandler
136 switch e.negotiated {
137 case remotecommand.StreamProtocolV5Name:
138 streamer = newStreamProtocolV5(options)
139 case remotecommand.StreamProtocolV4Name:
140 streamer = newStreamProtocolV4(options)
141 case remotecommand.StreamProtocolV3Name:
142 streamer = newStreamProtocolV3(options)
143 case remotecommand.StreamProtocolV2Name:
144 streamer = newStreamProtocolV2(options)
145 case "":
146 klog.V(4).Infof("The server did not negotiate a streaming protocol version. Falling back to %s", remotecommand.StreamProtocolV1Name)
147 fallthrough
148 case remotecommand.StreamProtocolV1Name:
149 streamer = newStreamProtocolV1(options)
150 }
151
152 panicChan := make(chan any, 1)
153 errorChan := make(chan error, 1)
154 go func() {
155 defer func() {
156 if p := recover(); p != nil {
157 panicChan <- p
158 }
159 }()
160 creator := newWSStreamCreator(conn)
161 go creator.readDemuxLoop(
162 e.upgrader.DataBufferSize(),
163 e.heartbeatPeriod,
164 e.heartbeatDeadline,
165 )
166 errorChan <- streamer.stream(creator)
167 }()
168
169 select {
170 case p := <-panicChan:
171 panic(p)
172 case err := <-errorChan:
173 return err
174 case <-ctx.Done():
175 return ctx.Err()
176 }
177 }
178
179 type wsStreamCreator struct {
180 conn *gwebsocket.Conn
181 // Protects writing to websocket connection; reading is lock-free
182 connWriteLock sync.Mutex
183 // map of stream id to stream; multiple streams read/write the connection
184 streams map[byte]*stream
185 streamsMu sync.Mutex
186 // setStreamErr holds the error to return to anyone calling setStreams.
187 // this is populated in closeAllStreamReaders
188 setStreamErr error
189 }
190
191 func newWSStreamCreator(conn *gwebsocket.Conn) *wsStreamCreator {
192 return &wsStreamCreator{
193 conn: conn,
194 streams: map[byte]*stream{},
195 }
196 }
197
198 func (c *wsStreamCreator) getStream(id byte) *stream {
199 c.streamsMu.Lock()
200 defer c.streamsMu.Unlock()
201 return c.streams[id]
202 }
203
204 func (c *wsStreamCreator) setStream(id byte, s *stream) error {
205 c.streamsMu.Lock()
206 defer c.streamsMu.Unlock()
207 if c.setStreamErr != nil {
208 return c.setStreamErr
209 }
210 c.streams[id] = s
211 return nil
212 }
213
214 // CreateStream uses id from passed headers to create a stream over "c.conn" connection.
215 // Returns a Stream structure or nil and an error if one occurred.
216 func (c *wsStreamCreator) CreateStream(headers http.Header) (httpstream.Stream, error) {
217 streamType := headers.Get(v1.StreamType)
218 id, ok := streamType2streamID[streamType]
219 if !ok {
220 return nil, fmt.Errorf("unknown stream type: %s", streamType)
221 }
222 if s := c.getStream(id); s != nil {
223 return nil, fmt.Errorf("duplicate stream for type %s", streamType)
224 }
225 reader, writer := io.Pipe()
226 s := &stream{
227 headers: headers,
228 readPipe: reader,
229 writePipe: writer,
230 conn: c.conn,
231 connWriteLock: &c.connWriteLock,
232 id: id,
233 }
234 if err := c.setStream(id, s); err != nil {
235 _ = s.writePipe.Close()
236 _ = s.readPipe.Close()
237 return nil, err
238 }
239 return s, nil
240 }
241
242 // readDemuxLoop is the lock-free reading processor for this endpoint of the websocket
243 // connection. This loop reads the connection, and demultiplexes the data
244 // into one of the individual stream pipes (by checking the stream id). This
245 // loop can *not* be run concurrently, because there can only be one websocket
246 // connection reader at a time (a read mutex would provide no benefit).
247 func (c *wsStreamCreator) readDemuxLoop(bufferSize int, period time.Duration, deadline time.Duration) {
248 // Initialize and start the ping/pong heartbeat.
249 h := newHeartbeat(c.conn, period, deadline)
250 // Set initial timeout for websocket connection reading.
251 klog.V(5).Infof("Websocket initial read deadline: %s", deadline)
252 if err := c.conn.SetReadDeadline(time.Now().Add(deadline)); err != nil {
253 klog.Errorf("Websocket initial setting read deadline failed %v", err)
254 return
255 }
256 go h.start()
257 // Buffer size must correspond to the same size allocated
258 // for the read buffer during websocket client creation. A
259 // difference can cause incomplete connection reads.
260 readBuffer := make([]byte, bufferSize)
261 for {
262 // NextReader() only returns data messages (BinaryMessage or Text
263 // Message). Even though this call will never return control frames
264 // such as ping, pong, or close, this call is necessary for these
265 // message types to be processed. There can only be one reader
266 // at a time, so this reader loop must *not* be run concurrently;
267 // there is no lock for reading. Calling "NextReader()" before the
268 // current reader has been processed will close the current reader.
269 // If the heartbeat read deadline times out, this "NextReader()" will
270 // return an i/o error, and error handling will clean up.
271 messageType, r, err := c.conn.NextReader()
272 if err != nil {
273 websocketErr, ok := err.(*gwebsocket.CloseError)
274 if ok && websocketErr.Code == gwebsocket.CloseNormalClosure {
275 err = nil // readers will get io.EOF as it's a normal closure
276 } else {
277 err = fmt.Errorf("next reader: %w", err)
278 }
279 c.closeAllStreamReaders(err)
280 return
281 }
282 // All remote command protocols send/receive only binary data messages.
283 if messageType != gwebsocket.BinaryMessage {
284 c.closeAllStreamReaders(fmt.Errorf("unexpected message type: %d", messageType))
285 return
286 }
287 // It's ok to read just a single byte because the underlying library wraps the actual
288 // connection with a buffered reader anyway.
289 _, err = io.ReadFull(r, readBuffer[:1])
290 if err != nil {
291 c.closeAllStreamReaders(fmt.Errorf("read stream id: %w", err))
292 return
293 }
294 streamID := readBuffer[0]
295 s := c.getStream(streamID)
296 if s == nil {
297 klog.Errorf("Unknown stream id %d, discarding message", streamID)
298 continue
299 }
300 for {
301 nr, errRead := r.Read(readBuffer)
302 if nr > 0 {
303 // Write the data to the stream's pipe. This can block.
304 _, errWrite := s.writePipe.Write(readBuffer[:nr])
305 if errWrite != nil {
306 // Pipe must have been closed by the stream user.
307 // Nothing to do, discard the message.
308 break
309 }
310 }
311 if errRead != nil {
312 if errRead == io.EOF {
313 break
314 }
315 c.closeAllStreamReaders(fmt.Errorf("read message: %w", errRead))
316 return
317 }
318 }
319 }
320 }
321
322 // closeAllStreamReaders closes readers in all streams.
323 // This unblocks all stream.Read() calls, and keeps any future streams from being created.
324 func (c *wsStreamCreator) closeAllStreamReaders(err error) {
325 c.streamsMu.Lock()
326 defer c.streamsMu.Unlock()
327 for _, s := range c.streams {
328 // Closing writePipe unblocks all readPipe.Read() callers and prevents any future writes.
329 _ = s.writePipe.CloseWithError(err)
330 }
331 // ensure callers to setStreams receive an error after this point
332 if err != nil {
333 c.setStreamErr = err
334 } else {
335 c.setStreamErr = fmt.Errorf("closed all streams")
336 }
337 }
338
339 type stream struct {
340 headers http.Header
341 readPipe *io.PipeReader
342 writePipe *io.PipeWriter
343 // conn is used for writing directly into the connection.
344 // Is nil after Close() / Reset() to prevent future writes.
345 conn *gwebsocket.Conn
346 // connWriteLock protects conn against concurrent write operations. There must be a single writer and a single reader only.
347 // The mutex is shared across all streams because the underlying connection is shared.
348 connWriteLock *sync.Mutex
349 id byte
350 }
351
352 func (s *stream) Read(p []byte) (n int, err error) {
353 return s.readPipe.Read(p)
354 }
355
356 // Write writes directly to the underlying WebSocket connection.
357 func (s *stream) Write(p []byte) (n int, err error) {
358 klog.V(8).Infof("Write() on stream %d", s.id)
359 defer klog.V(8).Infof("Write() done on stream %d", s.id)
360 s.connWriteLock.Lock()
361 defer s.connWriteLock.Unlock()
362 if s.conn == nil {
363 return 0, fmt.Errorf("write on closed stream %d", s.id)
364 }
365 err = s.conn.SetWriteDeadline(time.Now().Add(writeDeadline))
366 if err != nil {
367 klog.V(4).Infof("Websocket setting write deadline failed %v", err)
368 return 0, err
369 }
370 // Message writer buffers the message data, so we don't need to do that ourselves.
371 // Just write id and the data as two separate writes to avoid allocating an intermediate buffer.
372 w, err := s.conn.NextWriter(gwebsocket.BinaryMessage)
373 if err != nil {
374 return 0, err
375 }
376 defer func() {
377 if w != nil {
378 w.Close()
379 }
380 }()
381 _, err = w.Write([]byte{s.id})
382 if err != nil {
383 return 0, err
384 }
385 n, err = w.Write(p)
386 if err != nil {
387 return n, err
388 }
389 err = w.Close()
390 w = nil
391 return n, err
392 }
393
394 // Close half-closes the stream, indicating this side is finished with the stream.
395 func (s *stream) Close() error {
396 klog.V(6).Infof("Close() on stream %d", s.id)
397 defer klog.V(6).Infof("Close() done on stream %d", s.id)
398 s.connWriteLock.Lock()
399 defer s.connWriteLock.Unlock()
400 if s.conn == nil {
401 return fmt.Errorf("Close() on already closed stream %d", s.id)
402 }
403 // Communicate the CLOSE stream signal to the other websocket endpoint.
404 err := s.conn.WriteMessage(gwebsocket.BinaryMessage, []byte{remotecommand.StreamClose, s.id})
405 s.conn = nil
406 return err
407 }
408
409 func (s *stream) Reset() error {
410 klog.V(4).Infof("Reset() on stream %d", s.id)
411 defer klog.V(4).Infof("Reset() done on stream %d", s.id)
412 s.Close()
413 return s.writePipe.Close()
414 }
415
416 func (s *stream) Headers() http.Header {
417 return s.headers
418 }
419
420 func (s *stream) Identifier() uint32 {
421 return uint32(s.id)
422 }
423
424 // heartbeat encasulates data necessary for the websocket ping/pong heartbeat. This
425 // heartbeat works by setting a read deadline on the websocket connection, then
426 // pushing this deadline into the future for every successful heartbeat. If the
427 // heartbeat "pong" fails to respond within the deadline, then the "NextReader()" call
428 // inside the "readDemuxLoop" will return an i/o error prompting a connection close
429 // and cleanup.
430 type heartbeat struct {
431 conn *gwebsocket.Conn
432 // period defines how often a "ping" heartbeat message is sent to the other endpoint
433 period time.Duration
434 // closing the "closer" channel will clean up the heartbeat timers
435 closer chan struct{}
436 // optional data to send with "ping" message
437 message []byte
438 // optionally received data message with "pong" message, same as sent with ping
439 pongMessage []byte
440 }
441
442 // newHeartbeat creates heartbeat structure encapsulating fields necessary to
443 // run the websocket connection ping/pong mechanism and sets up handlers on
444 // the websocket connection.
445 func newHeartbeat(conn *gwebsocket.Conn, period time.Duration, deadline time.Duration) *heartbeat {
446 h := &heartbeat{
447 conn: conn,
448 period: period,
449 closer: make(chan struct{}),
450 }
451 // Set up handler for receiving returned "pong" message from other endpoint
452 // by pushing the read deadline into the future. The "msg" received could
453 // be empty.
454 h.conn.SetPongHandler(func(msg string) error {
455 // Push the read deadline into the future.
456 klog.V(6).Infof("Pong message received (%s)--resetting read deadline", msg)
457 err := h.conn.SetReadDeadline(time.Now().Add(deadline))
458 if err != nil {
459 klog.Errorf("Websocket setting read deadline failed %v", err)
460 return err
461 }
462 if len(msg) > 0 {
463 h.pongMessage = []byte(msg)
464 }
465 return nil
466 })
467 // Set up handler to cleanup timers when this endpoint receives "Close" message.
468 closeHandler := h.conn.CloseHandler()
469 h.conn.SetCloseHandler(func(code int, text string) error {
470 close(h.closer)
471 return closeHandler(code, text)
472 })
473 return h
474 }
475
476 // setMessage is optional data sent with "ping" heartbeat. According to the websocket RFC
477 // this data sent with "ping" message should be returned in "pong" message.
478 func (h *heartbeat) setMessage(msg string) {
479 h.message = []byte(msg)
480 }
481
482 // start the heartbeat by setting up necesssary handlers and looping by sending "ping"
483 // message every "period" until the "closer" channel is closed.
484 func (h *heartbeat) start() {
485 // Loop to continually send "ping" message through websocket connection every "period".
486 t := time.NewTicker(h.period)
487 defer t.Stop()
488 for {
489 select {
490 case <-h.closer:
491 klog.V(5).Infof("closed channel--returning")
492 return
493 case <-t.C:
494 // "WriteControl" does not need to be protected by a mutex. According to
495 // gorilla/websockets library docs: "The Close and WriteControl methods can
496 // be called concurrently with all other methods."
497 if err := h.conn.WriteControl(gwebsocket.PingMessage, h.message, time.Now().Add(pingReadDeadline)); err == nil {
498 klog.V(6).Infof("Websocket Ping succeeeded")
499 } else {
500 klog.Errorf("Websocket Ping failed: %v", err)
501 if errors.Is(err, gwebsocket.ErrCloseSent) {
502 // we continue because c.conn.CloseChan will manage closing the connection already
503 continue
504 } else if e, ok := err.(net.Error); ok && e.Timeout() {
505 // Continue, in case this is a transient failure.
506 // c.conn.CloseChan above will tell us when the connection is
507 // actually closed.
508 // If Temporary function hadn't been deprecated, we would have used it.
509 // But most of temporary errors are timeout errors anyway.
510 continue
511 }
512 return
513 }
514 }
515 }
516 }