http.go 6.3 KB

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