server_badhttp.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. //go:build go1.20 && !go1.21
  2. package v2raygrpclite
  3. import (
  4. "context"
  5. "fmt"
  6. "net"
  7. "net/url"
  8. "os"
  9. "strings"
  10. "github.com/sagernet/badhttp"
  11. "github.com/sagernet/badhttp2"
  12. "github.com/sagernet/badhttp2/h2c"
  13. "github.com/sagernet/sing-box/adapter"
  14. "github.com/sagernet/sing-box/common/tls"
  15. "github.com/sagernet/sing-box/option"
  16. "github.com/sagernet/sing-box/transport/v2rayhttp"
  17. "github.com/sagernet/sing/common"
  18. E "github.com/sagernet/sing/common/exceptions"
  19. M "github.com/sagernet/sing/common/metadata"
  20. N "github.com/sagernet/sing/common/network"
  21. sHttp "github.com/sagernet/sing/protocol/http"
  22. )
  23. var _ adapter.V2RayServerTransport = (*Server)(nil)
  24. type Server struct {
  25. handler adapter.V2RayServerTransportHandler
  26. errorHandler E.Handler
  27. httpServer *http.Server
  28. h2Server *http2.Server
  29. h2cHandler http.Handler
  30. path string
  31. }
  32. func (s *Server) Network() []string {
  33. return []string{N.NetworkTCP}
  34. }
  35. func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (*Server, error) {
  36. server := &Server{
  37. handler: handler,
  38. path: fmt.Sprintf("/%s/Tun", url.QueryEscape(options.ServiceName)),
  39. h2Server: new(http2.Server),
  40. }
  41. server.httpServer = &http.Server{
  42. Handler: server,
  43. }
  44. server.h2cHandler = h2c.NewHandler(server, server.h2Server)
  45. if tlsConfig != nil {
  46. if len(tlsConfig.NextProtos()) == 0 {
  47. tlsConfig.SetNextProtos([]string{http2.NextProtoTLS})
  48. }
  49. server.httpServer.TLSConfig = tlsConfig
  50. }
  51. return server, nil
  52. }
  53. func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
  54. if request.Method == "PRI" && len(request.Header) == 0 && request.URL.Path == "*" && request.Proto == "HTTP/2.0" {
  55. s.h2cHandler.ServeHTTP(writer, request)
  56. return
  57. }
  58. if request.URL.Path != s.path {
  59. s.fallbackRequest(request.Context(), writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path))
  60. return
  61. }
  62. if request.Method != http.MethodPost {
  63. s.fallbackRequest(request.Context(), writer, request, http.StatusNotFound, E.New("bad method: ", request.Method))
  64. return
  65. }
  66. if ct := request.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/grpc") {
  67. s.fallbackRequest(request.Context(), writer, request, http.StatusNotFound, E.New("bad content type: ", ct))
  68. return
  69. }
  70. writer.Header().Set("Content-Type", "application/grpc")
  71. writer.Header().Set("TE", "trailers")
  72. writer.WriteHeader(http.StatusOK)
  73. var metadata M.Metadata
  74. metadata.Source = sHttp.SourceAddress(v2rayhttp.BadRequest(request))
  75. conn := v2rayhttp.NewHTTP2Wrapper(newGunConn(request.Body, writer, writer.(http.Flusher)))
  76. s.handler.NewConnection(request.Context(), conn, metadata)
  77. conn.CloseWrapper()
  78. }
  79. func (s *Server) fallbackRequest(ctx context.Context, writer http.ResponseWriter, request *http.Request, statusCode int, err error) {
  80. conn := v2rayhttp.NewHTTPConn(request.Body, writer)
  81. fErr := s.handler.FallbackConnection(ctx, &conn, M.Metadata{})
  82. if fErr == nil {
  83. return
  84. } else if fErr == os.ErrInvalid {
  85. fErr = nil
  86. }
  87. writer.WriteHeader(statusCode)
  88. s.handler.NewError(request.Context(), E.Cause(E.Errors(err, E.Cause(fErr, "fallback connection")), "process connection from ", request.RemoteAddr))
  89. }
  90. func (s *Server) Serve(listener net.Listener) error {
  91. if s.httpServer.TLSConfig != nil {
  92. err := http2.ConfigureServer(s.httpServer, s.h2Server)
  93. if err != nil {
  94. return err
  95. }
  96. return s.httpServer.ServeTLS(listener, "", "")
  97. } else {
  98. return s.httpServer.Serve(listener)
  99. }
  100. }
  101. func (s *Server) ServePacket(listener net.PacketConn) error {
  102. return os.ErrInvalid
  103. }
  104. func (s *Server) Close() error {
  105. return common.Close(common.PtrOrNil(s.httpServer))
  106. }