1
0

static_file.go 2.2 KB

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