actions.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package common
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/drakkan/sftpgo/dataprovider"
  16. "github.com/drakkan/sftpgo/httpclient"
  17. "github.com/drakkan/sftpgo/logger"
  18. "github.com/drakkan/sftpgo/utils"
  19. )
  20. var (
  21. errUnconfiguredAction = errors.New("no hook is configured for this action")
  22. errNoHook = errors.New("unable to execute action, no hook defined")
  23. errUnexpectedHTTResponse = errors.New("unexpected HTTP response code")
  24. )
  25. // ProtocolActions defines the action to execute on file operations and SSH commands
  26. type ProtocolActions struct {
  27. // Valid values are download, upload, pre-delete, delete, rename, ssh_cmd. Empty slice to disable
  28. ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
  29. // Absolute path to an external program or an HTTP URL
  30. Hook string `json:"hook" mapstructure:"hook"`
  31. }
  32. var actionHandler ActionHandler = defaultActionHandler{}
  33. // InitializeActionHandler lets the user choose an action handler implementation.
  34. //
  35. // Do NOT call this function after application initialization.
  36. func InitializeActionHandler(handler ActionHandler) {
  37. actionHandler = handler
  38. }
  39. // SSHCommandActionNotification executes the defined action for the specified SSH command.
  40. func SSHCommandActionNotification(user *dataprovider.User, filePath, target, sshCmd string, err error) {
  41. notification := newActionNotification(user, operationSSHCmd, filePath, target, sshCmd, ProtocolSSH, 0, err)
  42. go actionHandler.Handle(notification) // nolint:errcheck
  43. }
  44. // ActionHandler handles a notification for a Protocol Action.
  45. type ActionHandler interface {
  46. Handle(notification ActionNotification) error
  47. }
  48. // ActionNotification defines a notification for a Protocol Action.
  49. type ActionNotification struct {
  50. Action string `json:"action"`
  51. Username string `json:"username"`
  52. Path string `json:"path"`
  53. TargetPath string `json:"target_path,omitempty"`
  54. SSHCmd string `json:"ssh_cmd,omitempty"`
  55. FileSize int64 `json:"file_size,omitempty"`
  56. FsProvider int `json:"fs_provider"`
  57. Bucket string `json:"bucket,omitempty"`
  58. Endpoint string `json:"endpoint,omitempty"`
  59. Status int `json:"status"`
  60. Protocol string `json:"protocol"`
  61. }
  62. func newActionNotification(
  63. user *dataprovider.User,
  64. operation, filePath, target, sshCmd, protocol string,
  65. fileSize int64,
  66. err error,
  67. ) ActionNotification {
  68. var bucket, endpoint string
  69. status := 1
  70. if user.FsConfig.Provider == dataprovider.S3FilesystemProvider {
  71. bucket = user.FsConfig.S3Config.Bucket
  72. endpoint = user.FsConfig.S3Config.Endpoint
  73. } else if user.FsConfig.Provider == dataprovider.GCSFilesystemProvider {
  74. bucket = user.FsConfig.GCSConfig.Bucket
  75. } else if user.FsConfig.Provider == dataprovider.AzureBlobFilesystemProvider {
  76. bucket = user.FsConfig.AzBlobConfig.Container
  77. if user.FsConfig.AzBlobConfig.SASURL != "" {
  78. endpoint = user.FsConfig.AzBlobConfig.SASURL
  79. } else {
  80. endpoint = user.FsConfig.AzBlobConfig.Endpoint
  81. }
  82. }
  83. if err == ErrQuotaExceeded {
  84. status = 2
  85. } else if err != nil {
  86. status = 0
  87. }
  88. return ActionNotification{
  89. Action: operation,
  90. Username: user.Username,
  91. Path: filePath,
  92. TargetPath: target,
  93. SSHCmd: sshCmd,
  94. FileSize: fileSize,
  95. FsProvider: int(user.FsConfig.Provider),
  96. Bucket: bucket,
  97. Endpoint: endpoint,
  98. Status: status,
  99. Protocol: protocol,
  100. }
  101. }
  102. type defaultActionHandler struct{}
  103. func (h defaultActionHandler) Handle(notification ActionNotification) error {
  104. if !utils.IsStringInSlice(notification.Action, Config.Actions.ExecuteOn) {
  105. return errUnconfiguredAction
  106. }
  107. if Config.Actions.Hook == "" {
  108. logger.Warn(notification.Protocol, "", "Unable to send notification, no hook is defined")
  109. return errNoHook
  110. }
  111. if strings.HasPrefix(Config.Actions.Hook, "http") {
  112. return h.handleHTTP(notification)
  113. }
  114. return h.handleCommand(notification)
  115. }
  116. func (h defaultActionHandler) handleHTTP(notification ActionNotification) error {
  117. u, err := url.Parse(Config.Actions.Hook)
  118. if err != nil {
  119. logger.Warn(notification.Protocol, "", "Invalid hook %#v for operation %#v: %v", Config.Actions.Hook, notification.Action, err)
  120. return err
  121. }
  122. startTime := time.Now()
  123. respCode := 0
  124. httpClient := httpclient.GetHTTPClient()
  125. var b bytes.Buffer
  126. _ = json.NewEncoder(&b).Encode(notification)
  127. resp, err := httpClient.Post(u.String(), "application/json", &b)
  128. if err == nil {
  129. respCode = resp.StatusCode
  130. resp.Body.Close()
  131. if respCode != http.StatusOK {
  132. err = errUnexpectedHTTResponse
  133. }
  134. }
  135. logger.Debug(notification.Protocol, "", "notified operation %#v to URL: %v status code: %v, elapsed: %v err: %v", notification.Action, u.String(), respCode, time.Since(startTime), err)
  136. return err
  137. }
  138. func (h defaultActionHandler) handleCommand(notification ActionNotification) error {
  139. if !filepath.IsAbs(Config.Actions.Hook) {
  140. err := fmt.Errorf("invalid notification command %#v", Config.Actions.Hook)
  141. logger.Warn(notification.Protocol, "", "unable to execute notification command: %v", err)
  142. return err
  143. }
  144. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  145. defer cancel()
  146. cmd := exec.CommandContext(ctx, Config.Actions.Hook, notification.Action, notification.Username, notification.Path, notification.TargetPath, notification.SSHCmd)
  147. cmd.Env = append(os.Environ(), notificationAsEnvVars(notification)...)
  148. startTime := time.Now()
  149. err := cmd.Run()
  150. logger.Debug(notification.Protocol, "", "executed command %#v with arguments: %#v, %#v, %#v, %#v, %#v, elapsed: %v, error: %v",
  151. Config.Actions.Hook, notification.Action, notification.Username, notification.Path, notification.TargetPath, notification.SSHCmd, time.Since(startTime), err)
  152. return err
  153. }
  154. func notificationAsEnvVars(notification ActionNotification) []string {
  155. return []string{
  156. fmt.Sprintf("SFTPGO_ACTION=%v", notification.Action),
  157. fmt.Sprintf("SFTPGO_ACTION_USERNAME=%v", notification.Username),
  158. fmt.Sprintf("SFTPGO_ACTION_PATH=%v", notification.Path),
  159. fmt.Sprintf("SFTPGO_ACTION_TARGET=%v", notification.TargetPath),
  160. fmt.Sprintf("SFTPGO_ACTION_SSH_CMD=%v", notification.SSHCmd),
  161. fmt.Sprintf("SFTPGO_ACTION_FILE_SIZE=%v", notification.FileSize),
  162. fmt.Sprintf("SFTPGO_ACTION_FS_PROVIDER=%v", notification.FsProvider),
  163. fmt.Sprintf("SFTPGO_ACTION_BUCKET=%v", notification.Bucket),
  164. fmt.Sprintf("SFTPGO_ACTION_ENDPOINT=%v", notification.Endpoint),
  165. fmt.Sprintf("SFTPGO_ACTION_STATUS=%v", notification.Status),
  166. fmt.Sprintf("SFTPGO_ACTION_PROTOCOL=%v", notification.Protocol),
  167. }
  168. }