http.go 5.6 KB

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