Debian Codegraph @

transport/websocket/roundtripper.go

raw
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 websocket
18
19 import (
20 "crypto/tls"
21 "errors"
22 "fmt"
23 "io"
24 "net/http"
25 "net/url"
26 "strings"
27
28 gwebsocket "github.com/gorilla/websocket"
29
30 apierrors "k8s.io/apimachinery/pkg/api/errors"
31 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32 "k8s.io/apimachinery/pkg/runtime"
33 "k8s.io/apimachinery/pkg/runtime/serializer"
34 "k8s.io/apimachinery/pkg/util/httpstream"
35 "k8s.io/apimachinery/pkg/util/httpstream/wsstream"
36 utilnet "k8s.io/apimachinery/pkg/util/net"
37 restclient "k8s.io/client-go/rest"
38 "k8s.io/client-go/transport"
39 )
40
41 var (
42 _ utilnet.TLSClientConfigHolder = &RoundTripper{}
43 _ http.RoundTripper = &RoundTripper{}
44 )
45
46 var (
47 statusScheme = runtime.NewScheme()
48 statusCodecs = serializer.NewCodecFactory(statusScheme)
49 )
50
51 func init() {
52 statusScheme.AddUnversionedTypes(metav1.SchemeGroupVersion,
53 &metav1.Status{},
54 )
55 }
56
57 // ConnectionHolder defines functions for structure providing
58 // access to the websocket connection.
59 type ConnectionHolder interface {
60 DataBufferSize() int
61 Connection() *gwebsocket.Conn
62 }
63
64 // RoundTripper knows how to establish a connection to a remote WebSocket endpoint and make it available for use.
65 // RoundTripper must not be reused.
66 type RoundTripper struct {
67 // TLSConfig holds the TLS configuration settings to use when connecting
68 // to the remote server.
69 TLSConfig *tls.Config
70
71 // Proxier specifies a function to return a proxy for a given
72 // Request. If the function returns a non-nil error, the
73 // request is aborted with the provided error.
74 // If Proxy is nil or returns a nil *URL, no proxy is used.
75 Proxier func(req *http.Request) (*url.URL, error)
76
77 // Conn holds the WebSocket connection after a round trip.
78 Conn *gwebsocket.Conn
79 }
80
81 // Connection returns the stored websocket connection.
82 func (rt *RoundTripper) Connection() *gwebsocket.Conn {
83 return rt.Conn
84 }
85
86 // DataBufferSize returns the size of buffers for the
87 // websocket connection.
88 func (rt *RoundTripper) DataBufferSize() int {
89 return 32 * 1024
90 }
91
92 // TLSClientConfig implements pkg/util/net.TLSClientConfigHolder.
93 func (rt *RoundTripper) TLSClientConfig() *tls.Config {
94 return rt.TLSConfig
95 }
96
97 // RoundTrip connects to the remote websocket using the headers in the request and the TLS
98 // configuration from the config
99 func (rt *RoundTripper) RoundTrip(request *http.Request) (retResp *http.Response, retErr error) {
100 defer func() {
101 if request.Body != nil {
102 err := request.Body.Close()
103 if retErr == nil {
104 retErr = err
105 }
106 }
107 }()
108
109 // set the protocol version directly on the dialer from the header
110 protocolVersions := request.Header[wsstream.WebSocketProtocolHeader]
111 delete(request.Header, wsstream.WebSocketProtocolHeader)
112
113 dialer := gwebsocket.Dialer{
114 Proxy: rt.Proxier,
115 TLSClientConfig: rt.TLSConfig,
116 Subprotocols: protocolVersions,
117 ReadBufferSize: rt.DataBufferSize() + 1024, // add space for the protocol byte indicating which channel the data is for
118 WriteBufferSize: rt.DataBufferSize() + 1024, // add space for the protocol byte indicating which channel the data is for
119 }
120 switch request.URL.Scheme {
121 case "https":
122 request.URL.Scheme = "wss"
123 case "http":
124 request.URL.Scheme = "ws"
125 default:
126 return nil, fmt.Errorf("unknown url scheme: %s", request.URL.Scheme)
127 }
128 wsConn, resp, err := dialer.DialContext(request.Context(), request.URL.String(), request.Header)
129 if err != nil {
130 // BadHandshake error becomes an "UpgradeFailureError" (used for streaming fallback).
131 if errors.Is(err, gwebsocket.ErrBadHandshake) {
132 cause := err
133 // Enhance the error message with the error response if possible.
134 if resp != nil && len(resp.Status) > 0 {
135 defer resp.Body.Close() //nolint:errcheck
136 cause = fmt.Errorf("%w (%s)", err, resp.Status) // Always add the response status
137 responseError := ""
138 responseErrorBytes, readErr := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
139 if readErr != nil {
140 cause = fmt.Errorf("%w: unable to read error from server response", cause)
141 } else {
142 // If returned error can be decoded as "metav1.Status", return a "StatusError".
143 responseError = strings.TrimSpace(string(responseErrorBytes))
144 if len(responseError) > 0 {
145 if obj, _, decodeErr := statusCodecs.UniversalDecoder().Decode(responseErrorBytes, nil, &metav1.Status{}); decodeErr == nil {
146 if status, ok := obj.(*metav1.Status); ok {
147 cause = &apierrors.StatusError{ErrStatus: *status}
148 }
149 } else {
150 // Otherwise, append the responseError string.
151 cause = fmt.Errorf("%w: %s", cause, responseError)
152 }
153 }
154 }
155 }
156 return nil, &httpstream.UpgradeFailureError{Cause: cause}
157 }
158 return nil, err
159 }
160
161 // Ensure we got back a protocol we understand
162 foundProtocol := false
163 for _, protocolVersion := range protocolVersions {
164 if protocolVersion == wsConn.Subprotocol() {
165 foundProtocol = true
166 break
167 }
168 }
169 if !foundProtocol {
170 wsConn.Close() // nolint:errcheck
171 return nil, &httpstream.UpgradeFailureError{Cause: fmt.Errorf("invalid protocol, expected one of %q, got %q", protocolVersions, wsConn.Subprotocol())}
172 }
173
174 rt.Conn = wsConn
175
176 return resp, nil
177 }
178
179 // RoundTripperFor transforms the passed rest config into a wrapped roundtripper, as well
180 // as a pointer to the websocket RoundTripper. The websocket RoundTripper contains the
181 // websocket connection after RoundTrip() on the wrapper. Returns an error if there is
182 // a problem creating the round trippers.
183 func RoundTripperFor(config *restclient.Config) (http.RoundTripper, ConnectionHolder, error) {
184 transportCfg, err := config.TransportConfig()
185 if err != nil {
186 return nil, nil, err
187 }
188 tlsConfig, err := transport.TLSConfigFor(transportCfg)
189 if err != nil {
190 return nil, nil, err
191 }
192 proxy := config.Proxy
193 if proxy == nil {
194 proxy = utilnet.NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment)
195 }
196
197 upgradeRoundTripper := &RoundTripper{
198 TLSConfig: tlsConfig,
199 Proxier: proxy,
200 }
201 wrapper, err := transport.HTTPWrappersForConfig(transportCfg, upgradeRoundTripper)
202 if err != nil {
203 return nil, nil, err
204 }
205 return wrapper, upgradeRoundTripper, nil
206 }
207
208 // Negotiate opens a connection to a remote server and attempts to negotiate
209 // a WebSocket connection. Upon success, it returns the negotiated connection.
210 // The round tripper rt must use the WebSocket round tripper wsRt - see RoundTripperFor.
211 func Negotiate(rt http.RoundTripper, connectionInfo ConnectionHolder, req *http.Request, protocols ...string) (*gwebsocket.Conn, error) {
212 // Plumb protocols to RoundTripper#RoundTrip
213 req.Header[wsstream.WebSocketProtocolHeader] = protocols
214 resp, err := rt.RoundTrip(req)
215 if err != nil {
216 return nil, err
217 }
218 err = resp.Body.Close()
219 if err != nil {
220 connectionInfo.Connection().Close()
221 return nil, fmt.Errorf("error closing response body: %v", err)
222 }
223 return connectionInfo.Connection(), nil
224 }