httpd.go 5.2 KB

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