static_file.go 2.0 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 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. }
  52. go func() {
  53. _ = sp.s.Serve(listener)
  54. }()
  55. return sp, nil
  56. }
  57. func (sp *StaticFilePlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ *ExtraInfo) {
  58. wrapConn := netpkg.WrapReadWriteCloserToConn(conn, realConn)
  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. }