1
0

static_file.go 2.1 KB

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