123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624 |
- package vhost
- import (
- "context"
- "fmt"
- "io"
- "log"
- "net"
- "net/http"
- "net/textproto"
- "net/url"
- "strings"
- "sync"
- "time"
- "golang.org/x/net/http/httpguts"
- )
- type ReverseProxy struct {
-
-
-
-
-
-
- Director func(*http.Request)
-
-
- Transport http.RoundTripper
-
-
-
-
-
-
-
-
-
-
- FlushInterval time.Duration
-
-
-
- ErrorLog *log.Logger
-
-
-
- BufferPool BufferPool
-
-
-
-
-
-
-
-
-
- ModifyResponse func(*http.Response) error
-
-
-
-
-
- ErrorHandler func(http.ResponseWriter, *http.Request, error)
- }
- type BufferPool interface {
- Get() []byte
- Put([]byte)
- }
- func singleJoiningSlash(a, b string) string {
- aslash := strings.HasSuffix(a, "/")
- bslash := strings.HasPrefix(b, "/")
- switch {
- case aslash && bslash:
- return a + b[1:]
- case !aslash && !bslash:
- return a + "/" + b
- }
- return a + b
- }
- func joinURLPath(a, b *url.URL) (path, rawpath string) {
- if a.RawPath == "" && b.RawPath == "" {
- return singleJoiningSlash(a.Path, b.Path), ""
- }
-
-
- apath := a.EscapedPath()
- bpath := b.EscapedPath()
- aslash := strings.HasSuffix(apath, "/")
- bslash := strings.HasPrefix(bpath, "/")
- switch {
- case aslash && bslash:
- return a.Path + b.Path[1:], apath + bpath[1:]
- case !aslash && !bslash:
- return a.Path + "/" + b.Path, apath + "/" + bpath
- }
- return a.Path + b.Path, apath + bpath
- }
- func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
- targetQuery := target.RawQuery
- director := func(req *http.Request) {
- req.URL.Scheme = target.Scheme
- req.URL.Host = target.Host
- req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
- if targetQuery == "" || req.URL.RawQuery == "" {
- req.URL.RawQuery = targetQuery + req.URL.RawQuery
- } else {
- req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
- }
- if _, ok := req.Header["User-Agent"]; !ok {
-
- req.Header.Set("User-Agent", "")
- }
- }
- return &ReverseProxy{Director: director}
- }
- func copyHeader(dst, src http.Header) {
- for k, vv := range src {
- for _, v := range vv {
- dst.Add(k, v)
- }
- }
- }
- var hopHeaders = []string{
- "Connection",
- "Proxy-Connection",
- "Keep-Alive",
- "Proxy-Authenticate",
- "Proxy-Authorization",
- "Te",
- "Trailer",
- "Transfer-Encoding",
- "Upgrade",
- }
- func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
- p.logf("http: proxy error: %v", err)
- rw.WriteHeader(http.StatusBadGateway)
- }
- func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
- if p.ErrorHandler != nil {
- return p.ErrorHandler
- }
- return p.defaultErrorHandler
- }
- func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
- if p.ModifyResponse == nil {
- return true
- }
- if err := p.ModifyResponse(res); err != nil {
- res.Body.Close()
- p.getErrorHandler()(rw, req, err)
- return false
- }
- return true
- }
- func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
- transport := p.Transport
- if transport == nil {
- transport = http.DefaultTransport
- }
- ctx := req.Context()
- if cn, ok := rw.(http.CloseNotifier); ok {
- var cancel context.CancelFunc
- ctx, cancel = context.WithCancel(ctx)
- defer cancel()
- notifyChan := cn.CloseNotify()
- go func() {
- select {
- case <-notifyChan:
- cancel()
- case <-ctx.Done():
- }
- }()
- }
- outreq := req.Clone(ctx)
- if req.ContentLength == 0 {
- outreq.Body = nil
- }
- if outreq.Header == nil {
- outreq.Header = make(http.Header)
- }
-
-
- outreq = outreq.Clone(context.WithValue(outreq.Context(), RouteInfoURL, req.URL.Path))
- outreq = outreq.Clone(context.WithValue(outreq.Context(), RouteInfoHost, req.Host))
- outreq = outreq.Clone(context.WithValue(outreq.Context(), RouteInfoRemote, req.RemoteAddr))
-
- p.Director(outreq)
- outreq.Close = false
- reqUpType := upgradeType(outreq.Header)
- removeConnectionHeaders(outreq.Header)
-
-
-
- for _, h := range hopHeaders {
- hv := outreq.Header.Get(h)
- if hv == "" {
- continue
- }
- if h == "Te" && hv == "trailers" {
-
-
-
-
-
-
- continue
- }
- outreq.Header.Del(h)
- }
-
-
- if reqUpType != "" {
- outreq.Header.Set("Connection", "Upgrade")
- outreq.Header.Set("Upgrade", reqUpType)
- }
- if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
-
-
-
- prior, ok := outreq.Header["X-Forwarded-For"]
- omit := ok && prior == nil
- if len(prior) > 0 {
- clientIP = strings.Join(prior, ", ") + ", " + clientIP
- }
- if !omit {
- outreq.Header.Set("X-Forwarded-For", clientIP)
- }
- }
- res, err := transport.RoundTrip(outreq)
- if err != nil {
- p.getErrorHandler()(rw, outreq, err)
- return
- }
-
- if res.StatusCode == http.StatusSwitchingProtocols {
- if !p.modifyResponse(rw, res, outreq) {
- return
- }
- p.handleUpgradeResponse(rw, outreq, res)
- return
- }
- removeConnectionHeaders(res.Header)
- for _, h := range hopHeaders {
- res.Header.Del(h)
- }
- if !p.modifyResponse(rw, res, outreq) {
- return
- }
- copyHeader(rw.Header(), res.Header)
-
-
- announcedTrailers := len(res.Trailer)
- if announcedTrailers > 0 {
- trailerKeys := make([]string, 0, len(res.Trailer))
- for k := range res.Trailer {
- trailerKeys = append(trailerKeys, k)
- }
- rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
- }
- rw.WriteHeader(res.StatusCode)
- err = p.copyResponse(rw, res.Body, p.flushInterval(res))
- if err != nil {
- defer res.Body.Close()
-
-
-
- if !shouldPanicOnCopyError(req) {
- p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
- return
- }
- panic(http.ErrAbortHandler)
- }
- res.Body.Close()
- if len(res.Trailer) > 0 {
-
-
-
- if fl, ok := rw.(http.Flusher); ok {
- fl.Flush()
- }
- }
- if len(res.Trailer) == announcedTrailers {
- copyHeader(rw.Header(), res.Trailer)
- return
- }
- for k, vv := range res.Trailer {
- k = http.TrailerPrefix + k
- for _, v := range vv {
- rw.Header().Add(k, v)
- }
- }
- }
- var inOurTests bool
- func shouldPanicOnCopyError(req *http.Request) bool {
- if inOurTests {
-
- return true
- }
- if req.Context().Value(http.ServerContextKey) != nil {
-
-
- return true
- }
-
-
- return false
- }
- func removeConnectionHeaders(h http.Header) {
- for _, f := range h["Connection"] {
- for _, sf := range strings.Split(f, ",") {
- if sf = textproto.TrimString(sf); sf != "" {
- h.Del(sf)
- }
- }
- }
- }
- func (p *ReverseProxy) flushInterval(res *http.Response) time.Duration {
- resCT := res.Header.Get("Content-Type")
-
-
- if resCT == "text/event-stream" {
- return -1
- }
-
- if res.ContentLength == -1 {
- return -1
- }
- return p.FlushInterval
- }
- func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader, flushInterval time.Duration) error {
- if flushInterval != 0 {
- if wf, ok := dst.(writeFlusher); ok {
- mlw := &maxLatencyWriter{
- dst: wf,
- latency: flushInterval,
- }
- defer mlw.stop()
-
- mlw.flushPending = true
- mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
- dst = mlw
- }
- }
- var buf []byte
- if p.BufferPool != nil {
- buf = p.BufferPool.Get()
- defer p.BufferPool.Put(buf)
- }
- _, err := p.copyBuffer(dst, src, buf)
- return err
- }
- func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
- if len(buf) == 0 {
- buf = make([]byte, 32*1024)
- }
- var written int64
- for {
- nr, rerr := src.Read(buf)
- if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
- p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
- }
- if nr > 0 {
- nw, werr := dst.Write(buf[:nr])
- if nw > 0 {
- written += int64(nw)
- }
- if werr != nil {
- return written, werr
- }
- if nr != nw {
- return written, io.ErrShortWrite
- }
- }
- if rerr != nil {
- if rerr == io.EOF {
- rerr = nil
- }
- return written, rerr
- }
- }
- }
- func (p *ReverseProxy) logf(format string, args ...interface{}) {
- if p.ErrorLog != nil {
- p.ErrorLog.Printf(format, args...)
- } else {
- log.Printf(format, args...)
- }
- }
- type writeFlusher interface {
- io.Writer
- http.Flusher
- }
- type maxLatencyWriter struct {
- dst writeFlusher
- latency time.Duration
- mu sync.Mutex
- t *time.Timer
- flushPending bool
- }
- func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- n, err = m.dst.Write(p)
- if m.latency < 0 {
- m.dst.Flush()
- return
- }
- if m.flushPending {
- return
- }
- if m.t == nil {
- m.t = time.AfterFunc(m.latency, m.delayedFlush)
- } else {
- m.t.Reset(m.latency)
- }
- m.flushPending = true
- return
- }
- func (m *maxLatencyWriter) delayedFlush() {
- m.mu.Lock()
- defer m.mu.Unlock()
- if !m.flushPending {
- return
- }
- m.dst.Flush()
- m.flushPending = false
- }
- func (m *maxLatencyWriter) stop() {
- m.mu.Lock()
- defer m.mu.Unlock()
- m.flushPending = false
- if m.t != nil {
- m.t.Stop()
- }
- }
- func upgradeType(h http.Header) string {
- if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
- return ""
- }
- return strings.ToLower(h.Get("Upgrade"))
- }
- func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
- reqUpType := upgradeType(req.Header)
- resUpType := upgradeType(res.Header)
- if reqUpType != resUpType {
- p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
- return
- }
- hj, ok := rw.(http.Hijacker)
- if !ok {
- p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
- return
- }
- backConn, ok := res.Body.(io.ReadWriteCloser)
- if !ok {
- p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
- return
- }
- backConnCloseCh := make(chan bool)
- go func() {
-
-
- select {
- case <-req.Context().Done():
- case <-backConnCloseCh:
- }
- backConn.Close()
- }()
- defer close(backConnCloseCh)
- conn, brw, err := hj.Hijack()
- if err != nil {
- p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", err))
- return
- }
- defer conn.Close()
- copyHeader(rw.Header(), res.Header)
- res.Header = rw.Header()
- res.Body = nil
- if err := res.Write(brw); err != nil {
- p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
- return
- }
- if err := brw.Flush(); err != nil {
- p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
- return
- }
- errc := make(chan error, 1)
- spc := switchProtocolCopier{user: conn, backend: backConn}
- go spc.copyToBackend(errc)
- go spc.copyFromBackend(errc)
- <-errc
- return
- }
- type switchProtocolCopier struct {
- user, backend io.ReadWriter
- }
- func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
- _, err := io.Copy(c.user, c.backend)
- errc <- err
- }
- func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
- _, err := io.Copy(c.backend, c.user)
- errc <- err
- }
|