wireproxy/http.go
Evsyukov Denis a2d7aecb6f
fix: improvements in memory consumption (#100)
* fix: must close the connection after processing

I think it should help to close #80

* feat: migration to github.com/things-go/go-socks5

- preallocate config slices
- not used interfaces in consumer
- do not allocate new variables in loops

* feat: close connection after full processing

* feat: correct process sigint signal

* feat: improve build system

* fix: http proxy

* feat: update golangci-lint-action to v3.7.0

* feat: correct process routines

* fix: close http conn correctly

* feat: update golangci-lint-action to v4

* fix: goreleaser used clean now
2024-02-11 12:45:43 +00:00

162 lines
3.4 KiB
Go

package wireproxy
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"io"
"log"
"net"
"net/http"
"strings"
"github.com/sourcegraph/conc"
)
const proxyAuthHeaderKey = "Proxy-Authorization"
type HTTPServer struct {
config *HTTPConfig
auth CredentialValidator
dial func(network, address string) (net.Conn, error)
authRequired bool
}
func (s *HTTPServer) authenticate(req *http.Request) (int, error) {
if !s.authRequired {
return 0, nil
}
auth := req.Header.Get(proxyAuthHeaderKey)
if auth != "" {
enc := strings.TrimPrefix(auth, "Basic ")
str, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return http.StatusNotAcceptable, fmt.Errorf("decode username and password failed: %w", err)
}
pairs := bytes.SplitN(str, []byte(":"), 2)
if len(pairs) != 2 {
return http.StatusLengthRequired, fmt.Errorf("username and password format invalid")
}
if s.auth.Valid(string(pairs[0]), string(pairs[1])) {
return 0, nil
}
return http.StatusUnauthorized, fmt.Errorf("username and password not matching")
}
return http.StatusProxyAuthRequired, fmt.Errorf(http.StatusText(http.StatusProxyAuthRequired))
}
func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn, err error) {
addr := req.Host
if !strings.Contains(addr, ":") {
port := "443"
addr = net.JoinHostPort(addr, port)
}
peer, err = s.dial("tcp", addr)
if err != nil {
return peer, fmt.Errorf("tun tcp dial failed: %w", err)
}
_, err = conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
if err != nil {
_ = peer.Close()
peer = nil
}
return
}
func (s *HTTPServer) handle(req *http.Request) (peer net.Conn, err error) {
addr := req.Host
if !strings.Contains(addr, ":") {
port := "80"
addr = net.JoinHostPort(addr, port)
}
peer, err = s.dial("tcp", addr)
if err != nil {
return peer, fmt.Errorf("tun tcp dial failed: %w", err)
}
err = req.Write(peer)
if err != nil {
_ = peer.Close()
peer = nil
return peer, fmt.Errorf("conn write failed: %w", err)
}
return
}
func (s *HTTPServer) serve(conn net.Conn) {
var rd = bufio.NewReader(conn)
req, err := http.ReadRequest(rd)
if err != nil {
log.Printf("read request failed: %s\n", err)
return
}
code, err := s.authenticate(req)
if err != nil {
_ = responseWith(req, code).Write(conn)
log.Println(err)
return
}
var peer net.Conn
switch req.Method {
case http.MethodConnect:
peer, err = s.handleConn(req, conn)
case http.MethodGet:
peer, err = s.handle(req)
default:
_ = responseWith(req, http.StatusMethodNotAllowed).Write(conn)
log.Printf("unsupported protocol: %s\n", req.Method)
return
}
if err != nil {
log.Printf("dial proxy failed: %s\n", err)
return
}
if peer == nil {
log.Println("dial proxy failed: peer nil")
return
}
go func() {
wg := conc.NewWaitGroup()
wg.Go(func() {
_, err = io.Copy(conn, peer)
_ = conn.Close()
})
wg.Go(func() {
_, err = io.Copy(peer, conn)
_ = peer.Close()
})
wg.Wait()
}()
}
// ListenAndServe is used to create a listener and serve on it
func (s *HTTPServer) ListenAndServe(network, addr string) error {
server, err := net.Listen(network, addr)
if err != nil {
return fmt.Errorf("listen tcp failed: %w", err)
}
defer func(server net.Listener) {
_ = server.Close()
}(server)
for {
conn, err := server.Accept()
if err != nil {
return fmt.Errorf("accept request failed: %w", err)
}
go func(conn net.Conn) {
s.serve(conn)
}(conn)
}
}