123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513 |
- package dpcore
- import (
- "context"
- "errors"
- "io"
- "log"
- "net"
- "net/http"
- "net/url"
- "strings"
- "time"
- "imuslab.com/zoraxy/mod/dynamicproxy/domainsniff"
- "imuslab.com/zoraxy/mod/dynamicproxy/modh2c"
- "imuslab.com/zoraxy/mod/dynamicproxy/permissionpolicy"
- )
- type ReverseProxy struct {
-
- Timeout time.Duration
-
-
-
-
-
-
- Director func(*http.Request)
-
-
- Transport http.RoundTripper
-
-
-
- FlushInterval time.Duration
-
-
-
-
- ErrorLog *log.Logger
-
-
-
- ModifyResponse func(*http.Response) error
-
- Prepender string
- Verbal bool
-
- }
- type ResponseRewriteRuleSet struct {
-
- ProxyDomain string
- OriginalHost string
- UseTLS bool
- NoCache bool
- PathPrefix string
- UpstreamHeaders [][]string
- DownstreamHeaders [][]string
-
- HostHeaderOverwrite string
- NoRemoveHopByHop bool
-
- Version string
- }
- type requestCanceler interface {
- CancelRequest(req *http.Request)
- }
- type DpcoreOptions struct {
- IgnoreTLSVerification bool
- FlushInterval time.Duration
- UseH2CRoundTripper bool
- }
- func NewDynamicProxyCore(target *url.URL, prepender string, dpcOptions *DpcoreOptions) *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
- }
- }
- thisTransporter := http.DefaultTransport
-
- optimalConcurrentConnection := 32
- thisTransporter.(*http.Transport).MaxIdleConns = optimalConcurrentConnection * 2
- thisTransporter.(*http.Transport).MaxIdleConnsPerHost = optimalConcurrentConnection
- thisTransporter.(*http.Transport).IdleConnTimeout = 30 * time.Second
- thisTransporter.(*http.Transport).MaxConnsPerHost = optimalConcurrentConnection * 2
- thisTransporter.(*http.Transport).DisableCompression = true
- if dpcOptions.IgnoreTLSVerification {
-
- thisTransporter.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
- }
-
- if dpcOptions.UseH2CRoundTripper {
-
- thisTransporter = modh2c.NewH2CRoundTripper()
- }
- return &ReverseProxy{
- Director: director,
- Prepender: prepender,
- FlushInterval: dpcOptions.FlushInterval,
- Verbal: false,
- Transport: thisTransporter,
- }
- }
- 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 copyHeader(dst, src http.Header) {
- for k, vv := range src {
- for _, v := range vv {
- dst.Add(k, v)
- }
- }
- }
- var hopHeaders = []string{
-
- "Proxy-Connection",
- "Keep-Alive",
- "Proxy-Authenticate",
- "Proxy-Authorization",
- "Te",
- "Trailer",
- "Transfer-Encoding",
-
- }
- func (p *ReverseProxy) copyResponse(dst http.ResponseWriter, src io.Reader, flushInterval time.Duration) error {
- var w io.Writer = dst
- if flushInterval != 0 {
- mlw := &maxLatencyWriter{
- dst: dst,
- flush: http.NewResponseController(dst).Flush,
- latency: flushInterval,
- }
- defer mlw.stop()
-
- mlw.flushPending = true
- mlw.t = time.AfterFunc(flushInterval, mlw.delayedFlush)
- w = mlw
- }
- var buf []byte
- _, err := p.copyBuffer(w, 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, 64*1024)
- }
- var written int64
- for {
- nr, rerr := src.Read(buf)
- if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
- p.logf("dpcore 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...)
- }
- }
- func (p *ReverseProxy) ProxyHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) (int, error) {
- transport := p.Transport
- outreq := new(http.Request)
-
- *outreq = *req
- if cn, ok := rw.(http.CloseNotifier); ok {
- if requestCanceler, ok := transport.(requestCanceler); ok {
-
-
- reqDone := make(chan struct{})
- defer close(reqDone)
- clientGone := cn.CloseNotify()
- go func() {
- select {
- case <-clientGone:
- requestCanceler.CancelRequest(outreq)
- case <-reqDone:
- }
- }()
- }
- }
- p.Director(outreq)
- outreq.Close = false
-
- if rrr.HostHeaderOverwrite != "" {
-
- outreq.Host = rrr.HostHeaderOverwrite
- } else if !(rrr.UseTLS && isExternalDomainName(rrr.ProxyDomain)) {
-
- outreq.Host = rrr.OriginalHost
- }
-
- outreq.Header = make(http.Header)
- copyHeader(outreq.Header, req.Header)
-
- if !rrr.NoRemoveHopByHop {
- removeHeaders(outreq.Header, rrr.NoCache)
- }
-
- addXForwardedForHeader(outreq)
-
- injectUserDefinedHeaders(outreq.Header, rrr.UpstreamHeaders)
-
- rewriteUserAgent(outreq.Header, "Zoraxy/"+rrr.Version)
-
- if domainsniff.IsProxmox(req) {
- outreq.TransferEncoding = []string{"identity"}
- }
- res, err := transport.RoundTrip(outreq)
- if err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
-
- return http.StatusBadGateway, err
- }
-
- if !rrr.NoRemoveHopByHop {
- removeHeaders(res.Header, rrr.NoCache)
- }
-
- if _, ok := res.Header["User-Agent"]; ok {
-
- res.Header.Del("User-Agent")
- }
- if p.ModifyResponse != nil {
- if err := p.ModifyResponse(res); err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
-
- return http.StatusBadGateway, err
- }
- }
-
- res.Header.Set("x-proxy-by", "zoraxy/"+rrr.Version)
-
- if res.Header.Get("Location") != "" {
- locationRewrite := res.Header.Get("Location")
- originLocation := res.Header.Get("Location")
- res.Header.Set("zr-origin-location", originLocation)
- if strings.HasPrefix(originLocation, "http://") || strings.HasPrefix(originLocation, "https://") {
-
-
- lr, err := replaceLocationHost(locationRewrite, rrr, req.TLS != nil)
- if err == nil {
- locationRewrite = lr
- }
- } else if strings.HasPrefix(originLocation, "/") && rrr.PathPrefix != "" {
-
-
- locationRewrite = strings.TrimSuffix(rrr.PathPrefix, "/") + originLocation
- } else {
-
- }
-
- res.Header.Set("Location", locationRewrite)
- }
-
- injectUserDefinedHeaders(res.Header, rrr.DownstreamHeaders)
-
- copyHeader(rw.Header(), res.Header)
-
- permissionpolicy.InjectPermissionPolicyHeader(rw, nil)
-
- if len(res.Trailer) > 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)
- if len(res.Trailer) > 0 {
-
-
-
- if fl, ok := rw.(http.Flusher); ok {
- fl.Flush()
- }
- }
-
- flushInterval := p.getFlushInterval(req, res)
- p.copyResponse(rw, res.Body, flushInterval)
-
- res.Body.Close()
- copyHeader(rw.Header(), res.Trailer)
- return res.StatusCode, nil
- }
- func (p *ReverseProxy) ProxyHTTPS(rw http.ResponseWriter, req *http.Request) (int, error) {
- hij, ok := rw.(http.Hijacker)
- if !ok {
- p.logf("http server does not support hijacker")
- return http.StatusNotImplemented, errors.New("http server does not support hijacker")
- }
- clientConn, _, err := hij.Hijack()
- if err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
- return http.StatusInternalServerError, err
- }
- proxyConn, err := net.Dial("tcp", req.URL.Host)
- if err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
- return http.StatusInternalServerError, err
- }
-
-
-
-
- deadline := time.Now()
- if p.Timeout == 0 {
- deadline = deadline.Add(time.Minute * 5)
- } else {
- deadline = deadline.Add(p.Timeout)
- }
- err = clientConn.SetDeadline(deadline)
- if err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
- return http.StatusGatewayTimeout, err
- }
- err = proxyConn.SetDeadline(deadline)
- if err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
- return http.StatusGatewayTimeout, err
- }
- _, err = clientConn.Write([]byte("HTTP/1.0 200 OK\r\n\r\n"))
- if err != nil {
- if p.Verbal {
- p.logf("http: proxy error: %v", err)
- }
- return http.StatusInternalServerError, err
- }
- go func() {
- io.Copy(clientConn, proxyConn)
- clientConn.Close()
- proxyConn.Close()
- }()
- io.Copy(proxyConn, clientConn)
- proxyConn.Close()
- clientConn.Close()
- return http.StatusOK, nil
- }
- func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request, rrr *ResponseRewriteRuleSet) (int, error) {
- if req.Method == "CONNECT" {
- return p.ProxyHTTPS(rw, req)
- } else {
- return p.ProxyHTTP(rw, req, rrr)
- }
- }
|