tunnel answers a CONNECT as the host gh asked for: it completes the TLS handshake with a certificate from ghmock's authority, then hands the connection to the server that answers the requests inside it.
(w http.ResponseWriter, r *http.Request)
| 270 | // handshake with a certificate from ghmock's authority, then hands the |
| 271 | // connection to the server that answers the requests inside it. |
| 272 | func (m *mockServer) tunnel(w http.ResponseWriter, r *http.Request) { |
| 273 | hostname := r.Host |
| 274 | if h, _, err := net.SplitHostPort(r.Host); err == nil { |
| 275 | hostname = h |
| 276 | } |
| 277 | hj, ok := w.(http.Hijacker) |
| 278 | if !ok { |
| 279 | http.Error(w, "ghmock: can't open a tunnel", http.StatusInternalServerError) |
| 280 | return |
| 281 | } |
| 282 | conn, rw, err := hj.Hijack() |
| 283 | if err != nil { |
| 284 | return |
| 285 | } |
| 286 | if !m.startHandshake() { |
| 287 | _ = conn.Close() |
| 288 | return |
| 289 | } |
| 290 | defer m.handshakes.Done() |
| 291 | if _, err := rw.WriteString("HTTP/1.1 200 Connection established\r\n\r\n"); err != nil { |
| 292 | _ = conn.Close() |
| 293 | return |
| 294 | } |
| 295 | if err := rw.Flush(); err != nil { |
| 296 | _ = conn.Close() |
| 297 | return |
| 298 | } |
| 299 | |
| 300 | tlsConn := tls.Server(&bufferedConn{Conn: conn, r: rw.Reader}, m.ca.serverConfig(hostname)) |
| 301 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 302 | defer cancel() |
| 303 | if err := tlsConn.HandshakeContext(ctx); err != nil { |
| 304 | _ = tlsConn.Close() |
| 305 | // A client that hangs up before the handshake hasn't rejected anything. |
| 306 | if !errors.Is(err, io.EOF) { |
| 307 | m.record(loggedRequest{Method: http.MethodConnect, Host: r.Host, TLSError: err.Error()}) |
| 308 | } |
| 309 | return |
| 310 | } |
| 311 | m.tunnels.push(tlsConn) |
| 312 | } |
| 313 | |
| 314 | // startHandshake counts a TLS handshake that close waits for. It returns false |
| 315 | // once the server is closing. |
no test coverage detected