actions.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. "net/url"
  23. "os/exec"
  24. "path"
  25. "path/filepath"
  26. "strings"
  27. "sync/atomic"
  28. "time"
  29. "github.com/sftpgo/sdk"
  30. "github.com/sftpgo/sdk/plugin/notifier"
  31. "github.com/drakkan/sftpgo/v2/internal/command"
  32. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  33. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  34. "github.com/drakkan/sftpgo/v2/internal/logger"
  35. "github.com/drakkan/sftpgo/v2/internal/plugin"
  36. "github.com/drakkan/sftpgo/v2/internal/util"
  37. )
  38. var (
  39. errUnexpectedHTTResponse = errors.New("unexpected HTTP hook response code")
  40. hooksConcurrencyGuard = make(chan struct{}, 150)
  41. activeHooks atomic.Int32
  42. )
  43. func startNewHook() {
  44. activeHooks.Add(1)
  45. hooksConcurrencyGuard <- struct{}{}
  46. }
  47. func hookEnded() {
  48. activeHooks.Add(-1)
  49. <-hooksConcurrencyGuard
  50. }
  51. // ProtocolActions defines the action to execute on file operations and SSH commands
  52. type ProtocolActions struct {
  53. // Valid values are download, upload, pre-delete, delete, rename, ssh_cmd. Empty slice to disable
  54. ExecuteOn []string `json:"execute_on" mapstructure:"execute_on"`
  55. // Actions to be performed synchronously.
  56. // The pre-delete action is always executed synchronously while the other ones are asynchronous.
  57. // Executing an action synchronously means that SFTPGo will not return a result code to the client
  58. // (which is waiting for it) until your hook have completed its execution.
  59. ExecuteSync []string `json:"execute_sync" mapstructure:"execute_sync"`
  60. // Absolute path to an external program or an HTTP URL
  61. Hook string `json:"hook" mapstructure:"hook"`
  62. }
  63. var actionHandler ActionHandler = &defaultActionHandler{}
  64. // InitializeActionHandler lets the user choose an action handler implementation.
  65. //
  66. // Do NOT call this function after application initialization.
  67. func InitializeActionHandler(handler ActionHandler) {
  68. actionHandler = handler
  69. }
  70. // ExecutePreAction executes a pre-* action and returns the result.
  71. // The returned status has the following meaning:
  72. // - 0 not executed
  73. // - 1 executed using an external hook
  74. // - 2 executed using the event manager
  75. func ExecutePreAction(conn *BaseConnection, operation, filePath, virtualPath string, fileSize int64, openFlags int) (int, error) {
  76. var event *notifier.FsEvent
  77. hasNotifiersPlugin := plugin.Handler.HasNotifiers()
  78. hasHook := util.Contains(Config.Actions.ExecuteOn, operation)
  79. hasRules := eventManager.hasFsRules()
  80. if !hasHook && !hasNotifiersPlugin && !hasRules {
  81. return 0, nil
  82. }
  83. event = newActionNotification(&conn.User, operation, filePath, virtualPath, "", "", "",
  84. conn.protocol, conn.GetRemoteIP(), conn.ID, fileSize, openFlags, conn.getNotificationStatus(nil), 0)
  85. if hasNotifiersPlugin {
  86. plugin.Handler.NotifyFsEvent(event)
  87. }
  88. if hasRules {
  89. params := EventParams{
  90. Name: event.Username,
  91. Groups: conn.User.Groups,
  92. Event: event.Action,
  93. Status: event.Status,
  94. VirtualPath: event.VirtualPath,
  95. FsPath: event.Path,
  96. VirtualTargetPath: event.VirtualTargetPath,
  97. FsTargetPath: event.TargetPath,
  98. ObjectName: path.Base(event.VirtualPath),
  99. FileSize: event.FileSize,
  100. Protocol: event.Protocol,
  101. IP: event.IP,
  102. Role: event.Role,
  103. Timestamp: event.Timestamp,
  104. Object: nil,
  105. }
  106. executedSync, err := eventManager.handleFsEvent(params)
  107. if executedSync {
  108. return 2, err
  109. }
  110. }
  111. if !hasHook {
  112. return 0, nil
  113. }
  114. return actionHandler.Handle(event)
  115. }
  116. // ExecuteActionNotification executes the defined hook, if any, for the specified action
  117. func ExecuteActionNotification(conn *BaseConnection, operation, filePath, virtualPath, target, virtualTarget, sshCmd string,
  118. fileSize int64, err error, elapsed int64,
  119. ) error {
  120. hasNotifiersPlugin := plugin.Handler.HasNotifiers()
  121. hasHook := util.Contains(Config.Actions.ExecuteOn, operation)
  122. hasRules := eventManager.hasFsRules()
  123. if !hasHook && !hasNotifiersPlugin && !hasRules {
  124. return nil
  125. }
  126. notification := newActionNotification(&conn.User, operation, filePath, virtualPath, target, virtualTarget, sshCmd,
  127. conn.protocol, conn.GetRemoteIP(), conn.ID, fileSize, 0, conn.getNotificationStatus(err), elapsed)
  128. if hasNotifiersPlugin {
  129. plugin.Handler.NotifyFsEvent(notification)
  130. }
  131. if hasRules {
  132. params := EventParams{
  133. Name: notification.Username,
  134. Groups: conn.User.Groups,
  135. Event: notification.Action,
  136. Status: notification.Status,
  137. VirtualPath: notification.VirtualPath,
  138. FsPath: notification.Path,
  139. VirtualTargetPath: notification.VirtualTargetPath,
  140. FsTargetPath: notification.TargetPath,
  141. ObjectName: path.Base(notification.VirtualPath),
  142. FileSize: notification.FileSize,
  143. Elapsed: notification.Elapsed,
  144. Protocol: notification.Protocol,
  145. IP: notification.IP,
  146. Role: notification.Role,
  147. Timestamp: notification.Timestamp,
  148. Object: nil,
  149. }
  150. if err != nil {
  151. params.AddError(fmt.Errorf("%q failed: %w", params.Event, err))
  152. }
  153. executedSync, err := eventManager.handleFsEvent(params)
  154. if executedSync {
  155. return err
  156. }
  157. }
  158. if hasHook {
  159. if util.Contains(Config.Actions.ExecuteSync, operation) {
  160. _, err := actionHandler.Handle(notification)
  161. return err
  162. }
  163. go func() {
  164. startNewHook()
  165. defer hookEnded()
  166. actionHandler.Handle(notification) //nolint:errcheck
  167. }()
  168. }
  169. return nil
  170. }
  171. // ActionHandler handles a notification for a Protocol Action.
  172. type ActionHandler interface {
  173. Handle(notification *notifier.FsEvent) (int, error)
  174. }
  175. func newActionNotification(
  176. user *dataprovider.User,
  177. operation, filePath, virtualPath, target, virtualTarget, sshCmd, protocol, ip, sessionID string,
  178. fileSize int64,
  179. openFlags, status int, elapsed int64,
  180. ) *notifier.FsEvent {
  181. var bucket, endpoint string
  182. fsConfig := user.GetFsConfigForPath(virtualPath)
  183. switch fsConfig.Provider {
  184. case sdk.S3FilesystemProvider:
  185. bucket = fsConfig.S3Config.Bucket
  186. endpoint = fsConfig.S3Config.Endpoint
  187. case sdk.GCSFilesystemProvider:
  188. bucket = fsConfig.GCSConfig.Bucket
  189. case sdk.AzureBlobFilesystemProvider:
  190. bucket = fsConfig.AzBlobConfig.Container
  191. if fsConfig.AzBlobConfig.Endpoint != "" {
  192. endpoint = fsConfig.AzBlobConfig.Endpoint
  193. }
  194. case sdk.SFTPFilesystemProvider:
  195. endpoint = fsConfig.SFTPConfig.Endpoint
  196. case sdk.HTTPFilesystemProvider:
  197. endpoint = fsConfig.HTTPConfig.Endpoint
  198. }
  199. return &notifier.FsEvent{
  200. Action: operation,
  201. Username: user.Username,
  202. Path: filePath,
  203. TargetPath: target,
  204. VirtualPath: virtualPath,
  205. VirtualTargetPath: virtualTarget,
  206. SSHCmd: sshCmd,
  207. FileSize: fileSize,
  208. FsProvider: int(fsConfig.Provider),
  209. Bucket: bucket,
  210. Endpoint: endpoint,
  211. Status: status,
  212. Protocol: protocol,
  213. IP: ip,
  214. SessionID: sessionID,
  215. OpenFlags: openFlags,
  216. Role: user.Role,
  217. Timestamp: time.Now().UnixNano(),
  218. Elapsed: elapsed,
  219. }
  220. }
  221. type defaultActionHandler struct{}
  222. func (h *defaultActionHandler) Handle(event *notifier.FsEvent) (int, error) {
  223. if !util.Contains(Config.Actions.ExecuteOn, event.Action) {
  224. return 0, nil
  225. }
  226. if Config.Actions.Hook == "" {
  227. logger.Warn(event.Protocol, "", "Unable to send notification, no hook is defined")
  228. return 0, nil
  229. }
  230. if strings.HasPrefix(Config.Actions.Hook, "http") {
  231. err := h.handleHTTP(event)
  232. return 1, err
  233. }
  234. err := h.handleCommand(event)
  235. return 1, err
  236. }
  237. func (h *defaultActionHandler) handleHTTP(event *notifier.FsEvent) error {
  238. u, err := url.Parse(Config.Actions.Hook)
  239. if err != nil {
  240. logger.Error(event.Protocol, "", "Invalid hook %q for operation %q: %v",
  241. Config.Actions.Hook, event.Action, err)
  242. return err
  243. }
  244. startTime := time.Now()
  245. respCode := 0
  246. var b bytes.Buffer
  247. _ = json.NewEncoder(&b).Encode(event)
  248. resp, err := httpclient.RetryablePost(Config.Actions.Hook, "application/json", &b)
  249. if err == nil {
  250. respCode = resp.StatusCode
  251. resp.Body.Close()
  252. if respCode != http.StatusOK {
  253. err = errUnexpectedHTTResponse
  254. }
  255. }
  256. logger.Debug(event.Protocol, "", "notified operation %q to URL: %s status code: %d, elapsed: %s err: %v",
  257. event.Action, u.Redacted(), respCode, time.Since(startTime), err)
  258. return err
  259. }
  260. func (h *defaultActionHandler) handleCommand(event *notifier.FsEvent) error {
  261. if !filepath.IsAbs(Config.Actions.Hook) {
  262. err := fmt.Errorf("invalid notification command %q", Config.Actions.Hook)
  263. logger.Warn(event.Protocol, "", "unable to execute notification command: %v", err)
  264. return err
  265. }
  266. timeout, env, args := command.GetConfig(Config.Actions.Hook, command.HookFsActions)
  267. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  268. defer cancel()
  269. cmd := exec.CommandContext(ctx, Config.Actions.Hook, args...)
  270. cmd.Env = append(env, notificationAsEnvVars(event)...)
  271. startTime := time.Now()
  272. err := cmd.Run()
  273. logger.Debug(event.Protocol, "", "executed command %q, elapsed: %s, error: %v",
  274. Config.Actions.Hook, time.Since(startTime), err)
  275. return err
  276. }
  277. func notificationAsEnvVars(event *notifier.FsEvent) []string {
  278. return []string{
  279. fmt.Sprintf("SFTPGO_ACTION=%s", event.Action),
  280. fmt.Sprintf("SFTPGO_ACTION_USERNAME=%s", event.Username),
  281. fmt.Sprintf("SFTPGO_ACTION_PATH=%s", event.Path),
  282. fmt.Sprintf("SFTPGO_ACTION_TARGET=%s", event.TargetPath),
  283. fmt.Sprintf("SFTPGO_ACTION_VIRTUAL_PATH=%s", event.VirtualPath),
  284. fmt.Sprintf("SFTPGO_ACTION_VIRTUAL_TARGET=%s", event.VirtualTargetPath),
  285. fmt.Sprintf("SFTPGO_ACTION_SSH_CMD=%s", event.SSHCmd),
  286. fmt.Sprintf("SFTPGO_ACTION_FILE_SIZE=%d", event.FileSize),
  287. fmt.Sprintf("SFTPGO_ACTION_ELAPSED=%d", event.Elapsed),
  288. fmt.Sprintf("SFTPGO_ACTION_FS_PROVIDER=%d", event.FsProvider),
  289. fmt.Sprintf("SFTPGO_ACTION_BUCKET=%s", event.Bucket),
  290. fmt.Sprintf("SFTPGO_ACTION_ENDPOINT=%s", event.Endpoint),
  291. fmt.Sprintf("SFTPGO_ACTION_STATUS=%d", event.Status),
  292. fmt.Sprintf("SFTPGO_ACTION_PROTOCOL=%s", event.Protocol),
  293. fmt.Sprintf("SFTPGO_ACTION_IP=%s", event.IP),
  294. fmt.Sprintf("SFTPGO_ACTION_SESSION_ID=%s", event.SessionID),
  295. fmt.Sprintf("SFTPGO_ACTION_OPEN_FLAGS=%d", event.OpenFlags),
  296. fmt.Sprintf("SFTPGO_ACTION_TIMESTAMP=%d", event.Timestamp),
  297. fmt.Sprintf("SFTPGO_ACTION_ROLE=%s", event.Role),
  298. }
  299. }