httpconnect.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2020 guylewin, guy@lewin.co.il
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package tcpmux
  15. import (
  16. "bufio"
  17. "fmt"
  18. "io"
  19. "net"
  20. "net/http"
  21. "time"
  22. "github.com/fatedier/frp/pkg/util/util"
  23. "github.com/fatedier/frp/pkg/util/vhost"
  24. )
  25. type HTTPConnectTCPMuxer struct {
  26. *vhost.Muxer
  27. }
  28. func NewHTTPConnectTCPMuxer(listener net.Listener, timeout time.Duration) (*HTTPConnectTCPMuxer, error) {
  29. mux, err := vhost.NewMuxer(listener, getHostFromHTTPConnect, nil, sendHTTPOk, nil, timeout)
  30. return &HTTPConnectTCPMuxer{mux}, err
  31. }
  32. func readHTTPConnectRequest(rd io.Reader) (host string, err error) {
  33. bufioReader := bufio.NewReader(rd)
  34. req, err := http.ReadRequest(bufioReader)
  35. if err != nil {
  36. return
  37. }
  38. if req.Method != "CONNECT" {
  39. err = fmt.Errorf("connections to tcp vhost must be of method CONNECT")
  40. return
  41. }
  42. host, _ = util.CanonicalHost(req.Host)
  43. return
  44. }
  45. func sendHTTPOk(c net.Conn) error {
  46. return util.OkResponse().Write(c)
  47. }
  48. func getHostFromHTTPConnect(c net.Conn) (_ net.Conn, _ map[string]string, err error) {
  49. reqInfoMap := make(map[string]string, 0)
  50. host, err := readHTTPConnectRequest(c)
  51. if err != nil {
  52. return nil, reqInfoMap, err
  53. }
  54. reqInfoMap["Host"] = host
  55. reqInfoMap["Scheme"] = "tcp"
  56. return c, reqInfoMap, nil
  57. }