httpd.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // Package httpd implements REST API and Web interface for SFTPGo.
  2. // REST API allows to manage users and quota and to get real time reports for the active connections
  3. // with possibility of forcibly closing a connection.
  4. // The OpenAPI 3 schema for the exposed API can be found inside the source tree:
  5. // https://github.com/drakkan/sftpgo/tree/master/api/schema/openapi.yaml
  6. // A basic Web interface to manage users and connections is provided too
  7. package httpd
  8. import (
  9. "crypto/tls"
  10. "fmt"
  11. "net/http"
  12. "path/filepath"
  13. "time"
  14. "github.com/go-chi/chi"
  15. "github.com/drakkan/sftpgo/dataprovider"
  16. "github.com/drakkan/sftpgo/logger"
  17. "github.com/drakkan/sftpgo/utils"
  18. )
  19. const (
  20. logSender = "httpd"
  21. apiPrefix = "/api/v1"
  22. activeConnectionsPath = "/api/v1/connection"
  23. quotaScanPath = "/api/v1/quota_scan"
  24. quotaScanVFolderPath = "/api/v1/folder_quota_scan"
  25. userPath = "/api/v1/user"
  26. versionPath = "/api/v1/version"
  27. folderPath = "/api/v1/folder"
  28. providerStatusPath = "/api/v1/providerstatus"
  29. dumpDataPath = "/api/v1/dumpdata"
  30. loadDataPath = "/api/v1/loaddata"
  31. metricsPath = "/metrics"
  32. pprofBasePath = "/debug"
  33. webBasePath = "/web"
  34. webUsersPath = "/web/users"
  35. webUserPath = "/web/user"
  36. webConnectionsPath = "/web/connections"
  37. webFoldersPath = "/web/folders"
  38. webFolderPath = "/web/folder"
  39. webStaticFilesPath = "/static"
  40. maxRestoreSize = 10485760 // 10 MB
  41. maxRequestSize = 1048576 // 1MB
  42. )
  43. var (
  44. router *chi.Mux
  45. dataProvider dataprovider.Provider
  46. backupsPath string
  47. httpAuth httpAuthProvider
  48. certMgr *certManager
  49. )
  50. // Conf httpd daemon configuration
  51. type Conf struct {
  52. // The port used for serving HTTP requests. 0 disable the HTTP server. Default: 8080
  53. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  54. // The address to listen on. A blank value means listen on all available network interfaces. Default: "127.0.0.1"
  55. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  56. // Path to the HTML web templates. This can be an absolute path or a path relative to the config dir
  57. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  58. // Path to the static files for the web interface. This can be an absolute path or a path relative to the config dir
  59. StaticFilesPath string `json:"static_files_path" mapstructure:"static_files_path"`
  60. // Path to the backup directory. This can be an absolute path or a path relative to the config dir
  61. BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
  62. // Path to a file used to store usernames and password for basic authentication.
  63. // This can be an absolute path or a path relative to the config dir.
  64. // We support HTTP basic authentication and the file format must conform to the one generated using the Apache
  65. // htpasswd tool. The supported password formats are bcrypt ($2y$ prefix) and md5 crypt ($apr1$ prefix).
  66. // If empty HTTP authentication is disabled
  67. AuthUserFile string `json:"auth_user_file" mapstructure:"auth_user_file"`
  68. // If files containing a certificate and matching private key for the server are provided the server will expect
  69. // HTTPS connections.
  70. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  71. // "paramchange" request to the running service on Windows.
  72. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  73. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  74. }
  75. type apiResponse struct {
  76. Error string `json:"error"`
  77. Message string `json:"message"`
  78. HTTPStatus int `json:"status"`
  79. }
  80. // SetDataProvider sets the data provider to use to fetch the data about users
  81. func SetDataProvider(provider dataprovider.Provider) {
  82. dataProvider = provider
  83. }
  84. // Initialize configures and starts the HTTP server
  85. func (c Conf) Initialize(configDir string, profiler bool) error {
  86. var err error
  87. logger.Debug(logSender, "", "initializing HTTP server with config %+v", c)
  88. backupsPath = getConfigPath(c.BackupsPath, configDir)
  89. staticFilesPath := getConfigPath(c.StaticFilesPath, configDir)
  90. templatesPath := getConfigPath(c.TemplatesPath, configDir)
  91. if len(backupsPath) == 0 || len(staticFilesPath) == 0 || len(templatesPath) == 0 {
  92. return fmt.Errorf("Required directory is invalid, backup path %#v, static file path: %#v template path: %#v",
  93. backupsPath, staticFilesPath, templatesPath)
  94. }
  95. authUserFile := getConfigPath(c.AuthUserFile, configDir)
  96. httpAuth, err = newBasicAuthProvider(authUserFile)
  97. if err != nil {
  98. return err
  99. }
  100. certificateFile := getConfigPath(c.CertificateFile, configDir)
  101. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  102. loadTemplates(templatesPath)
  103. initializeRouter(staticFilesPath, profiler)
  104. httpServer := &http.Server{
  105. Addr: fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort),
  106. Handler: router,
  107. ReadTimeout: 60 * time.Second,
  108. WriteTimeout: 60 * time.Second,
  109. IdleTimeout: 120 * time.Second,
  110. MaxHeaderBytes: 1 << 16, // 64KB
  111. }
  112. if len(certificateFile) > 0 && len(certificateKeyFile) > 0 {
  113. certMgr, err = newCertManager(certificateFile, certificateKeyFile)
  114. if err != nil {
  115. return err
  116. }
  117. config := &tls.Config{
  118. GetCertificate: certMgr.GetCertificateFunc(),
  119. }
  120. httpServer.TLSConfig = config
  121. return httpServer.ListenAndServeTLS("", "")
  122. }
  123. return httpServer.ListenAndServe()
  124. }
  125. // ReloadTLSCertificate reloads the TLS certificate and key from the configured paths
  126. func ReloadTLSCertificate() error {
  127. if certMgr != nil {
  128. return certMgr.loadCertificate()
  129. }
  130. return nil
  131. }
  132. func getConfigPath(name, configDir string) string {
  133. if !utils.IsFileInputValid(name) {
  134. return ""
  135. }
  136. if len(name) > 0 && !filepath.IsAbs(name) {
  137. return filepath.Join(configDir, name)
  138. }
  139. return name
  140. }