| 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 server |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "io" |
| 22 | "math/rand" |
| 23 | "net/http" |
| 24 | "sync" |
| 25 | "time" |
| 26 | |
| 27 | "k8s.io/klog/v2" |
| 28 | "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 29 | "sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics" |
| 30 | ) |
| 31 | |
| 32 | // Tunnel implements Proxy based on HTTP Connect, which tunnels the traffic to |
| 33 | // the agent registered in ProxyServer. |
| 34 | type Tunnel struct { |
| 35 | Server *ProxyServer |
| 36 | } |
| 37 | |
| 38 | func (t *Tunnel) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 39 | metrics.Metrics.HTTPConnectionInc() |
| 40 | defer metrics.Metrics.HTTPConnectionDec() |
| 41 | |
| 42 | klog.V(2).InfoS("Received request for host", "method", r.Method, "host", r.Host, "userAgent", r.UserAgent()) |
| 43 | if r.TLS != nil { |
| 44 | klog.V(2).InfoS("TLS", "commonName", r.TLS.PeerCertificates[0].Subject.CommonName) |
| 45 | } |
| 46 | if r.Method != http.MethodConnect { |
| 47 | http.Error(w, "this proxy only supports CONNECT passthrough", http.StatusMethodNotAllowed) |
| 48 | return |
| 49 | } |
| 50 | |
| 51 | hijacker, ok := w.(http.Hijacker) |
| 52 | if !ok { |
| 53 | http.Error(w, "hijacking not supported", http.StatusInternalServerError) |
| 54 | return |
| 55 | } |
| 56 | |
| 57 | conn, bufrw, err := hijacker.Hijack() |
| 58 | if err != nil { |
| 59 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 60 | return |
| 61 | } |
| 62 | |
| 63 | // Send the HTTP 200 OK status after a successful hijack |
| 64 | _, err = conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) |
| 65 | if err != nil { |
| 66 | klog.ErrorS(err, "failed to send 200 connection established") |
| 67 | conn.Close() |
| 68 | return |
| 69 | } |
| 70 | |
| 71 | var closeOnce sync.Once |
| 72 | defer closeOnce.Do(func() { conn.Close() }) |
| 73 | |
| 74 | random := rand.Int63() /* #nosec G404 */ |
| 75 | dialRequest := &client.Packet{ |
| 76 | Type: client.PacketType_DIAL_REQ, |
| 77 | Payload: &client.Packet_DialRequest{ |
| 78 | DialRequest: &client.DialRequest{ |
| 79 | Protocol: "tcp", |
| 80 | Address: r.Host, |
| 81 | Random: random, |
| 82 | }, |
| 83 | }, |
| 84 | } |
| 85 | |
| 86 | klog.V(4).Infof("Set pending(rand=%d) to %v", random, w) |
| 87 | backend, err := t.Server.getBackend(r.Host) |
| 88 | if err != nil { |
| 89 | klog.ErrorS(err, "no tunnels available") |
| 90 | conn.Write([]byte(fmt.Sprintf("HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\n\r\ncurrently no tunnels available: %v", err))) |
| 91 | conn.Close() |
| 92 | return |
| 93 | } |
| 94 | closed := make(chan struct{}) |
| 95 | connected := make(chan struct{}) |
| 96 | connection := &ProxyClientConnection{ |
| 97 | Mode: ModeHTTPConnect, |
| 98 | HTTP: io.ReadWriter(conn), // pass as ReadWriter so the caller must close with CloseHTTP |
| 99 | CloseHTTP: func() error { |
| 100 | closeOnce.Do(func() { conn.Close() }) |
| 101 | close(closed) |
| 102 | return nil |
| 103 | }, |
| 104 | connected: connected, |
| 105 | start: time.Now(), |
| 106 | backend: backend, |
| 107 | } |
| 108 | t.Server.PendingDial.Add(random, connection) |
| 109 | if err := backend.Send(dialRequest); err != nil { |
| 110 | klog.ErrorS(err, "failed to tunnel dial request") |
| 111 | return |
| 112 | } |
| 113 | ctxt := backend.Context() |
| 114 | if ctxt.Err() != nil { |
| 115 | klog.ErrorS(err, "context reports failure") |
| 116 | } |
| 117 | |
| 118 | select { |
| 119 | case <-ctxt.Done(): |
| 120 | klog.V(5).Infoln("context reports done") |
| 121 | default: |
| 122 | } |
| 123 | |
| 124 | select { |
| 125 | case <-connection.connected: // Waiting for response before we begin full communication. |
| 126 | case <-closed: // Connection was closed before being established |
| 127 | } |
| 128 | |
| 129 | defer func() { |
| 130 | packet := &client.Packet{ |
| 131 | Type: client.PacketType_CLOSE_REQ, |
| 132 | Payload: &client.Packet_CloseRequest{ |
| 133 | CloseRequest: &client.CloseRequest{ |
| 134 | ConnectID: connection.connectID, |
| 135 | }, |
| 136 | }, |
| 137 | } |
| 138 | |
| 139 | if err = backend.Send(packet); err != nil { |
| 140 | klog.V(2).InfoS("failed to send close request packet", "host", r.Host, "agentID", connection.agentID, "connectionID", connection.connectID) |
| 141 | } |
| 142 | conn.Close() |
| 143 | }() |
| 144 | |
| 145 | klog.V(3).InfoS("Starting proxy to host", "host", r.Host) |
| 146 | pkt := make([]byte, 1<<15) // Match GRPC Window size |
| 147 | |
| 148 | connID := connection.connectID |
| 149 | agentID := connection.agentID |
| 150 | var acc int |
| 151 | |
| 152 | for { |
| 153 | n, err := bufrw.Read(pkt[:]) |
| 154 | acc += n |
| 155 | if err == io.EOF { |
| 156 | klog.V(1).InfoS("EOF from host", "host", r.Host) |
| 157 | break |
| 158 | } |
| 159 | if err != nil { |
| 160 | klog.ErrorS(err, "Received failure on connection") |
| 161 | break |
| 162 | } |
| 163 | |
| 164 | packet := &client.Packet{ |
| 165 | Type: client.PacketType_DATA, |
| 166 | Payload: &client.Packet_Data{ |
| 167 | Data: &client.Data{ |
| 168 | ConnectID: connID, |
| 169 | Data: pkt[:n], |
| 170 | }, |
| 171 | }, |
| 172 | } |
| 173 | err = backend.Send(packet) |
| 174 | if err != nil { |
| 175 | klog.ErrorS(err, "error sending packet") |
| 176 | break |
| 177 | } |
| 178 | klog.V(5).InfoS("Forwarding data on tunnel to agent", |
| 179 | "bytes", n, |
| 180 | "totalBytes", acc, |
| 181 | "agentID", connection.agentID, |
| 182 | "connectionID", connection.connectID) |
| 183 | } |
| 184 | |
| 185 | klog.V(5).InfoS("Stopping transfer to host", "host", r.Host, "agentID", agentID, "connectionID", connID) |
| 186 | } |