1
0

http.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. var n int
  69. n, err = request.Read(buf)
  70. if err != nil {
  71. return
  72. }
  73. retBuffer, err := parseRequest(buf[:n], rewriteHost, remoteIP)
  74. return retBuffer, err
  75. }
  76. func parseRequest(org []byte, rewriteHost string, remoteIP string) (ret []byte, err error) {
  77. tp := bytes.NewBuffer(org)
  78. // First line: GET /index.html HTTP/1.0
  79. var b []byte
  80. if b, err = tp.ReadBytes('\n'); err != nil {
  81. return nil, err
  82. }
  83. req := new(http.Request)
  84. // we invoked ReadRequest in GetHttpHostname before, so we ignore error
  85. req.Method, req.RequestURI, req.Proto, _ = parseRequestLine(string(b))
  86. rawurl := req.RequestURI
  87. // CONNECT www.google.com:443 HTTP/1.1
  88. justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/")
  89. if justAuthority {
  90. rawurl = "http://" + rawurl
  91. }
  92. req.URL, _ = url.ParseRequestURI(rawurl)
  93. if justAuthority {
  94. // Strip the bogus "http://" back off.
  95. req.URL.Scheme = ""
  96. }
  97. // RFC2616: first case
  98. // GET /index.html HTTP/1.1
  99. // Host: www.google.com
  100. if req.URL.Host == "" {
  101. var changedBuf []byte
  102. if rewriteHost != "" {
  103. changedBuf, err = changeHostName(tp, rewriteHost)
  104. }
  105. buf := new(bytes.Buffer)
  106. buf.Write(b)
  107. buf.WriteString(fmt.Sprintf("X-Forwarded-For: %s\r\n", remoteIP))
  108. buf.WriteString(fmt.Sprintf("X-Real-IP: %s\r\n", remoteIP))
  109. if len(changedBuf) == 0 {
  110. tp.WriteTo(buf)
  111. } else {
  112. buf.Write(changedBuf)
  113. }
  114. return buf.Bytes(), err
  115. }
  116. // RFC2616: second case
  117. // GET http://www.google.com/index.html HTTP/1.1
  118. // Host: doesntmatter
  119. // In this case, any Host line is ignored.
  120. if rewriteHost != "" {
  121. hostPort := strings.Split(req.URL.Host, ":")
  122. if len(hostPort) == 1 {
  123. req.URL.Host = rewriteHost
  124. } else if len(hostPort) == 2 {
  125. req.URL.Host = fmt.Sprintf("%s:%s", rewriteHost, hostPort[1])
  126. }
  127. }
  128. firstLine := req.Method + " " + req.URL.String() + " " + req.Proto
  129. buf := new(bytes.Buffer)
  130. buf.WriteString(firstLine)
  131. buf.WriteString(fmt.Sprintf("X-Forwarded-For: %s\r\n", remoteIP))
  132. buf.WriteString(fmt.Sprintf("X-Real-IP: %s\r\n", remoteIP))
  133. tp.WriteTo(buf)
  134. return buf.Bytes(), err
  135. }
  136. // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
  137. func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
  138. s1 := strings.Index(line, " ")
  139. s2 := strings.Index(line[s1+1:], " ")
  140. if s1 < 0 || s2 < 0 {
  141. return
  142. }
  143. s2 += s1 + 1
  144. return line[:s1], line[s1+1 : s2], line[s2+1:], true
  145. }
  146. func changeHostName(buff *bytes.Buffer, rewriteHost string) (_ []byte, err error) {
  147. retBuf := new(bytes.Buffer)
  148. peek := buff.Bytes()
  149. for len(peek) > 0 {
  150. i := bytes.IndexByte(peek, '\n')
  151. if i < 3 {
  152. // Not present (-1) or found within the next few bytes,
  153. // implying we're at the end ("\r\n\r\n" or "\n\n")
  154. return nil, err
  155. }
  156. kv := peek[:i]
  157. j := bytes.IndexByte(kv, ':')
  158. if j < 0 {
  159. return nil, fmt.Errorf("malformed MIME header line: " + string(kv))
  160. }
  161. if strings.Contains(strings.ToLower(string(kv[:j])), "host") {
  162. var hostHeader string
  163. portPos := bytes.IndexByte(kv[j+1:], ':')
  164. if portPos == -1 {
  165. hostHeader = fmt.Sprintf("Host: %s\r\n", rewriteHost)
  166. } else {
  167. hostHeader = fmt.Sprintf("Host: %s:%s\r\n", rewriteHost, kv[j+portPos+2:])
  168. }
  169. retBuf.WriteString(hostHeader)
  170. peek = peek[i+1:]
  171. break
  172. } else {
  173. retBuf.Write(peek[:i])
  174. retBuf.WriteByte('\n')
  175. }
  176. peek = peek[i+1:]
  177. }
  178. retBuf.Write(peek)
  179. return retBuf.Bytes(), err
  180. }
  181. func HttpAuthFunc(c frpNet.Conn, userName, passWord, authorization string) (bAccess bool, err error) {
  182. s := strings.SplitN(authorization, " ", 2)
  183. if len(s) != 2 {
  184. res := noAuthResponse()
  185. res.Write(c)
  186. return
  187. }
  188. b, err := base64.StdEncoding.DecodeString(s[1])
  189. if err != nil {
  190. return
  191. }
  192. pair := strings.SplitN(string(b), ":", 2)
  193. if len(pair) != 2 {
  194. return
  195. }
  196. if pair[0] != userName || pair[1] != passWord {
  197. return
  198. }
  199. return true, nil
  200. }
  201. func noAuthResponse() *http.Response {
  202. header := make(map[string][]string)
  203. header["WWW-Authenticate"] = []string{`Basic realm="Restricted"`}
  204. res := &http.Response{
  205. Status: "401 Not authorized",
  206. StatusCode: 401,
  207. Proto: "HTTP/1.1",
  208. ProtoMajor: 1,
  209. ProtoMinor: 1,
  210. Header: header,
  211. }
  212. return res
  213. }