| // |
| 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 |
| 15 | package net |
| 16 |
| 17 | import ( |
| 18 | "compress/gzip" |
| 19 | "io" |
| 20 | "net/http" |
| 21 | "strings" |
| 22 | "time" |
| 23 |
| 24 | "github.com/fatedier/frp/pkg/util/util" |
| 25 | ) |
| 26 |
| 27 | type HTTPAuthMiddleware struct { |
| 28 | user string |
| 29 | passwd string |
| 30 | authFailDelay time.Duration |
| 31 | } |
| 32 |
| 33 | func NewHTTPAuthMiddleware(user, passwd string) *HTTPAuthMiddleware { |
| 34 | return &HTTPAuthMiddleware{ |
| 35 | user: user, |
| 36 | passwd: passwd, |
| 37 | } |
| 38 | } |
| 39 |
| 40 | func (authMid *HTTPAuthMiddleware) SetAuthFailDelay(delay time.Duration) *HTTPAuthMiddleware { |
| 41 | authMid.authFailDelay = delay |
| 42 | return authMid |
| 43 | } |
| 44 |
| 45 | func (authMid *HTTPAuthMiddleware) Middleware(next http.Handler) http.Handler { |
| 46 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 47 | reqUser, reqPasswd, hasAuth := r.BasicAuth() |
| 48 | if (authMid.user == "" && authMid.passwd == "") || |
| 49 | (hasAuth && util.ConstantTimeEqString(reqUser, authMid.user) && |
| 50 | util.ConstantTimeEqString(reqPasswd, authMid.passwd)) { |
| 51 | next.ServeHTTP(w, r) |
| 52 | } else { |
| 53 | if authMid.authFailDelay > 0 { |
| 54 | time.Sleep(authMid.authFailDelay) |
| 55 | } |
| 56 | w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) |
| 57 | http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) |
| 58 | } |
| 59 | }) |
| 60 | } |
| 61 |
| 62 | type HTTPGzipWrapper struct { |
| 63 | h http.Handler |
| 64 | } |
| 65 |
| 66 | func (gw *HTTPGzipWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 67 | if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { |
| 68 | gw.h.ServeHTTP(w, r) |
| 69 | return |
| 70 | } |
| 71 | w.Header().Set("Content-Encoding", "gzip") |
| 72 | gz := gzip.NewWriter(w) |
| 73 | defer gz.Close() |
| 74 | gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w} |
| 75 | gw.h.ServeHTTP(gzr, r) |
| 76 | } |
| 77 |
| 78 | func MakeHTTPGzipHandler(h http.Handler) http.Handler { |
| 79 | return &HTTPGzipWrapper{ |
| 80 | h: h, |
| 81 | } |
| 82 | } |
| 83 |
| 84 | type gzipResponseWriter struct { |
| 85 | io.Writer |
| 86 | http.ResponseWriter |
| 87 | } |
| 88 |
| 89 | func (w gzipResponseWriter) Write(b []byte) (int, error) { |
| 90 | return w.Writer.Write(b) |
| 91 | } |