httpd.go 7.1 KB

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