http.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  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 vhost
  15. import (
  16. "bufio"
  17. "bytes"
  18. "fmt"
  19. "io"
  20. "net"
  21. "net/http"
  22. "net/url"
  23. "strings"
  24. "time"
  25. "frp/utils/conn"
  26. "frp/utils/log"
  27. )
  28. type HttpMuxer struct {
  29. *VhostMuxer
  30. }
  31. func GetHttpHostname(c *conn.Conn) (_ net.Conn, routerName string, err error) {
  32. sc, rd := newShareConn(c.TcpConn)
  33. request, err := http.ReadRequest(bufio.NewReader(rd))
  34. if err != nil {
  35. return sc, "", err
  36. }
  37. tmpArr := strings.Split(request.Host, ":")
  38. routerName = tmpArr[0]
  39. request.Body.Close()
  40. return sc, routerName, nil
  41. }
  42. func NewHttpMuxer(listener *conn.Listener, timeout time.Duration) (*HttpMuxer, error) {
  43. mux, err := NewVhostMuxer(listener, GetHttpHostname, timeout)
  44. return &HttpMuxer{mux}, err
  45. }
  46. func HostNameRewrite(c *conn.Conn, clientHost string) (_ net.Conn, err error) {
  47. log.Info("HostNameRewrite, clientHost: %s", clientHost)
  48. sc, rd := newShareConn(c.TcpConn)
  49. var buff []byte
  50. if buff, err = hostNameRewrite(rd, clientHost); err != nil {
  51. return sc, err
  52. }
  53. err = sc.WriteBuff(buff)
  54. return sc, err
  55. }
  56. func hostNameRewrite(request io.Reader, clientHost string) (_ []byte, err error) {
  57. buffer := make([]byte, 1024)
  58. request.Read(buffer)
  59. log.Debug("before hostNameRewrite:\n %s", string(buffer))
  60. retBuffer, err := parseRequest(buffer, clientHost)
  61. log.Debug("after hostNameRewrite:\n %s", string(retBuffer))
  62. return retBuffer, err
  63. }
  64. func parseRequest(org []byte, clientHost string) (ret []byte, err error) {
  65. tp := bytes.NewBuffer(org)
  66. // First line: GET /index.html HTTP/1.0
  67. var b []byte
  68. if b, err = tp.ReadBytes('\n'); err != nil {
  69. return nil, err
  70. }
  71. req := new(http.Request)
  72. //we invoked ReadRequest in GetHttpHostname before, so we ignore error
  73. req.Method, req.RequestURI, req.Proto, _ = parseRequestLine(string(b))
  74. rawurl := req.RequestURI
  75. //CONNECT www.google.com:443 HTTP/1.1
  76. justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/")
  77. if justAuthority {
  78. rawurl = "http://" + rawurl
  79. }
  80. req.URL, _ = url.ParseRequestURI(rawurl)
  81. if justAuthority {
  82. // Strip the bogus "http://" back off.
  83. req.URL.Scheme = ""
  84. }
  85. // RFC2616: first case
  86. // GET /index.html HTTP/1.1
  87. // Host: www.google.com
  88. if req.URL.Host == "" {
  89. changedBuf, err := changeHostName(tp, clientHost)
  90. buf := new(bytes.Buffer)
  91. buf.Write(b)
  92. buf.Write(changedBuf)
  93. return buf.Bytes(), err
  94. }
  95. // RFC2616: second case
  96. // GET http://www.google.com/index.html HTTP/1.1
  97. // Host: doesntmatter
  98. // In this case, any Host line is ignored.
  99. req.URL.Host = clientHost
  100. firstLine := req.Method + " " + req.URL.String() + " " + req.Proto
  101. buf := new(bytes.Buffer)
  102. buf.WriteString(firstLine)
  103. tp.WriteTo(buf)
  104. return buf.Bytes(), err
  105. }
  106. // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
  107. func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
  108. s1 := strings.Index(line, " ")
  109. s2 := strings.Index(line[s1+1:], " ")
  110. if s1 < 0 || s2 < 0 {
  111. return
  112. }
  113. s2 += s1 + 1
  114. return line[:s1], line[s1+1 : s2], line[s2+1:], true
  115. }
  116. func changeHostName(buff *bytes.Buffer, clientHost string) (_ []byte, err error) {
  117. retBuf := new(bytes.Buffer)
  118. peek := buff.Bytes()
  119. for len(peek) > 0 {
  120. i := bytes.IndexByte(peek, '\n')
  121. if i < 3 {
  122. // Not present (-1) or found within the next few bytes,
  123. // implying we're at the end ("\r\n\r\n" or "\n\n")
  124. return nil, err
  125. }
  126. kv := peek[:i]
  127. j := bytes.IndexByte(kv, ':')
  128. if j < 0 {
  129. return nil, fmt.Errorf("malformed MIME header line: " + string(kv))
  130. }
  131. if strings.Contains(strings.ToLower(string(kv[:j])), "host") {
  132. hostHeader := fmt.Sprintf("Host: %s\n", clientHost)
  133. retBuf.WriteString(hostHeader)
  134. peek = peek[i+1:]
  135. break
  136. } else {
  137. retBuf.Write(peek[:i])
  138. retBuf.WriteByte('\n')
  139. }
  140. peek = peek[i+1:]
  141. }
  142. retBuf.Write(peek)
  143. return retBuf.Bytes(), err
  144. }