Compare commits

..

8 Commits

@ -1,14 +1,19 @@
package main package main
import ( import (
"bufio"
"bytes"
"fmt" "fmt"
auth "github.com/fangdingjun/go-http-auth"
"io" "io"
"log" "log"
"net" "net"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/fangdingjun/gnutls"
auth "github.com/fangdingjun/go-http-auth"
nghttp2 "github.com/fangdingjun/nghttp2-go"
) )
// handler process the proxy request first(if enabled) // handler process the proxy request first(if enabled)
@ -27,7 +32,7 @@ var defaultTransport http.RoundTripper = &http.Transport{
IdleConnTimeout: 30 * time.Second, IdleConnTimeout: 30 * time.Second,
MaxIdleConnsPerHost: 3, MaxIdleConnsPerHost: 3,
DisableKeepAlives: true, DisableKeepAlives: true,
ResponseHeaderTimeout: 2 * time.Second, ResponseHeaderTimeout: 10 * time.Second,
} }
// ServeHTTP implements the http.Handler interface // ServeHTTP implements the http.Handler interface
@ -95,7 +100,10 @@ func (h *handler) handleHTTP(w http.ResponseWriter, r *http.Request) {
r.Body = nil r.Body = nil
} }
} }
if r.Method == http.MethodPost && r.ContentLength == 0 {
r.Body = http.NoBody
}
//log.Println("content-length", r.Header.Get("content-length"))
resp, err = defaultTransport.RoundTrip(r) resp, err = defaultTransport.RoundTrip(r)
if err != nil { if err != nil {
log.Printf("RoundTrip: %s", err) log.Printf("RoundTrip: %s", err)
@ -109,9 +117,15 @@ func (h *handler) handleHTTP(w http.ResponseWriter, r *http.Request) {
hdr := w.Header() hdr := w.Header()
resp.Header.Del("connection")
for k, v := range resp.Header { for k, v := range resp.Header {
_k := strings.ToLower(k)
if _k == "connection" || _k == "transfer-encoding" ||
_k == "keep-alive" || _k == "upgrade" || _k == "te" {
continue
}
if resp.StatusCode == 204 && _k == "content-length" {
continue
}
for _, v1 := range v { for _, v1 := range v {
hdr.Add(k, v1) hdr.Add(k, v1)
} }
@ -121,21 +135,11 @@ func (h *handler) handleHTTP(w http.ResponseWriter, r *http.Request) {
io.Copy(w, resp.Body) io.Copy(w, resp.Body)
} }
type flushWriter struct {
w io.Writer
}
func (fw flushWriter) Write(buf []byte) (int, error) {
n, err := fw.w.Write(buf)
fw.w.(http.Flusher).Flush()
return n, err
}
func (h *handler) handleCONNECT(w http.ResponseWriter, r *http.Request) { func (h *handler) handleCONNECT(w http.ResponseWriter, r *http.Request) {
host := r.RequestURI host := r.RequestURI
if r.ProtoMajor == 2 { if r.ProtoMajor == 2 {
host = r.URL.Host host = r.Host
} }
if !strings.Contains(host, ":") { if !strings.Contains(host, ":") {
@ -156,7 +160,12 @@ func (h *handler) handleCONNECT(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 1 { if r.ProtoMajor == 1 {
// HTTP/1.1 // HTTP/1.1
hj, _ := w.(http.Hijacker) hj, ok := w.(http.Hijacker)
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
conn1, _, _ := hj.Hijack() conn1, _, _ := hj.Hijack()
fmt.Fprintf(conn1, "%s 200 connection established\r\n\r\n", r.Proto) fmt.Fprintf(conn1, "%s 200 connection established\r\n\r\n", r.Proto)
@ -176,7 +185,7 @@ func (h *handler) handleCONNECT(w http.ResponseWriter, r *http.Request) {
defer conn.Close() defer conn.Close()
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush() //w.(http.Flusher).Flush()
ch := make(chan int, 2) ch := make(chan int, 2)
go func() { go func() {
@ -185,7 +194,7 @@ func (h *handler) handleCONNECT(w http.ResponseWriter, r *http.Request) {
}() }()
go func() { go func() {
io.Copy(flushWriter{w}, conn) io.Copy(w, conn)
ch <- 1 ch <- 1
}() }()
@ -240,3 +249,107 @@ func pipeAndClose(r1, r2 io.ReadWriteCloser) {
<-ch <-ch
} }
func handleHTTPClient(c net.Conn, handler http.Handler) {
tlsconn := c.(*gnutls.Conn)
if err := tlsconn.Handshake(); err != nil {
log.Println(err)
return
}
state := tlsconn.ConnectionState()
if state.NegotiatedProtocol == "h2" {
h2conn, err := nghttp2.Server(tlsconn, handler)
if err != nil {
log.Println(err)
}
h2conn.Run()
h2conn = nil
return
}
defer c.Close()
r := bufio.NewReader(tlsconn)
buf := new(bytes.Buffer)
for {
req, err := http.ReadRequest(r)
if err != nil {
return
}
addr := tlsconn.RemoteAddr().String()
req.RemoteAddr = addr
rh := &responseHandler{
c: tlsconn,
header: http.Header{},
buf: buf,
}
handler.ServeHTTP(rh, req)
rh.Write(nil)
rh.buf.WriteTo(rh.c)
if req.Body != nil {
req.Body.Close()
}
}
}
type responseHandler struct {
c net.Conn
statusCode int
header http.Header
responseSend bool
w io.Writer
buf *bytes.Buffer
}
func (r *responseHandler) WriteHeader(statusCode int) {
if r.responseSend {
return
}
r.buf.Reset()
r.statusCode = statusCode
cl := r.header.Get("content-length")
te := r.header.Get("transfer-encoding")
if cl == "" || te != "" {
if te == "" {
r.header.Set("transfer-encoding", "chunked")
}
r.w = &chunkWriter{r.buf}
} else {
r.w = r.buf
}
fmt.Fprintf(r.buf, "HTTP/1.1 %d %s\r\n", statusCode,
http.StatusText(statusCode))
for k, v := range r.header {
fmt.Fprintf(r.buf, "%s: %s\r\n", strings.Title(k), strings.Join(v, ","))
}
fmt.Fprintf(r.buf, "\r\n")
r.responseSend = true
}
func (r *responseHandler) Header() http.Header {
return r.header
}
func (r *responseHandler) Write(buf []byte) (int, error) {
if !r.responseSend {
r.WriteHeader(http.StatusOK)
}
n, err := r.w.Write(buf)
if r.buf.Len() > 2048 {
r.buf.WriteTo(r.c)
}
return n, err
}
var _ http.ResponseWriter = &responseHandler{}
type chunkWriter struct {
w io.Writer
}
func (cw *chunkWriter) Write(buf []byte) (int, error) {
n := len(buf)
if n == 0 {
return fmt.Fprintf(cw.w, "0\r\n\r\n")
}
return fmt.Fprintf(cw.w, "%x\r\n%s\r\n", n, string(buf))
}

@ -15,29 +15,20 @@ usage example
*/ */
import ( import (
"crypto/tls"
"flag" "flag"
"fmt" "fmt"
"golang.org/x/net/http2"
"io" "io"
"io/ioutil"
"log" "log"
"net" "net"
"net/http" "net/http"
"net/http/httputil" _ "net/http/pprof"
"os" "os"
"sync" "sync"
"time" "time"
)
type clientConn struct { "github.com/fangdingjun/gnutls"
host string "github.com/fangdingjun/nghttp2-go"
port string )
hostname string
transport *http2.Transport
conn *http2.ClientConn
lock *sync.Mutex
}
type timeoutConn struct { type timeoutConn struct {
net.Conn net.Conn
@ -48,61 +39,132 @@ func (tc *timeoutConn) Read(b []byte) (n int, err error) {
if err = tc.Conn.SetReadDeadline(time.Now().Add(tc.timeout)); err != nil { if err = tc.Conn.SetReadDeadline(time.Now().Add(tc.timeout)); err != nil {
return 0, err return 0, err
} }
return tc.Conn.Read(b) n, err = tc.Conn.Read(b)
//log.Printf("read %d bytes from network", n)
return
} }
func (tc *timeoutConn) Write(b []byte) (n int, err error) { func (tc *timeoutConn) Write(b []byte) (n int, err error) {
if err = tc.Conn.SetWriteDeadline(time.Now().Add(tc.timeout)); err != nil { if err = tc.Conn.SetWriteDeadline(time.Now().Add(tc.timeout)); err != nil {
return 0, err return 0, err
} }
return tc.Conn.Write(b) n, err = tc.Conn.Write(b)
//log.Printf("write %d bytes to network", n)
return
} }
type handler struct { type handler struct {
transport *http2.Transport h2conn *nghttp2.Conn
addr string
hostname string
insecure bool
lock *sync.Mutex
} }
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h *handler) createConnection() (*nghttp2.Conn, error) {
if debug { log.Println("create connection to ", h.addr)
req, _ := httputil.DumpRequest(r, false) c, err := net.DialTimeout("tcp", h.addr, 5*time.Second)
log.Printf("%s", string(req)) if err != nil {
return nil, err
} }
conn, err := gnutls.Client(
if r.Method == http.MethodConnect { &timeoutConn{c, 20 * time.Second},
h.handleConnect(w, r) &gnutls.Config{
} else { ServerName: h.hostname,
h.handleHTTP(w, r) InsecureSkipVerify: h.insecure,
NextProtos: []string{"h2"},
})
if err != nil {
return nil, err
}
if err := conn.Handshake(); err != nil {
return nil, err
} }
client, err := nghttp2.Client(conn)
if err != nil {
return nil, err
}
return client, nil
} }
func (h *handler) handleConnect(w http.ResponseWriter, r *http.Request) { func (h *handler) getConn() (*nghttp2.Conn, error) {
pr, pw := io.Pipe() h.lock.Lock()
defer h.lock.Unlock()
defer pr.Close() if h.h2conn != nil {
defer pw.Close() if h.h2conn.CanTakeNewRequest() {
return h.h2conn, nil
}
h.h2conn.Close()
}
r.Body = ioutil.NopCloser(pr) for i := 0; i < 2; i++ {
r.URL.Scheme = "https" h2conn, err := h.createConnection()
if err == nil {
h.h2conn = h2conn
return h2conn, nil
}
}
return nil, fmt.Errorf("create conn failed")
}
r.Header.Del("proxy-connection") func (h *handler) checkError() {
h.lock.Lock()
defer h.lock.Unlock()
resp, err := h.transport.RoundTrip(r) if h.h2conn == nil {
if err != nil {
log.Printf("roundtrip: %s", err)
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, "%s", err)
return return
} }
defer resp.Body.Close() if err := h.h2conn.Error(); err != nil {
//log.Println("connection has error ", err)
h.h2conn.Close()
h.h2conn = nil
}
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if debug { if r.Method == http.MethodConnect {
d, _ := httputil.DumpResponse(resp, false) h.handleConnect(w, r)
log.Printf("%s", string(d)) } else {
h.handleHTTP(w, r)
} }
}
if resp.StatusCode != http.StatusOK { func (h *handler) handleConnect(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(resp.StatusCode) var err error
var h2conn *nghttp2.Conn
var code int
//var resp *http.Response
var cs net.Conn
for i := 0; i < 2; i++ {
h2conn, err = h.getConn()
if err != nil {
log.Println("connection error ", err)
w.WriteHeader(http.StatusBadGateway)
return
}
cs, code, err = h2conn.Connect(r.RequestURI)
if cs != nil {
break
}
h.checkError()
}
if err != nil || cs == nil {
log.Println("send connect error ", err)
h.checkError()
w.WriteHeader(http.StatusBadGateway)
return
}
defer cs.Close()
if code != http.StatusOK {
log.Println("code", code)
w.WriteHeader(code)
return return
} }
@ -120,12 +182,12 @@ func (h *handler) handleConnect(w http.ResponseWriter, r *http.Request) {
ch := make(chan struct{}, 2) ch := make(chan struct{}, 2)
go func() { go func() {
io.Copy(pw, c) io.Copy(cs, c)
ch <- struct{}{} ch <- struct{}{}
}() }()
go func() { go func() {
io.Copy(c, resp.Body) io.Copy(c, cs)
ch <- struct{}{} ch <- struct{}{}
}() }()
@ -133,19 +195,42 @@ func (h *handler) handleConnect(w http.ResponseWriter, r *http.Request) {
} }
func (h *handler) handleHTTP(w http.ResponseWriter, r *http.Request) { func (h *handler) handleHTTP(w http.ResponseWriter, r *http.Request) {
resp, err := h.transport.RoundTrip(r) var err error
if err != nil { var resp *http.Response
log.Println(err) var h2conn *nghttp2.Conn
if r.RequestURI[0] == '/' {
http.DefaultServeMux.ServeHTTP(w, r)
return
}
for i := 0; i < 2; i++ {
h2conn, err = h.getConn()
if err != nil {
//log.Println("create connection ", err)
w.WriteHeader(http.StatusBadGateway)
return
}
resp, err = h2conn.RoundTrip(r)
if resp != nil {
break
}
h.checkError()
}
if err != nil || resp == nil {
log.Println("create request error ", err)
h.checkError()
w.WriteHeader(http.StatusServiceUnavailable) w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprintf(w, "%s", err) fmt.Fprintf(w, "%s", err)
return return
} }
defer resp.Body.Close()
if debug { defer func() {
d, _ := httputil.DumpResponse(resp, false) if resp.Body != nil {
log.Printf("%s", string(d)) resp.Body.Close()
} }
}()
hdr := w.Header() hdr := w.Header()
for k, v := range resp.Header { for k, v := range resp.Header {
@ -158,73 +243,7 @@ func (h *handler) handleHTTP(w http.ResponseWriter, r *http.Request) {
io.Copy(w, resp.Body) io.Copy(w, resp.Body)
} }
func newClientConn(host string, port string, hostname string, t *http2.Transport) *clientConn {
return &clientConn{
host: host,
port: port,
hostname: hostname,
transport: t,
lock: new(sync.Mutex),
}
}
func (p *clientConn) GetClientConn(req *http.Request, addr string) (*http2.ClientConn, error) {
p.lock.Lock()
defer p.lock.Unlock()
if p.conn != nil && p.conn.CanTakeNewRequest() {
return p.conn, nil
}
if debug {
log.Printf("dial to %s:%s", p.host, p.port)
}
c, err := net.Dial("tcp", net.JoinHostPort(p.host, p.port))
if err != nil {
log.Println(err)
return nil, err
}
cc := &timeoutConn{c, time.Duration(idleTimeout) * time.Second}
config := &tls.Config{
ServerName: p.hostname,
NextProtos: []string{"h2"},
InsecureSkipVerify: insecure,
}
conn := tls.Client(cc, config)
if err := conn.Handshake(); err != nil {
log.Println(err)
return nil, err
}
http2conn, err := p.transport.NewClientConn(conn)
if err != nil {
conn.Close()
log.Println(err)
return nil, err
}
p.conn = http2conn
return http2conn, err
}
func (p *clientConn) MarkDead(conn *http2.ClientConn) {
//p.lock.Lock()
//defer p.lock.Unlock()
if debug {
log.Println("mark dead")
}
//p.conn = nil
}
var debug bool
var insecure bool var insecure bool
var idleTimeout int
func main() { func main() {
var addr string var addr string
@ -233,9 +252,7 @@ func main() {
flag.StringVar(&addr, "server", "", "server address") flag.StringVar(&addr, "server", "", "server address")
flag.StringVar(&hostname, "name", "", "server 's SNI name") flag.StringVar(&hostname, "name", "", "server 's SNI name")
flag.StringVar(&listen, "listen", ":8080", "listen address") flag.StringVar(&listen, "listen", ":8080", "listen address")
flag.BoolVar(&debug, "debug", false, "verbose mode")
flag.BoolVar(&insecure, "insecure", false, "insecure mode, not verify the server's certificate") flag.BoolVar(&insecure, "insecure", false, "insecure mode, not verify the server's certificate")
flag.IntVar(&idleTimeout, "idletime", 30, "idle timeout, close connection when no data transfer")
flag.Parse() flag.Parse()
if addr == "" { if addr == "" {
@ -243,31 +260,25 @@ func main() {
os.Exit(-1) os.Exit(-1)
} }
host, port, err := net.SplitHostPort(addr) host, _, err := net.SplitHostPort(addr)
if err != nil { if err != nil {
host = addr host = addr
port = "443" addr = fmt.Sprintf("%s:443", addr)
} }
if hostname == "" { if hostname == "" {
hostname = host hostname = host
} }
transport := &http2.Transport{
AllowHTTP: true,
}
p := newClientConn(host, port, hostname, transport)
transport.ConnPool = p
log.Printf("listen on %s", listen) log.Printf("listen on %s", listen)
if debug { hdr := &handler{
log.Printf("use parent proxy https://%s:%s/", host, port) addr: addr,
log.Printf("server SNI name %s", hostname) hostname: hostname,
insecure: insecure,
lock: new(sync.Mutex),
} }
if err := http.ListenAndServe(listen, hdr); err != nil {
if err := http.ListenAndServe(listen, &handler{transport}); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }

@ -1,12 +1,7 @@
package main package main
import ( import (
"crypto/tls"
"fmt" "fmt"
auth "github.com/fangdingjun/go-http-auth"
"github.com/fangdingjun/gofast"
loghandler "github.com/gorilla/handlers"
"github.com/gorilla/mux"
"io" "io"
"log" "log"
"net" "net"
@ -15,9 +10,14 @@ import (
"net/url" "net/url"
"os" "os"
"regexp" "regexp"
"sync"
//"path/filepath"
"strings" "strings"
"sync"
"github.com/fangdingjun/gnutls"
auth "github.com/fangdingjun/go-http-auth"
"github.com/fangdingjun/gofast"
loghandler "github.com/gorilla/handlers"
"github.com/gorilla/mux"
) )
type logwriter struct { type logwriter struct {
@ -34,7 +34,6 @@ func (lw *logwriter) Write(buf []byte) (int, error) {
func initRouters(cfg conf) { func initRouters(cfg conf) {
logout := os.Stdout logout := os.Stdout
if logfile != "" { if logfile != "" {
fp, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) fp, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil { if err != nil {
@ -49,7 +48,7 @@ func initRouters(cfg conf) {
for _, l := range cfg { for _, l := range cfg {
router := mux.NewRouter() router := mux.NewRouter()
domains := []string{} domains := []string{}
certs := []tls.Certificate{} certs := []*gnutls.Certificate{}
// initial virtual host // initial virtual host
for _, h := range l.Vhost { for _, h := range l.Vhost {
@ -59,7 +58,7 @@ func initRouters(cfg conf) {
} }
domains = append(domains, h2) domains = append(domains, h2)
if h.Cert != "" && h.Key != "" { if h.Cert != "" && h.Key != "" {
if cert, err := tls.LoadX509KeyPair(h.Cert, h.Key); err == nil { if cert, err := gnutls.LoadX509KeyPair(h.Cert, h.Key); err == nil {
certs = append(certs, cert) certs = append(certs, cert)
} else { } else {
log.Fatal(err) log.Fatal(err)
@ -128,27 +127,36 @@ func initRouters(cfg conf) {
} }
if len(certs) > 0 { if len(certs) > 0 {
tlsconfig := &tls.Config{ tlsconfig := &gnutls.Config{
Certificates: certs, Certificates: certs,
NextProtos: []string{"h2", "http/1.1"},
} }
listener, err := gnutls.Listen("tcp", addr, tlsconfig)
tlsconfig.BuildNameToCertificate() if err != nil {
srv := http.Server{
Addr: addr,
TLSConfig: tlsconfig,
Handler: loghandler.CombinedLoggingHandler(w, hdlr),
}
log.Printf("listen https on %s", addr)
if err := srv.ListenAndServeTLS("", ""); err != nil {
log.Fatal(err) log.Fatal(err)
} }
handler := loghandler.CombinedLoggingHandler(w, hdlr)
//handler := hdlr
log.Printf("listen https on %s", addr)
go func() {
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Println(err)
break
}
go handleHTTPClient(conn, handler)
}
}()
} else { } else {
log.Printf("listen http on %s", addr) log.Printf("listen http on %s", addr)
handler := loghandler.CombinedLoggingHandler(w, hdlr)
//handler := hdlr
if err := http.ListenAndServe( if err := http.ListenAndServe(
addr, addr, handler,
loghandler.CombinedLoggingHandler(w, hdlr),
); err != nil { ); err != nil {
log.Fatal(err) log.Fatal(err)
} }

Loading…
Cancel
Save