http.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package outbound
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/tls"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "net/http"
  12. "strconv"
  13. N "github.com/metacubex/mihomo/common/net"
  14. "github.com/metacubex/mihomo/component/ca"
  15. "github.com/metacubex/mihomo/component/dialer"
  16. "github.com/metacubex/mihomo/component/proxydialer"
  17. C "github.com/metacubex/mihomo/constant"
  18. )
  19. type Http struct {
  20. *Base
  21. user string
  22. pass string
  23. tlsConfig *tls.Config
  24. option *HttpOption
  25. }
  26. type HttpOption struct {
  27. BasicOption
  28. Name string `proxy:"name"`
  29. Server string `proxy:"server"`
  30. Port int `proxy:"port"`
  31. UserName string `proxy:"username,omitempty"`
  32. Password string `proxy:"password,omitempty"`
  33. TLS bool `proxy:"tls,omitempty"`
  34. SNI string `proxy:"sni,omitempty"`
  35. SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
  36. Fingerprint string `proxy:"fingerprint,omitempty"`
  37. Headers map[string]string `proxy:"headers,omitempty"`
  38. }
  39. // StreamConnContext implements C.ProxyAdapter
  40. func (h *Http) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
  41. if h.tlsConfig != nil {
  42. cc := tls.Client(c, h.tlsConfig)
  43. err := cc.HandshakeContext(ctx)
  44. c = cc
  45. if err != nil {
  46. return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
  47. }
  48. }
  49. if err := h.shakeHand(metadata, c); err != nil {
  50. return nil, err
  51. }
  52. return c, nil
  53. }
  54. // DialContext implements C.ProxyAdapter
  55. func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
  56. return h.DialContextWithDialer(ctx, dialer.NewDialer(h.Base.DialOptions(opts...)...), metadata)
  57. }
  58. // DialContextWithDialer implements C.ProxyAdapter
  59. func (h *Http) DialContextWithDialer(ctx context.Context, dialer C.Dialer, metadata *C.Metadata) (_ C.Conn, err error) {
  60. if len(h.option.DialerProxy) > 0 {
  61. dialer, err = proxydialer.NewByName(h.option.DialerProxy, dialer)
  62. if err != nil {
  63. return nil, err
  64. }
  65. }
  66. c, err := dialer.DialContext(ctx, "tcp", h.addr)
  67. if err != nil {
  68. return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
  69. }
  70. N.TCPKeepAlive(c)
  71. defer func(c net.Conn) {
  72. safeConnClose(c, err)
  73. }(c)
  74. c, err = h.StreamConnContext(ctx, c, metadata)
  75. if err != nil {
  76. return nil, err
  77. }
  78. return NewConn(c, h), nil
  79. }
  80. // SupportWithDialer implements C.ProxyAdapter
  81. func (h *Http) SupportWithDialer() C.NetWork {
  82. return C.TCP
  83. }
  84. func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
  85. addr := metadata.RemoteAddress()
  86. HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
  87. tempHeaders := map[string]string{
  88. "Host": addr,
  89. "User-Agent": "Go-http-client/1.1",
  90. "Proxy-Connection": "Keep-Alive",
  91. }
  92. for key, value := range h.option.Headers {
  93. tempHeaders[key] = value
  94. }
  95. if h.user != "" && h.pass != "" {
  96. auth := h.user + ":" + h.pass
  97. tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
  98. }
  99. for key, value := range tempHeaders {
  100. HeaderString += key + ": " + value + "\r\n"
  101. }
  102. HeaderString += "\r\n"
  103. _, err := rw.Write([]byte(HeaderString))
  104. if err != nil {
  105. return err
  106. }
  107. resp, err := http.ReadResponse(bufio.NewReader(rw), nil)
  108. if err != nil {
  109. return err
  110. }
  111. if resp.StatusCode == http.StatusOK {
  112. return nil
  113. }
  114. if resp.StatusCode == http.StatusProxyAuthRequired {
  115. return errors.New("HTTP need auth")
  116. }
  117. if resp.StatusCode == http.StatusMethodNotAllowed {
  118. return errors.New("CONNECT method not allowed by proxy")
  119. }
  120. if resp.StatusCode >= http.StatusInternalServerError {
  121. return errors.New(resp.Status)
  122. }
  123. return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
  124. }
  125. func NewHttp(option HttpOption) (*Http, error) {
  126. var tlsConfig *tls.Config
  127. if option.TLS {
  128. sni := option.Server
  129. if option.SNI != "" {
  130. sni = option.SNI
  131. }
  132. var err error
  133. tlsConfig, err = ca.GetSpecifiedFingerprintTLSConfig(&tls.Config{
  134. InsecureSkipVerify: option.SkipCertVerify,
  135. ServerName: sni,
  136. }, option.Fingerprint)
  137. if err != nil {
  138. return nil, err
  139. }
  140. }
  141. return &Http{
  142. Base: &Base{
  143. name: option.Name,
  144. addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
  145. tp: C.Http,
  146. tfo: option.TFO,
  147. mpTcp: option.MPTCP,
  148. iface: option.Interface,
  149. rmark: option.RoutingMark,
  150. prefer: C.NewDNSPrefer(option.IPVersion),
  151. },
  152. user: option.UserName,
  153. pass: option.Password,
  154. tlsConfig: tlsConfig,
  155. option: &option,
  156. }, nil
  157. }