tproxy-utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "github.com/asaskevich/govalidator"
  8. "github.com/elico/go-linux-tproxy"
  9. )
  10. // GlobalHTTPClients the map which hold the http client for use by tproxy
  11. var GlobalHTTPClients = map[string]*http.Client{}
  12. func noRedirect(req *http.Request, via []*http.Request) error {
  13. return errors.New("Don't redirect")
  14. }
  15. // CreateTproxyHTTPClient is creating a uniqe http client per client source IP addres
  16. func CreateTproxyHTTPClient(srcIP string) *http.Client {
  17. var netTransport = &http.Transport{
  18. Dial: (func(network, addr string) (net.Conn, error) {
  19. // Resolve address
  20. //if the address is an IP
  21. host, port, err := net.SplitHostPort(addr)
  22. if err != nil {
  23. return nil, err
  24. }
  25. switch {
  26. case govalidator.IsIP(host):
  27. srvConn, err := tproxy.TCPDial(srcIP, addr)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return srvConn, nil
  32. case govalidator.IsDNSName(host):
  33. ips, err := net.LookupIP(host)
  34. if err != nil {
  35. return nil, err
  36. }
  37. for i, ip := range ips {
  38. srvConn, err := tproxy.TCPDial(srcIP, net.JoinHostPort(ip.String(), port))
  39. if err != nil {
  40. fmt.Println(err)
  41. if i == len(ips) {
  42. return srvConn, nil
  43. }
  44. continue
  45. }
  46. fmt.Println("returning a srvconn")
  47. return srvConn, nil
  48. }
  49. srvConn, err := tproxy.TCPDial(srcIP, addr)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return srvConn, nil
  54. }
  55. return nil, nil
  56. }),
  57. }
  58. client := &http.Client{Transport: netTransport, CheckRedirect: noRedirect}
  59. return client
  60. }