istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/hbone/server.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package hbone 16 17 import ( 18 "context" 19 "net" 20 "net/http" 21 "sync" 22 "time" 23 24 "golang.org/x/net/http2" 25 26 "istio.io/istio/pkg/h2c" 27 ) 28 29 func NewServer() *http.Server { 30 // Need to set this to allow timeout on the read header 31 h1 := &http.Transport{ 32 ExpectContinueTimeout: 3 * time.Second, 33 } 34 h2, _ := http2.ConfigureTransports(h1) 35 h2.ReadIdleTimeout = 10 * time.Minute // TODO: much larger to support long-lived connections 36 h2.AllowHTTP = true 37 h2Server := &http2.Server{} 38 handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 39 if r.Method == http.MethodConnect { 40 if handleConnect(w, r) { 41 return 42 } 43 } else { 44 log.Errorf("non-CONNECT: %v", r.Method) 45 w.WriteHeader(http.StatusMethodNotAllowed) 46 } 47 }) 48 hs := &http.Server{ 49 Handler: h2c.NewHandler(handler, h2Server), 50 } 51 return hs 52 } 53 54 func handleConnect(w http.ResponseWriter, r *http.Request) bool { 55 t0 := time.Now() 56 log.WithLabels("host", r.Host, "source", r.RemoteAddr).Info("Received CONNECT") 57 // Send headers back immediately so we can start getting the body 58 w.(http.Flusher).Flush() 59 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 60 defer cancel() 61 62 dst, err := (&net.Dialer{}).DialContext(ctx, "tcp", r.Host) 63 if err != nil { 64 w.WriteHeader(http.StatusServiceUnavailable) 65 log.Errorf("failed to dial upstream: %v", err) 66 return true 67 } 68 log.Infof("Connected to %v", r.Host) 69 w.WriteHeader(http.StatusOK) 70 71 wg := sync.WaitGroup{} 72 wg.Add(1) 73 go func() { 74 // downstream (hbone client) <-- upstream (app) 75 copyBuffered(w, dst, log.WithLabels("name", "dst to w")) 76 err = r.Body.Close() 77 if err != nil { 78 log.Infof("connection to hbone client is not closed: %v", err) 79 } 80 wg.Done() 81 }() 82 // downstream (hbone client) --> upstream (app) 83 copyBuffered(dst, r.Body, log.WithLabels("name", "body to dst")) 84 wg.Wait() 85 log.Infof("connection closed in %v", time.Since(t0)) 86 return false 87 }