1
0

http.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "encoding/base64"
  19. "fmt"
  20. "io"
  21. "net/http"
  22. "net/url"
  23. "strings"
  24. "time"
  25. frpNet "github.com/fatedier/frp/utils/net"
  26. "github.com/fatedier/frp/utils/pool"
  27. )
  28. type HttpMuxer struct {
  29. *VhostMuxer
  30. }
  31. func GetHttpRequestInfo(c frpNet.Conn) (_ frpNet.Conn, _ map[string]string, err error) {
  32. reqInfoMap := make(map[string]string, 0)
  33. sc, rd := frpNet.NewShareConn(c)
  34. request, err := http.ReadRequest(bufio.NewReader(rd))
  35. if err != nil {
  36. return sc, reqInfoMap, err
  37. }
  38. // hostName
  39. tmpArr := strings.Split(request.Host, ":")
  40. reqInfoMap["Host"] = tmpArr[0]
  41. reqInfoMap["Path"] = request.URL.Path
  42. reqInfoMap["Scheme"] = request.URL.Scheme
  43. // Authorization
  44. authStr := request.Header.Get("Authorization")
  45. if authStr != "" {
  46. reqInfoMap["Authorization"] = authStr
  47. }
  48. request.Body.Close()
  49. return sc, reqInfoMap, nil
  50. }
  51. func NewHttpMuxer(listener frpNet.Listener, timeout time.Duration) (*HttpMuxer, error) {
  52. mux, err := NewVhostMuxer(listener, GetHttpRequestInfo, HttpAuthFunc, ModifyHttpRequest, timeout)
  53. return &HttpMuxer{mux}, err
  54. }
  55. func ModifyHttpRequest(c frpNet.Conn, rewriteHost string) (_ frpNet.Conn, err error) {
  56. sc, rd := frpNet.NewShareConn(c)
  57. var buff []byte
  58. remoteIP := strings.Split(c.RemoteAddr().String(), ":")[0]
  59. if buff, err = hostNameRewrite(rd, rewriteHost, remoteIP); err != nil {
  60. return sc, err
  61. }
  62. err = sc.WriteBuff(buff)
  63. return sc, err
  64. }
  65. func hostNameRewrite(request io.Reader, rewriteHost string, remoteIP string) (_ []byte, err error) {
  66. buf := pool.GetBuf(1024)
  67. defer pool.PutBuf(buf)
  68. request.Read(buf)
  69. retBuffer, err := parseRequest(buf, rewriteHost, remoteIP)
  70. return retBuffer, err
  71. }
  72. func parseRequest(org []byte, rewriteHost string, remoteIP string) (ret []byte, err error) {
  73. tp := bytes.NewBuffer(org)
  74. // First line: GET /index.html HTTP/1.0
  75. var b []byte
  76. if b, err = tp.ReadBytes('\n'); err != nil {
  77. return nil, err
  78. }
  79. req := new(http.Request)
  80. // we invoked ReadRequest in GetHttpHostname before, so we ignore error
  81. req.Method, req.RequestURI, req.Proto, _ = parseRequestLine(string(b))
  82. rawurl := req.RequestURI
  83. // CONNECT www.google.com:443 HTTP/1.1
  84. justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/")
  85. if justAuthority {
  86. rawurl = "http://" + rawurl
  87. }
  88. req.URL, _ = url.ParseRequestURI(rawurl)
  89. if justAuthority {
  90. // Strip the bogus "http://" back off.
  91. req.URL.Scheme = ""
  92. }
  93. // RFC2616: first case
  94. // GET /index.html HTTP/1.1
  95. // Host: www.google.com
  96. if req.URL.Host == "" {
  97. var changedBuf []byte
  98. if rewriteHost != "" {
  99. changedBuf, err = changeHostName(tp, rewriteHost)
  100. }
  101. buf := new(bytes.Buffer)
  102. buf.Write(b)
  103. buf.WriteString(fmt.Sprintf("X-Forwarded-For: %s\n", remoteIP))
  104. buf.WriteString(fmt.Sprintf("X-Real-IP: %s\n", remoteIP))
  105. if len(changedBuf) == 0 {
  106. tp.WriteTo(buf)
  107. } else {
  108. buf.Write(changedBuf)
  109. }
  110. return buf.Bytes(), err
  111. }
  112. // RFC2616: second case
  113. // GET http://www.google.com/index.html HTTP/1.1
  114. // Host: doesntmatter
  115. // In this case, any Host line is ignored.
  116. if rewriteHost != "" {
  117. hostPort := strings.Split(req.URL.Host, ":")
  118. if len(hostPort) == 1 {
  119. req.URL.Host = rewriteHost
  120. } else if len(hostPort) == 2 {
  121. req.URL.Host = fmt.Sprintf("%s:%s", rewriteHost, hostPort[1])
  122. }
  123. }
  124. firstLine := req.Method + " " + req.URL.String() + " " + req.Proto
  125. buf := new(bytes.Buffer)
  126. buf.WriteString(firstLine)
  127. buf.WriteString(fmt.Sprintf("X-Forwarded-For: %s\n", remoteIP))
  128. buf.WriteString(fmt.Sprintf("X-Real-IP: %s\n", remoteIP))
  129. tp.WriteTo(buf)
  130. return buf.Bytes(), err
  131. }
  132. // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
  133. func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
  134. s1 := strings.Index(line, " ")
  135. s2 := strings.Index(line[s1+1:], " ")
  136. if s1 < 0 || s2 < 0 {
  137. return
  138. }
  139. s2 += s1 + 1
  140. return line[:s1], line[s1+1 : s2], line[s2+1:], true
  141. }
  142. func changeHostName(buff *bytes.Buffer, rewriteHost string) (_ []byte, err error) {
  143. retBuf := new(bytes.Buffer)
  144. peek := buff.Bytes()
  145. for len(peek) > 0 {
  146. i := bytes.IndexByte(peek, '\n')
  147. if i < 3 {
  148. // Not present (-1) or found within the next few bytes,
  149. // implying we're at the end ("\r\n\r\n" or "\n\n")
  150. return nil, err
  151. }
  152. kv := peek[:i]
  153. j := bytes.IndexByte(kv, ':')
  154. if j < 0 {
  155. return nil, fmt.Errorf("malformed MIME header line: " + string(kv))
  156. }
  157. if strings.Contains(strings.ToLower(string(kv[:j])), "host") {
  158. var hostHeader string
  159. portPos := bytes.IndexByte(kv[j+1:], ':')
  160. if portPos == -1 {
  161. hostHeader = fmt.Sprintf("Host: %s\n", rewriteHost)
  162. } else {
  163. hostHeader = fmt.Sprintf("Host: %s:%s\n", rewriteHost, kv[j+portPos+2:])
  164. }
  165. retBuf.WriteString(hostHeader)
  166. peek = peek[i+1:]
  167. break
  168. } else {
  169. retBuf.Write(peek[:i])
  170. retBuf.WriteByte('\n')
  171. }
  172. peek = peek[i+1:]
  173. }
  174. retBuf.Write(peek)
  175. return retBuf.Bytes(), err
  176. }
  177. func HttpAuthFunc(c frpNet.Conn, userName, passWord, authorization string) (bAccess bool, err error) {
  178. s := strings.SplitN(authorization, " ", 2)
  179. if len(s) != 2 {
  180. res := noAuthResponse()
  181. res.Write(c)
  182. return
  183. }
  184. b, err := base64.StdEncoding.DecodeString(s[1])
  185. if err != nil {
  186. return
  187. }
  188. pair := strings.SplitN(string(b), ":", 2)
  189. if len(pair) != 2 {
  190. return
  191. }
  192. if pair[0] != userName || pair[1] != passWord {
  193. return
  194. }
  195. return true, nil
  196. }
  197. func noAuthResponse() *http.Response {
  198. header := make(map[string][]string)
  199. header["WWW-Authenticate"] = []string{`Basic realm="Restricted"`}
  200. res := &http.Response{
  201. Status: "401 Not authorized",
  202. StatusCode: 401,
  203. Proto: "HTTP/1.1",
  204. ProtoMajor: 1,
  205. ProtoMinor: 1,
  206. Header: header,
  207. }
  208. return res
  209. }