static_file.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. package plugin
  15. import (
  16. "io"
  17. "net"
  18. "net/http"
  19. "time"
  20. "github.com/gorilla/mux"
  21. v1 "github.com/fatedier/frp/pkg/config/v1"
  22. utilnet "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(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(utilnet.NewHTTPAuthMiddleware(opts.HTTPUser, opts.HTTPPassword).SetAuthFailDelay(200 * time.Millisecond).Middleware)
  47. router.PathPrefix(prefix).Handler(utilnet.MakeHTTPGzipHandler(http.StripPrefix(prefix, http.FileServer(http.Dir(opts.LocalPath))))).Methods("GET")
  48. sp.s = &http.Server{
  49. Handler: router,
  50. }
  51. go func() {
  52. _ = sp.s.Serve(listener)
  53. }()
  54. return sp, nil
  55. }
  56. func (sp *StaticFilePlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, _ *ExtraInfo) {
  57. wrapConn := utilnet.WrapReadWriteCloserToConn(conn, realConn)
  58. _ = sp.l.PutConn(wrapConn)
  59. }
  60. func (sp *StaticFilePlugin) Name() string {
  61. return v1.PluginStaticFile
  62. }
  63. func (sp *StaticFilePlugin) Close() error {
  64. sp.s.Close()
  65. sp.l.Close()
  66. return nil
  67. }