actions.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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/v2/dataprovider"
  16. "github.com/drakkan/sftpgo/v2/httpclient"
  17. "github.com/drakkan/sftpgo/v2/logger"
  18. "github.com/drakkan/sftpgo/v2/sdk"
  19. "github.com/drakkan/sftpgo/v2/sdk/plugin"
  20. "github.com/drakkan/sftpgo/v2/util"
  21. )
  22. var (
  23. errUnconfiguredAction = errors.New("no hook is configured for this action")
  24. errNoHook = errors.New("unable to execute action, no hook defined")
  25. errUnexpectedHTTResponse = errors.New("unexpected HTTP response code")
  26. )
  27. // ProtocolActions defines the action to execute on file operations and SSH commands
  28. type ProtocolActions struct {
  29. // Valid values are download, upload, pre-delete, delete, rename, ssh_cmd. Empty slice to disable
  30. ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
  31. // Actions to be performed synchronously.
  32. // The pre-delete action is always executed synchronously while the other ones are asynchronous.
  33. // Executing an action synchronously means that SFTPGo will not return a result code to the client
  34. // (which is waiting for it) until your hook have completed its execution.
  35. ExecuteSync []string `json:"execute_sync" mapstructure:"execute_sync"`
  36. // Absolute path to an external program or an HTTP URL
  37. Hook string `json:"hook" mapstructure:"hook"`
  38. }
  39. var actionHandler ActionHandler = &defaultActionHandler{}
  40. // InitializeActionHandler lets the user choose an action handler implementation.
  41. //
  42. // Do NOT call this function after application initialization.
  43. func InitializeActionHandler(handler ActionHandler) {
  44. actionHandler = handler
  45. }
  46. // ExecutePreAction executes a pre-* action and returns the result
  47. func ExecutePreAction(user *dataprovider.User, operation, filePath, virtualPath, protocol string, fileSize int64, openFlags int) error {
  48. plugin.Handler.NotifyFsEvent(time.Now(), operation, user.Username, filePath, "", "", protocol, fileSize, nil)
  49. if !util.IsStringInSlice(operation, Config.Actions.ExecuteOn) {
  50. // for pre-delete we execute the internal handling on error, so we must return errUnconfiguredAction.
  51. // Other pre action will deny the operation on error so if we have no configuration we must return
  52. // a nil error
  53. if operation == operationPreDelete {
  54. return errUnconfiguredAction
  55. }
  56. return nil
  57. }
  58. notification := newActionNotification(user, operation, filePath, virtualPath, "", "", protocol, fileSize, openFlags, nil)
  59. return actionHandler.Handle(notification)
  60. }
  61. // ExecuteActionNotification executes the defined hook, if any, for the specified action
  62. func ExecuteActionNotification(user *dataprovider.User, operation, filePath, virtualPath, target, sshCmd, protocol string, fileSize int64, err error) {
  63. plugin.Handler.NotifyFsEvent(time.Now(), operation, user.Username, filePath, target, sshCmd, protocol, fileSize, err)
  64. notification := newActionNotification(user, operation, filePath, virtualPath, target, sshCmd, protocol, fileSize, 0, err)
  65. if util.IsStringInSlice(operation, Config.Actions.ExecuteSync) {
  66. actionHandler.Handle(notification) //nolint:errcheck
  67. return
  68. }
  69. go actionHandler.Handle(notification) //nolint:errcheck
  70. }
  71. // ActionHandler handles a notification for a Protocol Action.
  72. type ActionHandler interface {
  73. Handle(notification *ActionNotification) error
  74. }
  75. // ActionNotification defines a notification for a Protocol Action.
  76. type ActionNotification struct {
  77. Action string `json:"action"`
  78. Username string `json:"username"`
  79. Path string `json:"path"`
  80. TargetPath string `json:"target_path,omitempty"`
  81. SSHCmd string `json:"ssh_cmd,omitempty"`
  82. FileSize int64 `json:"file_size,omitempty"`
  83. FsProvider int `json:"fs_provider"`
  84. Bucket string `json:"bucket,omitempty"`
  85. Endpoint string `json:"endpoint,omitempty"`
  86. Status int `json:"status"`
  87. Protocol string `json:"protocol"`
  88. OpenFlags int `json:"open_flags,omitempty"`
  89. }
  90. func newActionNotification(
  91. user *dataprovider.User,
  92. operation, filePath, virtualPath, target, sshCmd, protocol string,
  93. fileSize int64,
  94. openFlags int,
  95. err error,
  96. ) *ActionNotification {
  97. var bucket, endpoint string
  98. status := 1
  99. fsConfig := user.GetFsConfigForPath(virtualPath)
  100. switch fsConfig.Provider {
  101. case sdk.S3FilesystemProvider:
  102. bucket = fsConfig.S3Config.Bucket
  103. endpoint = fsConfig.S3Config.Endpoint
  104. case sdk.GCSFilesystemProvider:
  105. bucket = fsConfig.GCSConfig.Bucket
  106. case sdk.AzureBlobFilesystemProvider:
  107. bucket = fsConfig.AzBlobConfig.Container
  108. if fsConfig.AzBlobConfig.Endpoint != "" {
  109. endpoint = fsConfig.AzBlobConfig.Endpoint
  110. }
  111. case sdk.SFTPFilesystemProvider:
  112. endpoint = fsConfig.SFTPConfig.Endpoint
  113. }
  114. if err == ErrQuotaExceeded {
  115. status = 2
  116. } else if err != nil {
  117. status = 0
  118. }
  119. return &ActionNotification{
  120. Action: operation,
  121. Username: user.Username,
  122. Path: filePath,
  123. TargetPath: target,
  124. SSHCmd: sshCmd,
  125. FileSize: fileSize,
  126. FsProvider: int(fsConfig.Provider),
  127. Bucket: bucket,
  128. Endpoint: endpoint,
  129. Status: status,
  130. Protocol: protocol,
  131. OpenFlags: openFlags,
  132. }
  133. }
  134. type defaultActionHandler struct{}
  135. func (h *defaultActionHandler) Handle(notification *ActionNotification) error {
  136. if !util.IsStringInSlice(notification.Action, Config.Actions.ExecuteOn) {
  137. return errUnconfiguredAction
  138. }
  139. if Config.Actions.Hook == "" {
  140. logger.Warn(notification.Protocol, "", "Unable to send notification, no hook is defined")
  141. return errNoHook
  142. }
  143. if strings.HasPrefix(Config.Actions.Hook, "http") {
  144. return h.handleHTTP(notification)
  145. }
  146. return h.handleCommand(notification)
  147. }
  148. func (h *defaultActionHandler) handleHTTP(notification *ActionNotification) error {
  149. u, err := url.Parse(Config.Actions.Hook)
  150. if err != nil {
  151. logger.Warn(notification.Protocol, "", "Invalid hook %#v for operation %#v: %v", Config.Actions.Hook, notification.Action, err)
  152. return err
  153. }
  154. startTime := time.Now()
  155. respCode := 0
  156. var b bytes.Buffer
  157. _ = json.NewEncoder(&b).Encode(notification)
  158. resp, err := httpclient.RetryablePost(Config.Actions.Hook, "application/json", &b)
  159. if err == nil {
  160. respCode = resp.StatusCode
  161. resp.Body.Close()
  162. if respCode != http.StatusOK {
  163. err = errUnexpectedHTTResponse
  164. }
  165. }
  166. logger.Debug(notification.Protocol, "", "notified operation %#v to URL: %v status code: %v, elapsed: %v err: %v",
  167. notification.Action, u.Redacted(), respCode, time.Since(startTime), err)
  168. return err
  169. }
  170. func (h *defaultActionHandler) handleCommand(notification *ActionNotification) error {
  171. if !filepath.IsAbs(Config.Actions.Hook) {
  172. err := fmt.Errorf("invalid notification command %#v", Config.Actions.Hook)
  173. logger.Warn(notification.Protocol, "", "unable to execute notification command: %v", err)
  174. return err
  175. }
  176. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  177. defer cancel()
  178. cmd := exec.CommandContext(ctx, Config.Actions.Hook, notification.Action, notification.Username, notification.Path, notification.TargetPath, notification.SSHCmd)
  179. cmd.Env = append(os.Environ(), notificationAsEnvVars(notification)...)
  180. startTime := time.Now()
  181. err := cmd.Run()
  182. logger.Debug(notification.Protocol, "", "executed command %#v with arguments: %#v, %#v, %#v, %#v, %#v, elapsed: %v, error: %v",
  183. Config.Actions.Hook, notification.Action, notification.Username, notification.Path, notification.TargetPath, notification.SSHCmd, time.Since(startTime), err)
  184. return err
  185. }
  186. func notificationAsEnvVars(notification *ActionNotification) []string {
  187. return []string{
  188. fmt.Sprintf("SFTPGO_ACTION=%v", notification.Action),
  189. fmt.Sprintf("SFTPGO_ACTION_USERNAME=%v", notification.Username),
  190. fmt.Sprintf("SFTPGO_ACTION_PATH=%v", notification.Path),
  191. fmt.Sprintf("SFTPGO_ACTION_TARGET=%v", notification.TargetPath),
  192. fmt.Sprintf("SFTPGO_ACTION_SSH_CMD=%v", notification.SSHCmd),
  193. fmt.Sprintf("SFTPGO_ACTION_FILE_SIZE=%v", notification.FileSize),
  194. fmt.Sprintf("SFTPGO_ACTION_FS_PROVIDER=%v", notification.FsProvider),
  195. fmt.Sprintf("SFTPGO_ACTION_BUCKET=%v", notification.Bucket),
  196. fmt.Sprintf("SFTPGO_ACTION_ENDPOINT=%v", notification.Endpoint),
  197. fmt.Sprintf("SFTPGO_ACTION_STATUS=%v", notification.Status),
  198. fmt.Sprintf("SFTPGO_ACTION_PROTOCOL=%v", notification.Protocol),
  199. fmt.Sprintf("SFTPGO_ACTION_OPEN_FLAGS=%v", notification.OpenFlags),
  200. }
  201. }