static_file.go 2.1 KB

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