You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

316 lines
6.4 KiB
Go

4 years ago
package proxy
import (
4 years ago
"bytes"
"context"
"crypto/x509"
4 years ago
"io"
"net"
4 years ago
"net/http"
4 years ago
2 years ago
log "github.com/sirupsen/logrus"
4 years ago
)
4 years ago
type Options struct {
2 years ago
Debug int
4 years ago
Addr string
StreamLargeBodies int64 // 当请求或响应体大于此字节时,转为 stream 模式
SslInsecure bool
3 years ago
CaRootPath string
2 years ago
Upstream string
4 years ago
}
4 years ago
4 years ago
type Proxy struct {
2 years ago
Opts *Options
Version string
Addons []Addon
2 years ago
server *http.Server
interceptor *middle
}
2 years ago
func NewProxy(opts *Options) (*Proxy, error) {
if opts.StreamLargeBodies <= 0 {
opts.StreamLargeBodies = 1024 * 1024 * 5 // default: 5mb
}
2 years ago
proxy := &Proxy{
Opts: opts,
2 years ago
Version: "1.3.3",
2 years ago
Addons: make([]Addon, 0),
}
2 years ago
proxy.server = &http.Server{
Addr: opts.Addr,
Handler: proxy,
ConnContext: func(ctx context.Context, c net.Conn) context.Context {
2 years ago
connCtx := newConnContext(c, proxy)
for _, addon := range proxy.Addons {
2 years ago
addon.ClientConnected(connCtx.ClientConn)
}
2 years ago
c.(*wrapClientConn).connCtx = connCtx
return context.WithValue(ctx, connContextKey, connCtx)
},
4 years ago
}
2 years ago
interceptor, err := newMiddle(proxy)
4 years ago
if err != nil {
return nil, err
}
2 years ago
proxy.interceptor = interceptor
4 years ago
return proxy, nil
4 years ago
}
2 years ago
func (proxy *Proxy) AddAddon(addon Addon) {
4 years ago
proxy.Addons = append(proxy.Addons, addon)
}
func (proxy *Proxy) Start() error {
addr := proxy.server.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
go proxy.interceptor.start()
log.Infof("Proxy start listen at %v\n", proxy.server.Addr)
pln := &wrapListener{
Listener: ln,
proxy: proxy,
}
return proxy.server.Serve(pln)
}
func (proxy *Proxy) Close() error {
err := proxy.server.Close()
proxy.interceptor.close()
return err
}
func (proxy *Proxy) Shutdown(ctx context.Context) error {
err := proxy.server.Shutdown(ctx)
proxy.interceptor.close()
return err
}
func (proxy *Proxy) ServeHTTP(res http.ResponseWriter, req *http.Request) {
if req.Method == "CONNECT" {
proxy.handleConnect(res, req)
return
}
2 years ago
log := log.WithFields(log.Fields{
"in": "Proxy.ServeHTTP",
4 years ago
"url": req.URL,
"method": req.Method,
4 years ago
})
if !req.URL.IsAbs() || req.URL.Host == "" {
res.WriteHeader(400)
_, err := io.WriteString(res, "此为代理服务器,不能直接发起请求")
if err != nil {
4 years ago
log.Error(err)
4 years ago
}
return
}
4 years ago
2 years ago
reply := func(response *Response, body io.Reader) {
4 years ago
if response.Header != nil {
for key, value := range response.Header {
for _, v := range value {
res.Header().Add(key, v)
}
}
}
if response.close {
res.Header().Add("Connection", "close")
}
4 years ago
res.WriteHeader(response.StatusCode)
if body != nil {
_, err := io.Copy(res, body)
4 years ago
if err != nil {
2 years ago
logErr(log, err)
4 years ago
}
}
if response.BodyReader != nil {
_, err := io.Copy(res, response.BodyReader)
if err != nil {
logErr(log, err)
}
}
if response.Body != nil && len(response.Body) > 0 {
_, err := res.Write(response.Body)
if err != nil {
logErr(log, err)
4 years ago
}
}
}
// when addons panic
defer func() {
if err := recover(); err != nil {
log.Warnf("Recovered: %v\n", err)
}
}()
2 years ago
f := newFlow()
f.Request = newRequest(req)
f.ConnContext = req.Context().Value(connContextKey).(*ConnContext)
defer f.finish()
4 years ago
// trigger addon event Requestheaders
for _, addon := range proxy.Addons {
4 years ago
addon.Requestheaders(f)
if f.Response != nil {
reply(f.Response, nil)
4 years ago
return
}
}
4 years ago
// Read request body
4 years ago
var reqBody io.Reader = req.Body
4 years ago
if !f.Stream {
2 years ago
reqBuf, r, err := readerToBuffer(req.Body, proxy.Opts.StreamLargeBodies)
4 years ago
reqBody = r
if err != nil {
log.Error(err)
res.WriteHeader(502)
return
}
4 years ago
4 years ago
if reqBuf == nil {
log.Warnf("request body size >= %v\n", proxy.Opts.StreamLargeBodies)
4 years ago
f.Stream = true
4 years ago
} else {
4 years ago
f.Request.Body = reqBuf
4 years ago
4 years ago
// trigger addon event Request
4 years ago
for _, addon := range proxy.Addons {
4 years ago
addon.Request(f)
if f.Response != nil {
reply(f.Response, nil)
4 years ago
return
}
}
4 years ago
reqBody = bytes.NewReader(f.Request.Body)
4 years ago
}
}
4 years ago
for _, addon := range proxy.Addons {
reqBody = addon.StreamRequestModifier(f, reqBody)
}
4 years ago
proxyReq, err := http.NewRequest(f.Request.Method, f.Request.URL.String(), reqBody)
if err != nil {
4 years ago
log.Error(err)
res.WriteHeader(502)
return
}
4 years ago
4 years ago
for key, value := range f.Request.Header {
for _, v := range value {
proxyReq.Header.Add(key, v)
}
}
2 years ago
f.ConnContext.initHttpServerConn()
2 years ago
proxyRes, err := f.ConnContext.ServerConn.client.Do(proxyReq)
if err != nil {
2 years ago
logErr(log, err)
res.WriteHeader(502)
return
}
if proxyRes.Close {
f.ConnContext.closeAfterResponse = true
}
defer proxyRes.Body.Close()
4 years ago
2 years ago
f.Response = &Response{
4 years ago
StatusCode: proxyRes.StatusCode,
Header: proxyRes.Header,
close: proxyRes.Close,
4 years ago
}
// trigger addon event Responseheaders
for _, addon := range proxy.Addons {
4 years ago
addon.Responseheaders(f)
if f.Response.Body != nil {
reply(f.Response, nil)
4 years ago
return
}
}
4 years ago
4 years ago
// Read response body
4 years ago
var resBody io.Reader = proxyRes.Body
4 years ago
if !f.Stream {
2 years ago
resBuf, r, err := readerToBuffer(proxyRes.Body, proxy.Opts.StreamLargeBodies)
4 years ago
resBody = r
if err != nil {
log.Error(err)
res.WriteHeader(502)
return
}
if resBuf == nil {
log.Warnf("response body size >= %v\n", proxy.Opts.StreamLargeBodies)
4 years ago
f.Stream = true
4 years ago
} else {
4 years ago
f.Response.Body = resBuf
4 years ago
4 years ago
// trigger addon event Response
4 years ago
for _, addon := range proxy.Addons {
4 years ago
addon.Response(f)
4 years ago
}
}
}
for _, addon := range proxy.Addons {
resBody = addon.StreamResponseModifier(f, resBody)
}
4 years ago
reply(f.Response, resBody)
}
func (proxy *Proxy) handleConnect(res http.ResponseWriter, req *http.Request) {
2 years ago
log := log.WithFields(log.Fields{
"in": "Proxy.handleConnect",
4 years ago
"host": req.Host,
})
conn, err := proxy.interceptor.dial(req)
if err != nil {
4 years ago
log.Error(err)
res.WriteHeader(502)
return
}
defer conn.Close()
4 years ago
cconn, _, err := res.(http.Hijacker).Hijack()
if err != nil {
4 years ago
log.Error(err)
res.WriteHeader(502)
return
}
// cconn.(*net.TCPConn).SetLinger(0) // send RST other than FIN when finished, to avoid TIME_WAIT state
// cconn.(*net.TCPConn).SetKeepAlive(false)
defer cconn.Close()
_, err = io.WriteString(cconn, "HTTP/1.1 200 Connection Established\r\n\r\n")
if err != nil {
4 years ago
log.Error(err)
return
}
transfer(log, conn, cconn)
}
func (proxy *Proxy) GetCertificate() x509.Certificate {
return proxy.interceptor.ca.RootCert
}