1
0

static_file.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2018 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. //go:build !frps
  15. package client
  16. import (
  17. "context"
  18. "net/http"
  19. "time"
  20. "github.com/gorilla/mux"
  21. v1 "github.com/fatedier/frp/pkg/config/v1"
  22. netpkg "github.com/fatedier/frp/pkg/util/net"
  23. )
  24. func init() {
  25. Register(v1.PluginStaticFile, NewStaticFilePlugin)
  26. }
  27. type StaticFilePlugin struct {
  28. opts *v1.StaticFilePluginOptions
  29. l *Listener
  30. s *http.Server
  31. }
  32. func NewStaticFilePlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) {
  33. opts := options.(*v1.StaticFilePluginOptions)
  34. listener := NewProxyListener()
  35. sp := &StaticFilePlugin{
  36. opts: opts,
  37. l: listener,
  38. }
  39. var prefix string
  40. if opts.StripPrefix != "" {
  41. prefix = "/" + opts.StripPrefix + "/"
  42. } else {
  43. prefix = "/"
  44. }
  45. router := mux.NewRouter()
  46. router.Use(netpkg.NewHTTPAuthMiddleware(opts.HTTPUser, opts.HTTPPassword).SetAuthFailDelay(200 * time.Millisecond).Middleware)
  47. router.PathPrefix(prefix).Handler(netpkg.MakeHTTPGzipHandler(http.StripPrefix(prefix, http.FileServer(http.Dir(opts.LocalPath))))).Methods("GET")
  48. sp.s = &http.Server{
  49. Handler: router,
  50. ReadHeaderTimeout: 60 * time.Second,
  51. }
  52. go func() {
  53. _ = sp.s.Serve(listener)
  54. }()
  55. return sp, nil
  56. }
  57. func (sp *StaticFilePlugin) Handle(_ context.Context, connInfo *ConnectionInfo) {
  58. wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn)
  59. _ = sp.l.PutConn(wrapConn)
  60. }
  61. func (sp *StaticFilePlugin) Name() string {
  62. return v1.PluginStaticFile
  63. }
  64. func (sp *StaticFilePlugin) Close() error {
  65. sp.s.Close()
  66. sp.l.Close()
  67. return nil
  68. }