httpd.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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/common"
  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. updateUsedQuotaPath = "/api/v1/quota_update"
  32. updateFolderUsedQuotaPath = "/api/v1/folder_quota_update"
  33. metricsPath = "/metrics"
  34. pprofBasePath = "/debug"
  35. webBasePath = "/web"
  36. webUsersPath = "/web/users"
  37. webUserPath = "/web/user"
  38. webConnectionsPath = "/web/connections"
  39. webFoldersPath = "/web/folders"
  40. webFolderPath = "/web/folder"
  41. webStaticFilesPath = "/static"
  42. maxRestoreSize = 10485760 // 10 MB
  43. maxRequestSize = 1048576 // 1MB
  44. )
  45. var (
  46. router *chi.Mux
  47. backupsPath string
  48. httpAuth httpAuthProvider
  49. certMgr *common.CertManager
  50. )
  51. // Conf httpd daemon configuration
  52. type Conf struct {
  53. // The port used for serving HTTP requests. 0 disable the HTTP server. Default: 8080
  54. BindPort int `json:"bind_port" mapstructure:"bind_port"`
  55. // The address to listen on. A blank value means listen on all available network interfaces. Default: "127.0.0.1"
  56. BindAddress string `json:"bind_address" mapstructure:"bind_address"`
  57. // Path to the HTML web templates. This can be an absolute path or a path relative to the config dir
  58. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  59. // Path to the static files for the web interface. This can be an absolute path or a path relative to the config dir.
  60. // If both TemplatesPath and StaticFilesPath are empty the built-in web interface will be disabled
  61. StaticFilesPath string `json:"static_files_path" mapstructure:"static_files_path"`
  62. // Path to the backup directory. This can be an absolute path or a path relative to the config dir
  63. BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
  64. // Path to a file used to store usernames and password for basic authentication.
  65. // This can be an absolute path or a path relative to the config dir.
  66. // We support HTTP basic authentication and the file format must conform to the one generated using the Apache
  67. // htpasswd tool. The supported password formats are bcrypt ($2y$ prefix) and md5 crypt ($apr1$ prefix).
  68. // If empty HTTP authentication is disabled
  69. AuthUserFile string `json:"auth_user_file" mapstructure:"auth_user_file"`
  70. // If files containing a certificate and matching private key for the server are provided the server will expect
  71. // HTTPS connections.
  72. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  73. // "paramchange" request to the running service on Windows.
  74. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  75. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  76. }
  77. type apiResponse struct {
  78. Error string `json:"error,omitempty"`
  79. Message string `json:"message"`
  80. }
  81. // Initialize configures and starts the HTTP server
  82. func (c Conf) Initialize(configDir string, enableProfiler bool) error {
  83. var err error
  84. logger.Debug(logSender, "", "initializing HTTP server with config %+v", c)
  85. backupsPath = getConfigPath(c.BackupsPath, configDir)
  86. staticFilesPath := getConfigPath(c.StaticFilesPath, configDir)
  87. templatesPath := getConfigPath(c.TemplatesPath, configDir)
  88. enableWebAdmin := len(staticFilesPath) > 0 || len(templatesPath) > 0
  89. if len(backupsPath) == 0 {
  90. return fmt.Errorf("Required directory is invalid, backup path %#v", backupsPath)
  91. }
  92. if enableWebAdmin && (len(staticFilesPath) == 0 || len(templatesPath) == 0) {
  93. return fmt.Errorf("Required directory is invalid, static file path: %#v template path: %#v",
  94. staticFilesPath, templatesPath)
  95. }
  96. authUserFile := getConfigPath(c.AuthUserFile, configDir)
  97. httpAuth, err = newBasicAuthProvider(authUserFile)
  98. if err != nil {
  99. return err
  100. }
  101. certificateFile := getConfigPath(c.CertificateFile, configDir)
  102. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  103. if enableWebAdmin {
  104. loadTemplates(templatesPath)
  105. } else {
  106. logger.Info(logSender, "", "built-in web interface disabled, please set templates_path and static_files_path to enable it")
  107. }
  108. initializeRouter(staticFilesPath, enableProfiler, enableWebAdmin)
  109. httpServer := &http.Server{
  110. Addr: fmt.Sprintf("%s:%d", c.BindAddress, c.BindPort),
  111. Handler: router,
  112. ReadTimeout: 60 * time.Second,
  113. WriteTimeout: 60 * time.Second,
  114. IdleTimeout: 120 * time.Second,
  115. MaxHeaderBytes: 1 << 16, // 64KB
  116. }
  117. if len(certificateFile) > 0 && len(certificateKeyFile) > 0 {
  118. certMgr, err = common.NewCertManager(certificateFile, certificateKeyFile, logSender)
  119. if err != nil {
  120. return err
  121. }
  122. config := &tls.Config{
  123. GetCertificate: certMgr.GetCertificateFunc(),
  124. MinVersion: tls.VersionTLS12,
  125. }
  126. httpServer.TLSConfig = config
  127. return httpServer.ListenAndServeTLS("", "")
  128. }
  129. return httpServer.ListenAndServe()
  130. }
  131. // ReloadTLSCertificate reloads the TLS certificate and key from the configured paths
  132. func ReloadTLSCertificate() error {
  133. if certMgr != nil {
  134. return certMgr.LoadCertificate(logSender)
  135. }
  136. return nil
  137. }
  138. func getConfigPath(name, configDir string) string {
  139. if !utils.IsFileInputValid(name) {
  140. return ""
  141. }
  142. if len(name) > 0 && !filepath.IsAbs(name) {
  143. return filepath.Join(configDir, name)
  144. }
  145. return name
  146. }