static_file.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. frpNet "github.com/fatedier/frp/pkg/util/net"
  22. )
  23. const PluginStaticFile = "static_file"
  24. func init() {
  25. Register(PluginStaticFile, NewStaticFilePlugin)
  26. }
  27. type StaticFilePlugin struct {
  28. localPath string
  29. stripPrefix string
  30. httpUser string
  31. httpPasswd string
  32. l *Listener
  33. s *http.Server
  34. }
  35. func NewStaticFilePlugin(params map[string]string) (Plugin, error) {
  36. localPath := params["plugin_local_path"]
  37. stripPrefix := params["plugin_strip_prefix"]
  38. httpUser := params["plugin_http_user"]
  39. httpPasswd := params["plugin_http_passwd"]
  40. listener := NewProxyListener()
  41. sp := &StaticFilePlugin{
  42. localPath: localPath,
  43. stripPrefix: stripPrefix,
  44. httpUser: httpUser,
  45. httpPasswd: httpPasswd,
  46. l: listener,
  47. }
  48. var prefix string
  49. if stripPrefix != "" {
  50. prefix = "/" + stripPrefix + "/"
  51. } else {
  52. prefix = "/"
  53. }
  54. router := mux.NewRouter()
  55. router.Use(frpNet.NewHTTPAuthMiddleware(httpUser, httpPasswd).SetAuthFailDelay(200 * time.Millisecond).Middleware)
  56. router.PathPrefix(prefix).Handler(frpNet.MakeHTTPGzipHandler(http.StripPrefix(prefix, http.FileServer(http.Dir(localPath))))).Methods("GET")
  57. sp.s = &http.Server{
  58. Handler: router,
  59. }
  60. go func() {
  61. _ = sp.s.Serve(listener)
  62. }()
  63. return sp, nil
  64. }
  65. func (sp *StaticFilePlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
  66. wrapConn := frpNet.WrapReadWriteCloserToConn(conn, realConn)
  67. _ = sp.l.PutConn(wrapConn)
  68. }
  69. func (sp *StaticFilePlugin) Name() string {
  70. return PluginStaticFile
  71. }
  72. func (sp *StaticFilePlugin) Close() error {
  73. sp.s.Close()
  74. sp.l.Close()
  75. return nil
  76. }