static_file.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. frpNet "github.com/fatedier/frp/pkg/util/net"
  20. "github.com/gorilla/mux"
  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 sp.s.Serve(listener)
  60. return sp, nil
  61. }
  62. func (sp *StaticFilePlugin) Handle(conn io.ReadWriteCloser, realConn net.Conn, extraBufToLocal []byte) {
  63. wrapConn := frpNet.WrapReadWriteCloserToConn(conn, realConn)
  64. sp.l.PutConn(wrapConn)
  65. }
  66. func (sp *StaticFilePlugin) Name() string {
  67. return PluginStaticFile
  68. }
  69. func (sp *StaticFilePlugin) Close() error {
  70. sp.s.Close()
  71. sp.l.Close()
  72. return nil
  73. }