github.com/imannamdari/v2ray-core/v5@v5.0.5/proxy/http/server.go (about) 1 package http 2 3 import ( 4 "bufio" 5 "context" 6 "encoding/base64" 7 "io" 8 "net/http" 9 "strings" 10 "time" 11 12 core "github.com/imannamdari/v2ray-core/v5" 13 "github.com/imannamdari/v2ray-core/v5/common" 14 "github.com/imannamdari/v2ray-core/v5/common/buf" 15 "github.com/imannamdari/v2ray-core/v5/common/errors" 16 "github.com/imannamdari/v2ray-core/v5/common/log" 17 "github.com/imannamdari/v2ray-core/v5/common/net" 18 "github.com/imannamdari/v2ray-core/v5/common/protocol" 19 http_proto "github.com/imannamdari/v2ray-core/v5/common/protocol/http" 20 "github.com/imannamdari/v2ray-core/v5/common/session" 21 "github.com/imannamdari/v2ray-core/v5/common/signal" 22 "github.com/imannamdari/v2ray-core/v5/common/task" 23 "github.com/imannamdari/v2ray-core/v5/features/policy" 24 "github.com/imannamdari/v2ray-core/v5/features/routing" 25 "github.com/imannamdari/v2ray-core/v5/transport/internet" 26 ) 27 28 // Server is an HTTP proxy server. 29 type Server struct { 30 config *ServerConfig 31 policyManager policy.Manager 32 } 33 34 // NewServer creates a new HTTP inbound handler. 35 func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) { 36 v := core.MustFromContext(ctx) 37 s := &Server{ 38 config: config, 39 policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), 40 } 41 42 return s, nil 43 } 44 45 func (s *Server) policy() policy.Session { 46 config := s.config 47 p := s.policyManager.ForLevel(config.UserLevel) 48 if config.Timeout > 0 && config.UserLevel == 0 { 49 p.Timeouts.ConnectionIdle = time.Duration(config.Timeout) * time.Second 50 } 51 return p 52 } 53 54 // Network implements proxy.Inbound. 55 func (*Server) Network() []net.Network { 56 return []net.Network{net.Network_TCP, net.Network_UNIX} 57 } 58 59 func isTimeout(err error) bool { 60 nerr, ok := errors.Cause(err).(net.Error) 61 return ok && nerr.Timeout() 62 } 63 64 func parseBasicAuth(auth string) (username, password string, ok bool) { 65 const prefix = "Basic " 66 if !strings.HasPrefix(auth, prefix) { 67 return 68 } 69 c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) 70 if err != nil { 71 return 72 } 73 cs := string(c) 74 s := strings.IndexByte(cs, ':') 75 if s < 0 { 76 return 77 } 78 return cs[:s], cs[s+1:], true 79 } 80 81 type readerOnly struct { 82 io.Reader 83 } 84 85 func (s *Server) Process(ctx context.Context, network net.Network, conn internet.Connection, dispatcher routing.Dispatcher) error { 86 inbound := session.InboundFromContext(ctx) 87 if inbound != nil { 88 inbound.User = &protocol.MemoryUser{ 89 Level: s.config.UserLevel, 90 } 91 } 92 93 reader := bufio.NewReaderSize(readerOnly{conn}, buf.Size) 94 95 Start: 96 if err := conn.SetReadDeadline(time.Now().Add(s.policy().Timeouts.Handshake)); err != nil { 97 newError("failed to set read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) 98 } 99 100 request, err := http.ReadRequest(reader) 101 if err != nil { 102 trace := newError("failed to read http request").Base(err) 103 if errors.Cause(err) != io.EOF && !isTimeout(errors.Cause(err)) { 104 trace.AtWarning() 105 } 106 return trace 107 } 108 109 if len(s.config.Accounts) > 0 { 110 user, pass, ok := parseBasicAuth(request.Header.Get("Proxy-Authorization")) 111 if !ok || !s.config.HasAccount(user, pass) { 112 return common.Error2(conn.Write([]byte("HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"proxy\"\r\n\r\n"))) 113 } 114 if inbound != nil { 115 inbound.User.Email = user 116 } 117 } 118 119 newError("request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]").WriteToLog(session.ExportIDToError(ctx)) 120 if err := conn.SetReadDeadline(time.Time{}); err != nil { 121 newError("failed to clear read deadline").Base(err).WriteToLog(session.ExportIDToError(ctx)) 122 } 123 124 defaultPort := net.Port(80) 125 if strings.EqualFold(request.URL.Scheme, "https") { 126 defaultPort = net.Port(443) 127 } 128 host := request.Host 129 if host == "" { 130 host = request.URL.Host 131 } 132 dest, err := http_proto.ParseHost(host, defaultPort) 133 if err != nil { 134 return newError("malformed proxy host: ", host).AtWarning().Base(err) 135 } 136 ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ 137 From: conn.RemoteAddr(), 138 To: request.URL, 139 Status: log.AccessAccepted, 140 Reason: "", 141 }) 142 143 if strings.EqualFold(request.Method, "CONNECT") { 144 return s.handleConnect(ctx, request, reader, conn, dest, dispatcher) 145 } 146 147 keepAlive := (strings.TrimSpace(strings.ToLower(request.Header.Get("Proxy-Connection"))) == "keep-alive") 148 149 err = s.handlePlainHTTP(ctx, request, conn, dest, dispatcher) 150 if err == errWaitAnother { 151 if keepAlive { 152 goto Start 153 } 154 err = nil 155 } 156 157 return err 158 } 159 160 func (s *Server) handleConnect(ctx context.Context, _ *http.Request, reader *bufio.Reader, conn internet.Connection, dest net.Destination, dispatcher routing.Dispatcher) error { 161 _, err := conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")) 162 if err != nil { 163 return newError("failed to write back OK response").Base(err) 164 } 165 166 plcy := s.policy() 167 ctx, cancel := context.WithCancel(ctx) 168 timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle) 169 170 ctx = policy.ContextWithBufferPolicy(ctx, plcy.Buffer) 171 link, err := dispatcher.Dispatch(ctx, dest) 172 if err != nil { 173 return err 174 } 175 176 if reader.Buffered() > 0 { 177 payload, err := buf.ReadFrom(io.LimitReader(reader, int64(reader.Buffered()))) 178 if err != nil { 179 return err 180 } 181 if err := link.Writer.WriteMultiBuffer(payload); err != nil { 182 return err 183 } 184 reader = nil 185 } 186 187 requestDone := func() error { 188 defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly) 189 190 return buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)) 191 } 192 193 responseDone := func() error { 194 defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) 195 196 v2writer := buf.NewWriter(conn) 197 if err := buf.Copy(link.Reader, v2writer, buf.UpdateActivity(timer)); err != nil { 198 return err 199 } 200 201 return nil 202 } 203 204 closeWriter := task.OnSuccess(requestDone, task.Close(link.Writer)) 205 if err := task.Run(ctx, closeWriter, responseDone); err != nil { 206 common.Interrupt(link.Reader) 207 common.Interrupt(link.Writer) 208 return newError("connection ends").Base(err) 209 } 210 211 return nil 212 } 213 214 var errWaitAnother = newError("keep alive") 215 216 func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, writer io.Writer, dest net.Destination, dispatcher routing.Dispatcher) error { 217 if !s.config.AllowTransparent && request.URL.Host == "" { 218 // RFC 2068 (HTTP/1.1) requires URL to be absolute URL in HTTP proxy. 219 response := &http.Response{ 220 Status: "Bad Request", 221 StatusCode: 400, 222 Proto: "HTTP/1.1", 223 ProtoMajor: 1, 224 ProtoMinor: 1, 225 Header: http.Header(make(map[string][]string)), 226 Body: nil, 227 ContentLength: 0, 228 Close: true, 229 } 230 response.Header.Set("Proxy-Connection", "close") 231 response.Header.Set("Connection", "close") 232 return response.Write(writer) 233 } 234 235 if len(request.URL.Host) > 0 { 236 request.Host = request.URL.Host 237 } 238 http_proto.RemoveHopByHopHeaders(request.Header) 239 240 // Prevent UA from being set to golang's default ones 241 if request.Header.Get("User-Agent") == "" { 242 request.Header.Set("User-Agent", "") 243 } 244 245 content := &session.Content{ 246 Protocol: "http/1.1", 247 } 248 249 content.SetAttribute(":method", strings.ToUpper(request.Method)) 250 content.SetAttribute(":path", request.URL.Path) 251 for key := range request.Header { 252 value := request.Header.Get(key) 253 content.SetAttribute(strings.ToLower(key), value) 254 } 255 256 ctx = session.ContextWithContent(ctx, content) 257 258 link, err := dispatcher.Dispatch(ctx, dest) 259 if err != nil { 260 return err 261 } 262 263 // Plain HTTP request is not a stream. The request always finishes before response. Hence, request has to be closed later. 264 defer common.Close(link.Writer) 265 var result error = errWaitAnother 266 267 requestDone := func() error { 268 request.Header.Set("Connection", "close") 269 270 requestWriter := buf.NewBufferedWriter(link.Writer) 271 common.Must(requestWriter.SetBuffered(false)) 272 if err := request.Write(requestWriter); err != nil { 273 return newError("failed to write whole request").Base(err).AtWarning() 274 } 275 return nil 276 } 277 278 responseDone := func() error { 279 responseReader := bufio.NewReaderSize(&buf.BufferedReader{Reader: link.Reader}, buf.Size) 280 response, err := http.ReadResponse(responseReader, request) 281 if err == nil { 282 http_proto.RemoveHopByHopHeaders(response.Header) 283 if response.ContentLength >= 0 { 284 response.Header.Set("Proxy-Connection", "keep-alive") 285 response.Header.Set("Connection", "keep-alive") 286 response.Header.Set("Keep-Alive", "timeout=4") 287 response.Close = false 288 } else { 289 response.Close = true 290 result = nil 291 } 292 defer response.Body.Close() 293 } else { 294 newError("failed to read response from ", request.Host).Base(err).AtWarning().WriteToLog(session.ExportIDToError(ctx)) 295 response = &http.Response{ 296 Status: "Service Unavailable", 297 StatusCode: 503, 298 Proto: "HTTP/1.1", 299 ProtoMajor: 1, 300 ProtoMinor: 1, 301 Header: http.Header(make(map[string][]string)), 302 Body: nil, 303 ContentLength: 0, 304 Close: true, 305 } 306 response.Header.Set("Connection", "close") 307 response.Header.Set("Proxy-Connection", "close") 308 } 309 if err := response.Write(writer); err != nil { 310 return newError("failed to write response").Base(err).AtWarning() 311 } 312 return nil 313 } 314 315 if err := task.Run(ctx, requestDone, responseDone); err != nil { 316 common.Interrupt(link.Reader) 317 common.Interrupt(link.Writer) 318 return newError("connection ends").Base(err) 319 } 320 321 return result 322 } 323 324 func init() { 325 common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { 326 return NewServer(ctx, config.(*ServerConfig)) 327 })) 328 }