1
0

static_file.go 2.1 KB

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