http.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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"
  22. "net/http"
  23. "net/url"
  24. "strings"
  25. "time"
  26. "github.com/fatedier/frp/src/utils/conn"
  27. "github.com/fatedier/frp/src/utils/pool"
  28. )
  29. type HttpMuxer struct {
  30. *VhostMuxer
  31. }
  32. func GetHttpRequestInfo(c *conn.Conn) (_ net.Conn, _ map[string]string, err error) {
  33. reqInfoMap := make(map[string]string, 0)
  34. sc, rd := newShareConn(c.TcpConn)
  35. request, err := http.ReadRequest(bufio.NewReader(rd))
  36. if err != nil {
  37. return sc, 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 sc, reqInfoMap, nil
  51. }
  52. func NewHttpMuxer(listener *conn.Listener, timeout time.Duration) (*HttpMuxer, error) {
  53. mux, err := NewVhostMuxer(listener, GetHttpRequestInfo, HttpAuthFunc, HttpHostNameRewrite, timeout)
  54. return &HttpMuxer{mux}, err
  55. }
  56. func HttpHostNameRewrite(c *conn.Conn, rewriteHost string) (_ net.Conn, err error) {
  57. sc, rd := newShareConn(c.TcpConn)
  58. var buff []byte
  59. if buff, err = hostNameRewrite(rd, rewriteHost); 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) (_ []byte, err error) {
  66. buf := pool.GetBuf(1024)
  67. defer pool.PutBuf(buf)
  68. request.Read(buf)
  69. retBuffer, err := parseRequest(buf, rewriteHost)
  70. return retBuffer, err
  71. }
  72. func parseRequest(org []byte, rewriteHost 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. changedBuf, err := changeHostName(tp, rewriteHost)
  98. buf := new(bytes.Buffer)
  99. buf.Write(b)
  100. buf.Write(changedBuf)
  101. return buf.Bytes(), err
  102. }
  103. // RFC2616: second case
  104. // GET http://www.google.com/index.html HTTP/1.1
  105. // Host: doesntmatter
  106. // In this case, any Host line is ignored.
  107. hostPort := strings.Split(req.URL.Host, ":")
  108. if len(hostPort) == 1 {
  109. req.URL.Host = rewriteHost
  110. } else if len(hostPort) == 2 {
  111. req.URL.Host = fmt.Sprintf("%s:%s", rewriteHost, hostPort[1])
  112. }
  113. firstLine := req.Method + " " + req.URL.String() + " " + req.Proto
  114. buf := new(bytes.Buffer)
  115. buf.WriteString(firstLine)
  116. tp.WriteTo(buf)
  117. return buf.Bytes(), err
  118. }
  119. // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
  120. func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
  121. s1 := strings.Index(line, " ")
  122. s2 := strings.Index(line[s1+1:], " ")
  123. if s1 < 0 || s2 < 0 {
  124. return
  125. }
  126. s2 += s1 + 1
  127. return line[:s1], line[s1+1 : s2], line[s2+1:], true
  128. }
  129. func changeHostName(buff *bytes.Buffer, rewriteHost string) (_ []byte, err error) {
  130. retBuf := new(bytes.Buffer)
  131. peek := buff.Bytes()
  132. for len(peek) > 0 {
  133. i := bytes.IndexByte(peek, '\n')
  134. if i < 3 {
  135. // Not present (-1) or found within the next few bytes,
  136. // implying we're at the end ("\r\n\r\n" or "\n\n")
  137. return nil, err
  138. }
  139. kv := peek[:i]
  140. j := bytes.IndexByte(kv, ':')
  141. if j < 0 {
  142. return nil, fmt.Errorf("malformed MIME header line: " + string(kv))
  143. }
  144. if strings.Contains(strings.ToLower(string(kv[:j])), "host") {
  145. var hostHeader string
  146. portPos := bytes.IndexByte(kv[j+1:], ':')
  147. if portPos == -1 {
  148. hostHeader = fmt.Sprintf("Host: %s\n", rewriteHost)
  149. } else {
  150. hostHeader = fmt.Sprintf("Host: %s:%s\n", rewriteHost, kv[portPos+1:])
  151. }
  152. retBuf.WriteString(hostHeader)
  153. peek = peek[i+1:]
  154. break
  155. } else {
  156. retBuf.Write(peek[:i])
  157. retBuf.WriteByte('\n')
  158. }
  159. peek = peek[i+1:]
  160. }
  161. retBuf.Write(peek)
  162. return retBuf.Bytes(), err
  163. }
  164. func HttpAuthFunc(c *conn.Conn, userName, passWord, authorization string) (bAccess bool, err error) {
  165. s := strings.SplitN(authorization, " ", 2)
  166. if len(s) != 2 {
  167. res := noAuthResponse()
  168. res.Write(c.TcpConn)
  169. return
  170. }
  171. b, err := base64.StdEncoding.DecodeString(s[1])
  172. if err != nil {
  173. return
  174. }
  175. pair := strings.SplitN(string(b), ":", 2)
  176. if len(pair) != 2 {
  177. return
  178. }
  179. if pair[0] != userName || pair[1] != passWord {
  180. return
  181. }
  182. return true, nil
  183. }
  184. func noAuthResponse() *http.Response {
  185. header := make(map[string][]string)
  186. header["WWW-Authenticate"] = []string{`Basic realm="Restricted"`}
  187. res := &http.Response{
  188. Status: "401 Not authorized",
  189. StatusCode: 401,
  190. Proto: "HTTP/1.1",
  191. ProtoMajor: 1,
  192. ProtoMinor: 1,
  193. Header: header,
  194. }
  195. return res
  196. }