package relayclient

import (
	
	
	
	
	
	
	
	
	
	
	
	

	
)

// dialProxy opens a CONNECT tunnel to target. relayTLS configures the TLS
// connection to an https proxy. For a TLS relay, the caller performs the relay
// handshake over the tunnel so relay authentication is derived from that session.
func dialProxy( context.Context,  *url.URL,  string,  *tls.Config) (net.Conn, error) {
	if  := proxyurl.Validate();  != nil {
		return nil, fmt.Errorf("invalid proxy URL")
	}
	 := strings.ToLower(.Scheme)
	if  != "http" &&  != "https" {
		return nil, fmt.Errorf("unsupported proxy scheme %q", .Scheme)
	}
	 := .Port()
	if  == "" {
		if  == "https" {
			 = "443"
		} else {
			 = "80"
		}
	}
	if ,  := strconv.Atoi();  != nil ||  < 1 ||  > 65535 {
		return nil, fmt.Errorf("invalid proxy port %q", )
	}
	 := net.JoinHostPort(.Hostname(), )
	,  := (&net.Dialer{}).DialContext(, "tcp", )
	if  != nil {
		return nil, fmt.Errorf("dial proxy: %w", )
	}
	 := false
	defer func() {
		if ! {
			.Close()
		}
	}()

	if  == "https" {
		// Rust uses the relay TLS connector for the proxy TLS layer too.
		 := &tls.Config{}
		if  != nil {
			 = .Clone()
		}
		.ServerName = .Hostname()
		 := tls.Client(, )
		if  := .HandshakeContext();  != nil {
			return nil, fmt.Errorf("proxy TLS handshake: %w", )
		}
		 = 
	}

	 := context.AfterFunc(, func() { _ = .SetDeadline(time.Now()) })
	if ,  := .Deadline();  {
		if  := .SetDeadline();  != nil {
			()
			return nil, fmt.Errorf("set proxy deadline: %w", )
		}
	}
	 := 
	if ,  := fmt.Fprintf(, "CONNECT %s HTTP/1.1\r\nHost: %s\r\nProxy-Connection: Keep-Alive\r\n", , );  != nil {
		()
		return nil, fmt.Errorf("write CONNECT request: %w", )
	}
	if .User != nil {
		,  := .User.Password()
		 := .User.Username() + ":" + 
		if ,  := fmt.Fprintf(, "Proxy-Authorization: Basic %s\r\n", base64.StdEncoding.EncodeToString([]byte()));  != nil {
			()
			return nil, fmt.Errorf("write proxy authorization: %w", )
		}
	}
	if ,  := io.WriteString(, "\r\n");  != nil {
		()
		return nil, fmt.Errorf("finish CONNECT request: %w", )
	}
	 := bufio.NewReader()
	,  := http.ReadResponse(, &http.Request{Method: http.MethodConnect})
	if  != nil {
		()
		return nil, fmt.Errorf("read CONNECT response: %w", )
	}
	if .StatusCode < 200 || .StatusCode >= 300 {
		.Body.Close()
		()
		return nil, fmt.Errorf("proxy CONNECT failed: %s", .Status)
	}
	if !() {
		return nil, .Err()
	}
	if  := .SetDeadline(time.Time{});  != nil {
		return nil, fmt.Errorf("clear proxy deadline: %w", )
	}
	if .Buffered() > 0 {
		 = &bufferedConn{Conn: , reader: }
	}
	 = true
	return , nil
}

type bufferedConn struct {
	net.Conn
	reader *bufio.Reader
}

func ( *bufferedConn) ( []byte) (int, error) { return .reader.Read() }