| 1 | /* |
| 2 | Copyright 2019 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 main |
| 18 | |
| 19 | import ( |
| 20 | "bufio" |
| 21 | "context" |
| 22 | "crypto/tls" |
| 23 | "flag" |
| 24 | "fmt" |
| 25 | "io" |
| 26 | "net" |
| 27 | "net/http" |
| 28 | "net/url" |
| 29 | "os" |
| 30 | "os/signal" |
| 31 | runpprof "runtime/pprof" |
| 32 | "strconv" |
| 33 | "sync" |
| 34 | "time" |
| 35 | |
| 36 | "github.com/spf13/cobra" |
| 37 | "github.com/spf13/pflag" |
| 38 | "golang.org/x/net/http2" |
| 39 | "google.golang.org/grpc" |
| 40 | "google.golang.org/grpc/credentials" |
| 41 | "k8s.io/klog/v2" |
| 42 | |
| 43 | "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client" |
| 44 | "sigs.k8s.io/apiserver-network-proxy/pkg/util" |
| 45 | ) |
| 46 | |
| 47 | func main() { |
| 48 | client := &Client{} |
| 49 | o := newGrpcProxyClientOptions() |
| 50 | command := newGrpcProxyClientCommand(client, o) |
| 51 | flags := command.Flags() |
| 52 | flags.AddFlagSet(o.Flags()) |
| 53 | local := flag.NewFlagSet(os.Args[0], flag.ExitOnError) |
| 54 | klog.InitFlags(local) |
| 55 | err := local.Set("v", "4") |
| 56 | if err != nil { |
| 57 | fmt.Fprintf(os.Stderr, "error setting klog flags: %v", err) |
| 58 | } |
| 59 | local.VisitAll(func(fl *flag.Flag) { |
| 60 | fl.Name = util.Normalize(fl.Name) |
| 61 | flags.AddGoFlag(fl) |
| 62 | }) |
| 63 | if err := command.Execute(); err != nil { |
| 64 | klog.Errorf("error: %v\n", err) |
| 65 | klog.Flush() |
| 66 | os.Exit(1) |
| 67 | } |
| 68 | klog.Flush() |
| 69 | } |
| 70 | |
| 71 | type GrpcProxyClientOptions struct { |
| 72 | clientCert string |
| 73 | clientKey string |
| 74 | caCert string |
| 75 | requestProto string |
| 76 | requestPath string |
| 77 | requestHost string |
| 78 | requestPort int |
| 79 | proxyHost string |
| 80 | proxyPort int |
| 81 | proxyUdsName string |
| 82 | mode string |
| 83 | userAgent string |
| 84 | testRequests int |
| 85 | testDelaySec int |
| 86 | afterDelaySec int |
| 87 | closeIdleConn bool |
| 88 | enableHTTP2HealthChecks bool |
| 89 | } |
| 90 | |
| 91 | func (o *GrpcProxyClientOptions) Flags() *pflag.FlagSet { |
| 92 | flags := pflag.NewFlagSet("proxy", pflag.ContinueOnError) |
| 93 | flags.StringVar(&o.clientCert, "client-cert", o.clientCert, "If non-empty secure communication with this cert.") |
| 94 | flags.StringVar(&o.clientKey, "client-key", o.clientKey, "If non-empty secure communication with this key.") |
| 95 | flags.StringVar(&o.caCert, "ca-cert", o.caCert, "If non-empty the CAs we use to validate clients.") |
| 96 | flags.StringVar(&o.requestProto, "request-proto", o.requestProto, "The protocol for the request to send through the proxy.") |
| 97 | flags.StringVar(&o.requestPath, "request-path", o.requestPath, "The url request to send through the proxy.") |
| 98 | flags.StringVar(&o.requestHost, "request-host", o.requestHost, "The host of the request server.") |
| 99 | flags.IntVar(&o.requestPort, "request-port", o.requestPort, "The port the request server is listening on.") |
| 100 | flags.StringVar(&o.proxyHost, "proxy-host", o.proxyHost, "The host of the proxy server.") |
| 101 | flags.IntVar(&o.proxyPort, "proxy-port", o.proxyPort, "The port the proxy server is listening on.") |
| 102 | flags.StringVar(&o.proxyUdsName, "proxy-uds", o.proxyUdsName, "The UDS name to connect to.") |
| 103 | flags.StringVar(&o.mode, "mode", o.mode, "Mode can be either 'grpc' or 'http-connect'.") |
| 104 | flags.StringVar(&o.userAgent, "user-agent", o.userAgent, "User agent to pass to the proxy server") |
| 105 | flags.IntVar(&o.testRequests, "test-requests", o.testRequests, "The number of times to send the request.") |
| 106 | flags.IntVar(&o.testDelaySec, "test-delay", o.testDelaySec, "The delay in seconds between sending requests.") |
| 107 | flags.IntVar(&o.afterDelaySec, "after-delay", o.afterDelaySec, "The delay in seconds after sending requests.") |
| 108 | flags.BoolVar(&o.closeIdleConn, "close-idle-conn", o.closeIdleConn, "Controls if the client calls closeIdleConnections.") |
| 109 | flags.BoolVar(&o.enableHTTP2HealthChecks, "enable-http2-healthchecks", o.enableHTTP2HealthChecks, "enables health checks on http2 connections made by the client.") |
| 110 | |
| 111 | return flags |
| 112 | } |
| 113 | |
| 114 | func (o *GrpcProxyClientOptions) Print() { |
| 115 | klog.V(1).Infof("ClientCert set to %q.\n", o.clientCert) |
| 116 | klog.V(1).Infof("ClientKey set to %q.\n", o.clientKey) |
| 117 | klog.V(1).Infof("CACert set to %q.\n", o.caCert) |
| 118 | klog.V(1).Infof("RequestProto set to %q.\n", o.requestProto) |
| 119 | klog.V(1).Infof("RequestPath set to %q.\n", o.requestPath) |
| 120 | klog.V(1).Infof("RequestHost set to %q.\n", o.requestHost) |
| 121 | klog.V(1).Infof("RequestPort set to %d.\n", o.requestPort) |
| 122 | klog.V(1).Infof("ProxyHost set to %q.\n", o.proxyHost) |
| 123 | klog.V(1).Infof("ProxyPort set to %d.\n", o.proxyPort) |
| 124 | klog.V(1).Infof("ProxyUdsName set to %q.\n", o.proxyUdsName) |
| 125 | klog.V(1).Infof("TestRequests set to %q.\n", o.testRequests) |
| 126 | klog.V(1).Infof("TestDelaySec set to %d.\n", o.testDelaySec) |
| 127 | klog.V(1).Infof("AfterDelaySec set to %d.\n", o.afterDelaySec) |
| 128 | klog.V(1).Infof("CloseIdleConn set to %t.\n", o.closeIdleConn) |
| 129 | } |
| 130 | |
| 131 | func (o *GrpcProxyClientOptions) Validate() error { |
| 132 | if o.clientKey != "" { |
| 133 | if _, err := os.Stat(o.clientKey); os.IsNotExist(err) { |
| 134 | return err |
| 135 | } |
| 136 | if o.clientCert == "" { |
| 137 | return fmt.Errorf("cannot have client cert empty when client key is set to %q", o.clientKey) |
| 138 | } |
| 139 | } |
| 140 | if o.clientCert != "" { |
| 141 | if _, err := os.Stat(o.clientCert); os.IsNotExist(err) { |
| 142 | return err |
| 143 | } |
| 144 | if o.clientKey == "" { |
| 145 | return fmt.Errorf("cannot have client key empty when client cert is set to %q", o.clientCert) |
| 146 | } |
| 147 | } |
| 148 | if o.caCert != "" { |
| 149 | if _, err := os.Stat(o.caCert); os.IsNotExist(err) { |
| 150 | return err |
| 151 | } |
| 152 | } |
| 153 | if o.requestProto != "http" && o.requestProto != "https" { |
| 154 | return fmt.Errorf("request protocol must be set to either 'http' or 'https' not %q", o.requestProto) |
| 155 | } |
| 156 | if o.mode != "grpc" && o.mode != "http-connect" { |
| 157 | return fmt.Errorf("mode must be set to either 'grpc' or 'http-connect' not %q", o.mode) |
| 158 | } |
| 159 | if o.requestPort > 49151 { |
| 160 | return fmt.Errorf("please do not try to use ephemeral port %d for the request server port", o.requestPort) |
| 161 | } |
| 162 | if o.proxyPort > 49151 { |
| 163 | return fmt.Errorf("please do not try to use ephemeral port %d for the proxy server port", o.proxyPort) |
| 164 | } |
| 165 | if o.proxyPort < 1024 && o.proxyUdsName == "" { |
| 166 | return fmt.Errorf("please do not try to use reserved port %d for the proxy server port", o.proxyPort) |
| 167 | } |
| 168 | if o.proxyUdsName != "" { |
| 169 | if o.proxyHost != "" { |
| 170 | return fmt.Errorf("please set proxy host to \"\" when using UDS") |
| 171 | } |
| 172 | if o.proxyPort != 0 { |
| 173 | return fmt.Errorf("please set proxy server port to 0 when using UDS") |
| 174 | } |
| 175 | if o.clientKey != "" || o.clientCert != "" || o.caCert != "" { |
| 176 | return fmt.Errorf("please do not set cert materials when using UDS, key = %s, cert = %s, CA = %s", |
| 177 | o.clientKey, o.clientCert, o.caCert) |
| 178 | } |
| 179 | } |
| 180 | if o.testRequests < 1 { |
| 181 | return fmt.Errorf("please do not ask for fewer than 1 test request(%d)", o.testRequests) |
| 182 | } |
| 183 | if o.testDelaySec < 0 { |
| 184 | return fmt.Errorf("please do not ask for less than a 0 second delay(%d)", o.testDelaySec) |
| 185 | } |
| 186 | if o.afterDelaySec < 0 { |
| 187 | return fmt.Errorf("please do not ask for less than a 0 second delay(%d)", o.afterDelaySec) |
| 188 | } |
| 189 | return nil |
| 190 | } |
| 191 | |
| 192 | func newGrpcProxyClientOptions() *GrpcProxyClientOptions { |
| 193 | o := GrpcProxyClientOptions{ |
| 194 | clientCert: "", |
| 195 | clientKey: "", |
| 196 | caCert: "", |
| 197 | requestProto: "http", |
| 198 | requestPath: "success", |
| 199 | requestHost: "localhost", |
| 200 | requestPort: 8000, |
| 201 | proxyHost: "localhost", |
| 202 | proxyPort: 8090, |
| 203 | proxyUdsName: "", |
| 204 | mode: "grpc", |
| 205 | userAgent: "test-client", |
| 206 | testRequests: 1, |
| 207 | testDelaySec: 0, |
| 208 | afterDelaySec: 0, |
| 209 | closeIdleConn: true, |
| 210 | enableHTTP2HealthChecks: true, |
| 211 | } |
| 212 | return &o |
| 213 | } |
| 214 | |
| 215 | func newGrpcProxyClientCommand(c *Client, o *GrpcProxyClientOptions) *cobra.Command { |
| 216 | cmd := &cobra.Command{ |
| 217 | Use: "proxy-client", |
| 218 | Long: `A gRPC proxy Client, primarily used to test the Kubernetes gRPC Proxy Server.`, |
| 219 | RunE: func(cmd *cobra.Command, _ []string) error { |
| 220 | cmd.SilenceUsage = true |
| 221 | return c.run(o) |
| 222 | }, |
| 223 | } |
| 224 | |
| 225 | return cmd |
| 226 | } |
| 227 | |
| 228 | type Client struct { |
| 229 | } |
| 230 | |
| 231 | func (c *Client) run(o *GrpcProxyClientOptions) error { |
| 232 | o.Print() |
| 233 | if err := o.Validate(); err != nil { |
| 234 | return fmt.Errorf("failed to validate proxy client options, got: %w", err) |
| 235 | } |
| 236 | |
| 237 | // Run remote simple http service on server side as |
| 238 | // "python -m SimpleHTTPServer" |
| 239 | |
| 240 | // The apiserver network proxy does not support reusing the same dialer for multiple connections. |
| 241 | // With HTTP 1.1 Connection reuse, network proxy should support subsequent requests with the original connection |
| 242 | // as long as the connection has not been closed. This means that this connection/client cannot be shared. |
| 243 | // golang's default IdleConnTimeout is 90 seconds (https://golang.org/src/net/http/transport.go?s=13608:13676) |
| 244 | // k/k abides by this default. |
| 245 | // |
| 246 | // When running the test-client with a delay parameter greater than 90s (even when no agent restart is done) |
| 247 | // --test-requests=2 --test-delay=100 the second request will fail 100% of the time because currently network proxy |
| 248 | // explicitly closes the tunnel when a close request is sent to to the inner TCP connection. |
| 249 | // We do this as there is no way for us to know whether a tunnel will be reused. |
| 250 | // So to prevent leaking too many tunnel connections, |
| 251 | // we explicitly close the tunnel on the first CLOSE_RSP we obtain from the inner TCP connection |
| 252 | // (https://github.com/kubernetes-sigs/apiserver-network-proxy/blob/master/konnectivity-client/pkg/client/client.go#L137). |
| 253 | var wg sync.WaitGroup |
| 254 | ch := make(chan error, o.testRequests) |
| 255 | |
| 256 | for i := 1; i <= o.testRequests; i++ { |
| 257 | i := i |
| 258 | wg.Add(1) |
| 259 | labels := runpprof.Labels( |
| 260 | "core", "testClient", |
| 261 | "testID", strconv.Itoa(i), |
| 262 | ) |
| 263 | go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 264 | defer wg.Done() |
| 265 | dialer, err := c.getDialer(o) |
| 266 | if err != nil { |
| 267 | ch <- fmt.Errorf("failed to get dialer for client, got %v", err) |
| 268 | return |
| 269 | } |
| 270 | transport := &http.Transport{ |
| 271 | DialContext: dialer, |
| 272 | } |
| 273 | if o.enableHTTP2HealthChecks { |
| 274 | err = configureHTTP2Transport(transport) |
| 275 | if err != nil { |
| 276 | klog.V(1).Error(err, "error initializing HTTP2 health checking parameters. Using default transport.") |
| 277 | } |
| 278 | } |
| 279 | client := &http.Client{ |
| 280 | Transport: transport, |
| 281 | } |
| 282 | if o.closeIdleConn { |
| 283 | defer client.CloseIdleConnections() |
| 284 | } |
| 285 | |
| 286 | err = c.makeRequest(o, client) |
| 287 | if err != nil { |
| 288 | ch <- err |
| 289 | return |
| 290 | } |
| 291 | |
| 292 | if i != o.testRequests { |
| 293 | klog.V(1).InfoS("Waiting for next connection test.", "seconds", o.testDelaySec, "iteration", i, "test requests", o.testRequests) |
| 294 | wait := time.Duration(o.testDelaySec) * time.Second |
| 295 | time.Sleep(wait) |
| 296 | } |
| 297 | ch <- nil |
| 298 | }) |
| 299 | } |
| 300 | wg.Wait() |
| 301 | close(ch) |
| 302 | if o.afterDelaySec > 0 { |
| 303 | wait := time.Duration(o.afterDelaySec) * time.Second |
| 304 | time.Sleep(wait) |
| 305 | } |
| 306 | // collect up and return errors |
| 307 | errs := []error{} |
| 308 | for err := range ch { |
| 309 | if err != nil { |
| 310 | errs = append(errs, err) |
| 311 | } |
| 312 | } |
| 313 | if len(errs) > 1 { |
| 314 | klog.Errorf("Failed request number %d", len(errs)) |
| 315 | return fmt.Errorf("Requests failed: %d", len(errs)) |
| 316 | } else if len(errs) == 1 { |
| 317 | klog.Errorf("Failed request %v", errs[0]) |
| 318 | return errs[0] |
| 319 | } |
| 320 | |
| 321 | return nil |
| 322 | } |
| 323 | |
| 324 | func readIdleTimeoutSeconds() int { |
| 325 | ret := 30 |
| 326 | // User can set the readIdleTimeout to 0 to disable the HTTP/2 |
| 327 | // connection health check. |
| 328 | if s := os.Getenv("HTTP2_READ_IDLE_TIMEOUT_SECONDS"); len(s) > 0 { |
| 329 | i, err := strconv.Atoi(s) |
| 330 | if err != nil { |
| 331 | klog.Warningf("Illegal HTTP2_READ_IDLE_TIMEOUT_SECONDS(%q): %v."+ |
| 332 | " Default value %d is used", s, err, ret) |
| 333 | return ret |
| 334 | } |
| 335 | ret = i |
| 336 | } |
| 337 | return ret |
| 338 | } |
| 339 | |
| 340 | func pingTimeoutSeconds() int { |
| 341 | ret := 15 |
| 342 | if s := os.Getenv("HTTP2_PING_TIMEOUT_SECONDS"); len(s) > 0 { |
| 343 | i, err := strconv.Atoi(s) |
| 344 | if err != nil { |
| 345 | klog.Warningf("Illegal HTTP2_PING_TIMEOUT_SECONDS(%q): %v."+ |
| 346 | " Default value %d is used", s, err, ret) |
| 347 | return ret |
| 348 | } |
| 349 | ret = i |
| 350 | } |
| 351 | return ret |
| 352 | } |
| 353 | |
| 354 | func configureHTTP2Transport(t *http.Transport) error { |
| 355 | t2, err := http2.ConfigureTransports(t) |
| 356 | if err != nil { |
| 357 | return err |
| 358 | } |
| 359 | // The following enables the HTTP/2 connection health check added in |
| 360 | // https://github.com/golang/net/pull/55. The health check detects and |
| 361 | // closes broken transport layer connections. Without the health check, |
| 362 | // a broken connection can linger too long, e.g., a broken TCP |
| 363 | // connection will be closed by the Linux kernel after 13 to 30 minutes |
| 364 | // by default, which caused |
| 365 | // https://github.com/kubernetes/client-go/issues/374 and |
| 366 | // https://github.com/kubernetes/kubernetes/issues/87615. |
| 367 | t2.ReadIdleTimeout = time.Duration(readIdleTimeoutSeconds()) * time.Second |
| 368 | t2.PingTimeout = time.Duration(pingTimeoutSeconds()) * time.Second |
| 369 | return nil |
| 370 | } |
| 371 | |
| 372 | func (c *Client) makeRequest(o *GrpcProxyClientOptions, client *http.Client) error { |
| 373 | requestURL := url.URL{ |
| 374 | Scheme: o.requestProto, |
| 375 | Host: joinHostPort(o.requestHost, o.requestPort), |
| 376 | Path: o.requestPath, |
| 377 | } |
| 378 | request, err := http.NewRequest("GET", requestURL.String(), nil) |
| 379 | if err != nil { |
| 380 | return fmt.Errorf("failed to create request %v to send, got %v", requestURL, err) |
| 381 | } |
| 382 | response, err := client.Do(request) |
| 383 | if err != nil { |
| 384 | return fmt.Errorf("failed to send request to client, got %v", err) |
| 385 | } |
| 386 | defer func() { |
| 387 | err := response.Body.Close() |
| 388 | if err != nil { |
| 389 | klog.Errorf("Failed to close connection, got %v", err) |
| 390 | } |
| 391 | }() // TODO: proxy server should handle the case where Body isn't closed. |
| 392 | |
| 393 | data, err := io.ReadAll(response.Body) |
| 394 | if err != nil { |
| 395 | return fmt.Errorf("failed to read response from client, got %v", err) |
| 396 | } |
| 397 | klog.V(4).Infof("HTML Response:\n%s\n", string(data)) |
| 398 | return nil |
| 399 | } |
| 400 | |
| 401 | func (c *Client) getDialer(o *GrpcProxyClientOptions) (func(ctx context.Context, network, addr string) (net.Conn, error), error) { |
| 402 | if o.proxyUdsName != "" { |
| 403 | return c.getUDSDialer(o) |
| 404 | } |
| 405 | return c.getMTLSDialer(o) |
| 406 | } |
| 407 | |
| 408 | func (c *Client) getUDSDialer(o *GrpcProxyClientOptions) (func(ctx context.Context, network, addr string) (net.Conn, error), error) { |
| 409 | ctx := context.Background() |
| 410 | |
| 411 | var proxyConn net.Conn |
| 412 | var err error |
| 413 | // Setup signal handler |
| 414 | ch := make(chan os.Signal, 1) |
| 415 | signal.Notify(ch) |
| 416 | |
| 417 | labels := runpprof.Labels( |
| 418 | "core", "testUdsDialer", |
| 419 | "requestPath", o.requestPath, |
| 420 | "udsName", o.proxyUdsName, |
| 421 | ) |
| 422 | go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 423 | <-ch |
| 424 | if proxyConn != nil { |
| 425 | err := proxyConn.Close() |
| 426 | klog.ErrorS(err, "connection closed") |
| 427 | } |
| 428 | }) |
| 429 | |
| 430 | switch o.mode { |
| 431 | case "grpc": |
| 432 | dialOption := grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { |
| 433 | // Ignoring addr and timeout arguments: |
| 434 | // addr - comes from the closure |
| 435 | // timeout - is turned off as this is test code and eases debugging. |
| 436 | c, err := net.DialTimeout("unix", o.proxyUdsName, 0) |
| 437 | if err != nil { |
| 438 | klog.ErrorS(err, "failed to create connection to uds", "name", o.proxyUdsName) |
| 439 | } |
| 440 | return c, err |
| 441 | }) |
| 442 | tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, o.proxyUdsName, dialOption, grpc.WithInsecure(), grpc.WithUserAgent(o.userAgent)) |
| 443 | if err != nil { |
| 444 | return nil, fmt.Errorf("failed to create tunnel %s, got %v", o.proxyUdsName, err) |
| 445 | } |
| 446 | |
| 447 | requestAddress := joinHostPort(o.requestHost, o.requestPort) |
| 448 | proxyConn, err = tunnel.DialContext(ctx, "tcp", requestAddress) |
| 449 | if err != nil { |
| 450 | return nil, fmt.Errorf("failed to dial request %s, got %v", requestAddress, err) |
| 451 | } |
| 452 | case "http-connect": |
| 453 | requestAddress := joinHostPort(o.requestHost, o.requestPort) |
| 454 | |
| 455 | proxyConn, err = net.Dial("unix", o.proxyUdsName) |
| 456 | if err != nil { |
| 457 | return nil, fmt.Errorf("dialing proxy %q failed: %v", o.proxyUdsName, err) |
| 458 | } |
| 459 | fmt.Fprintf(proxyConn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: %s\r\n\r\n", requestAddress, "127.0.0.1", o.userAgent) |
| 460 | br := bufio.NewReader(proxyConn) |
| 461 | res, err := http.ReadResponse(br, nil) |
| 462 | if err != nil { |
| 463 | return nil, fmt.Errorf("reading HTTP response from CONNECT to %s via uds proxy %s failed: %v", |
| 464 | requestAddress, o.proxyUdsName, err) |
| 465 | } |
| 466 | if res.StatusCode != 200 { |
| 467 | return nil, fmt.Errorf("proxy error from %s while dialing %s: %v", o.proxyUdsName, requestAddress, res.Status) |
| 468 | } |
| 469 | |
| 470 | // It's safe to discard the bufio.Reader here and return the |
| 471 | // original TCP conn directly because we only use this for |
| 472 | // TLS, and in TLS the client speaks first, so we know there's |
| 473 | // no unbuffered data. But we can double-check. |
| 474 | if br.Buffered() > 0 { |
| 475 | return nil, fmt.Errorf("unexpected %d bytes of buffered data from CONNECT uds proxy %q", |
| 476 | br.Buffered(), o.proxyUdsName) |
| 477 | } |
| 478 | default: |
| 479 | return nil, fmt.Errorf("failed to process mode %s", o.mode) |
| 480 | } |
| 481 | |
| 482 | return func(_ context.Context, _, _ string) (net.Conn, error) { |
| 483 | return proxyConn, nil |
| 484 | }, nil |
| 485 | } |
| 486 | |
| 487 | func (c *Client) getMTLSDialer(o *GrpcProxyClientOptions) (func(ctx context.Context, network, addr string) (net.Conn, error), error) { |
| 488 | ctx := context.Background() |
| 489 | tlsConfig, err := util.GetClientTLSConfig(o.caCert, o.clientCert, o.clientKey, o.proxyHost, nil) |
| 490 | if err != nil { |
| 491 | return nil, err |
| 492 | } |
| 493 | |
| 494 | var proxyConn net.Conn |
| 495 | |
| 496 | // Setup signal handler |
| 497 | ch := make(chan os.Signal, 1) |
| 498 | signal.Notify(ch) |
| 499 | |
| 500 | labels := runpprof.Labels( |
| 501 | "core", "testMTLSDialer", |
| 502 | "requestPath", o.requestPath, |
| 503 | "requestPort", strconv.Itoa(o.requestPort), |
| 504 | ) |
| 505 | go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 506 | <-ch |
| 507 | if proxyConn != nil { |
| 508 | err := proxyConn.Close() |
| 509 | klog.ErrorS(err, "connection closed") |
| 510 | } |
| 511 | }) |
| 512 | |
| 513 | switch o.mode { |
| 514 | case "grpc": |
| 515 | transportCreds := credentials.NewTLS(tlsConfig) |
| 516 | dialOption := grpc.WithTransportCredentials(transportCreds) |
| 517 | serverAddress := joinHostPort(o.proxyHost, o.proxyPort) |
| 518 | tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, serverAddress, dialOption) |
| 519 | if err != nil { |
| 520 | return nil, fmt.Errorf("failed to create tunnel %s, got %v", serverAddress, err) |
| 521 | } |
| 522 | |
| 523 | requestAddress := joinHostPort(o.requestHost, o.requestPort) |
| 524 | proxyConn, err = tunnel.DialContext(ctx, "tcp", requestAddress) |
| 525 | if err != nil { |
| 526 | return nil, fmt.Errorf("failed to dial request %s, got %v", requestAddress, err) |
| 527 | } |
| 528 | case "http-connect": |
| 529 | proxyAddress := joinHostPort(o.proxyHost, o.proxyPort) |
| 530 | requestAddress := joinHostPort(o.requestHost, o.requestPort) |
| 531 | |
| 532 | proxyConn, err = tls.Dial("tcp", proxyAddress, tlsConfig) |
| 533 | if err != nil { |
| 534 | return nil, fmt.Errorf("dialing proxy %q failed: %v", proxyAddress, err) |
| 535 | } |
| 536 | fmt.Fprintf(proxyConn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", requestAddress, "127.0.0.1") |
| 537 | br := bufio.NewReader(proxyConn) |
| 538 | res, err := http.ReadResponse(br, nil) |
| 539 | if err != nil { |
| 540 | return nil, fmt.Errorf("reading HTTP response from CONNECT to %s via proxy %s failed: %v", |
| 541 | requestAddress, proxyAddress, err) |
| 542 | } |
| 543 | if res.StatusCode != 200 { |
| 544 | return nil, fmt.Errorf("proxy error from %s while dialing %s: %v", proxyAddress, requestAddress, res.Status) |
| 545 | } |
| 546 | |
| 547 | // It's safe to discard the bufio.Reader here and return the |
| 548 | // original TCP conn directly because we only use this for |
| 549 | // TLS, and in TLS the client speaks first, so we know there's |
| 550 | // no unbuffered data. But we can double-check. |
| 551 | if br.Buffered() > 0 { |
| 552 | return nil, fmt.Errorf("unexpected %d bytes of buffered data from CONNECT proxy %q", |
| 553 | br.Buffered(), proxyAddress) |
| 554 | } |
| 555 | default: |
| 556 | return nil, fmt.Errorf("failed to process mode %s", o.mode) |
| 557 | } |
| 558 | |
| 559 | return func(_ context.Context, _, _ string) (net.Conn, error) { |
| 560 | return proxyConn, nil |
| 561 | }, nil |
| 562 | } |
| 563 | |
| 564 | func joinHostPort(host string, port int) string { |
| 565 | return net.JoinHostPort(host, strconv.Itoa(port)) |
| 566 | } |