http.go 5.6 KB

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