actions.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. Email: conn.User.Email,
  105. Object: nil,
  106. }
  107. executedSync, err := eventManager.handleFsEvent(params)
  108. if executedSync {
  109. return 2, err
  110. }
  111. }
  112. if !hasHook {
  113. return 0, nil
  114. }
  115. return actionHandler.Handle(event)
  116. }
  117. // ExecuteActionNotification executes the defined hook, if any, for the specified action
  118. func ExecuteActionNotification(conn *BaseConnection, operation, filePath, virtualPath, target, virtualTarget, sshCmd string,
  119. fileSize int64, err error, elapsed int64,
  120. ) error {
  121. hasNotifiersPlugin := plugin.Handler.HasNotifiers()
  122. hasHook := util.Contains(Config.Actions.ExecuteOn, operation)
  123. hasRules := eventManager.hasFsRules()
  124. if !hasHook && !hasNotifiersPlugin && !hasRules {
  125. return nil
  126. }
  127. notification := newActionNotification(&conn.User, operation, filePath, virtualPath, target, virtualTarget, sshCmd,
  128. conn.protocol, conn.GetRemoteIP(), conn.ID, fileSize, 0, conn.getNotificationStatus(err), elapsed)
  129. if hasNotifiersPlugin {
  130. plugin.Handler.NotifyFsEvent(notification)
  131. }
  132. if hasRules {
  133. params := EventParams{
  134. Name: notification.Username,
  135. Groups: conn.User.Groups,
  136. Event: notification.Action,
  137. Status: notification.Status,
  138. VirtualPath: notification.VirtualPath,
  139. FsPath: notification.Path,
  140. VirtualTargetPath: notification.VirtualTargetPath,
  141. FsTargetPath: notification.TargetPath,
  142. ObjectName: path.Base(notification.VirtualPath),
  143. FileSize: notification.FileSize,
  144. Elapsed: notification.Elapsed,
  145. Protocol: notification.Protocol,
  146. IP: notification.IP,
  147. Role: notification.Role,
  148. Timestamp: notification.Timestamp,
  149. Email: conn.User.Email,
  150. Object: nil,
  151. }
  152. if err != nil {
  153. params.AddError(fmt.Errorf("%q failed: %w", params.Event, err))
  154. }
  155. executedSync, err := eventManager.handleFsEvent(params)
  156. if executedSync {
  157. return err
  158. }
  159. }
  160. if hasHook {
  161. if util.Contains(Config.Actions.ExecuteSync, operation) {
  162. _, err := actionHandler.Handle(notification)
  163. return err
  164. }
  165. go func() {
  166. startNewHook()
  167. defer hookEnded()
  168. actionHandler.Handle(notification) //nolint:errcheck
  169. }()
  170. }
  171. return nil
  172. }
  173. // ActionHandler handles a notification for a Protocol Action.
  174. type ActionHandler interface {
  175. Handle(notification *notifier.FsEvent) (int, error)
  176. }
  177. func newActionNotification(
  178. user *dataprovider.User,
  179. operation, filePath, virtualPath, target, virtualTarget, sshCmd, protocol, ip, sessionID string,
  180. fileSize int64,
  181. openFlags, status int, elapsed int64,
  182. ) *notifier.FsEvent {
  183. var bucket, endpoint string
  184. fsConfig := user.GetFsConfigForPath(virtualPath)
  185. switch fsConfig.Provider {
  186. case sdk.S3FilesystemProvider:
  187. bucket = fsConfig.S3Config.Bucket
  188. endpoint = fsConfig.S3Config.Endpoint
  189. case sdk.GCSFilesystemProvider:
  190. bucket = fsConfig.GCSConfig.Bucket
  191. case sdk.AzureBlobFilesystemProvider:
  192. bucket = fsConfig.AzBlobConfig.Container
  193. if fsConfig.AzBlobConfig.Endpoint != "" {
  194. endpoint = fsConfig.AzBlobConfig.Endpoint
  195. }
  196. case sdk.SFTPFilesystemProvider:
  197. endpoint = fsConfig.SFTPConfig.Endpoint
  198. case sdk.HTTPFilesystemProvider:
  199. endpoint = fsConfig.HTTPConfig.Endpoint
  200. }
  201. return &notifier.FsEvent{
  202. Action: operation,
  203. Username: user.Username,
  204. Path: filePath,
  205. TargetPath: target,
  206. VirtualPath: virtualPath,
  207. VirtualTargetPath: virtualTarget,
  208. SSHCmd: sshCmd,
  209. FileSize: fileSize,
  210. FsProvider: int(fsConfig.Provider),
  211. Bucket: bucket,
  212. Endpoint: endpoint,
  213. Status: status,
  214. Protocol: protocol,
  215. IP: ip,
  216. SessionID: sessionID,
  217. OpenFlags: openFlags,
  218. Role: user.Role,
  219. Timestamp: time.Now().UnixNano(),
  220. Elapsed: elapsed,
  221. }
  222. }
  223. type defaultActionHandler struct{}
  224. func (h *defaultActionHandler) Handle(event *notifier.FsEvent) (int, error) {
  225. if !util.Contains(Config.Actions.ExecuteOn, event.Action) {
  226. return 0, nil
  227. }
  228. if Config.Actions.Hook == "" {
  229. logger.Warn(event.Protocol, "", "Unable to send notification, no hook is defined")
  230. return 0, nil
  231. }
  232. if strings.HasPrefix(Config.Actions.Hook, "http") {
  233. err := h.handleHTTP(event)
  234. return 1, err
  235. }
  236. err := h.handleCommand(event)
  237. return 1, err
  238. }
  239. func (h *defaultActionHandler) handleHTTP(event *notifier.FsEvent) error {
  240. u, err := url.Parse(Config.Actions.Hook)
  241. if err != nil {
  242. logger.Error(event.Protocol, "", "Invalid hook %q for operation %q: %v",
  243. Config.Actions.Hook, event.Action, err)
  244. return err
  245. }
  246. startTime := time.Now()
  247. respCode := 0
  248. var b bytes.Buffer
  249. _ = json.NewEncoder(&b).Encode(event)
  250. resp, err := httpclient.RetryablePost(Config.Actions.Hook, "application/json", &b)
  251. if err == nil {
  252. respCode = resp.StatusCode
  253. resp.Body.Close()
  254. if respCode != http.StatusOK {
  255. err = errUnexpectedHTTResponse
  256. }
  257. }
  258. logger.Debug(event.Protocol, "", "notified operation %q to URL: %s status code: %d, elapsed: %s err: %v",
  259. event.Action, u.Redacted(), respCode, time.Since(startTime), err)
  260. return err
  261. }
  262. func (h *defaultActionHandler) handleCommand(event *notifier.FsEvent) error {
  263. if !filepath.IsAbs(Config.Actions.Hook) {
  264. err := fmt.Errorf("invalid notification command %q", Config.Actions.Hook)
  265. logger.Warn(event.Protocol, "", "unable to execute notification command: %v", err)
  266. return err
  267. }
  268. timeout, env, args := command.GetConfig(Config.Actions.Hook, command.HookFsActions)
  269. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  270. defer cancel()
  271. cmd := exec.CommandContext(ctx, Config.Actions.Hook, args...)
  272. cmd.Env = append(env, notificationAsEnvVars(event)...)
  273. startTime := time.Now()
  274. err := cmd.Run()
  275. logger.Debug(event.Protocol, "", "executed command %q, elapsed: %s, error: %v",
  276. Config.Actions.Hook, time.Since(startTime), err)
  277. return err
  278. }
  279. func notificationAsEnvVars(event *notifier.FsEvent) []string {
  280. return []string{
  281. fmt.Sprintf("SFTPGO_ACTION=%s", event.Action),
  282. fmt.Sprintf("SFTPGO_ACTION_USERNAME=%s", event.Username),
  283. fmt.Sprintf("SFTPGO_ACTION_PATH=%s", event.Path),
  284. fmt.Sprintf("SFTPGO_ACTION_TARGET=%s", event.TargetPath),
  285. fmt.Sprintf("SFTPGO_ACTION_VIRTUAL_PATH=%s", event.VirtualPath),
  286. fmt.Sprintf("SFTPGO_ACTION_VIRTUAL_TARGET=%s", event.VirtualTargetPath),
  287. fmt.Sprintf("SFTPGO_ACTION_SSH_CMD=%s", event.SSHCmd),
  288. fmt.Sprintf("SFTPGO_ACTION_FILE_SIZE=%d", event.FileSize),
  289. fmt.Sprintf("SFTPGO_ACTION_ELAPSED=%d", event.Elapsed),
  290. fmt.Sprintf("SFTPGO_ACTION_FS_PROVIDER=%d", event.FsProvider),
  291. fmt.Sprintf("SFTPGO_ACTION_BUCKET=%s", event.Bucket),
  292. fmt.Sprintf("SFTPGO_ACTION_ENDPOINT=%s", event.Endpoint),
  293. fmt.Sprintf("SFTPGO_ACTION_STATUS=%d", event.Status),
  294. fmt.Sprintf("SFTPGO_ACTION_PROTOCOL=%s", event.Protocol),
  295. fmt.Sprintf("SFTPGO_ACTION_IP=%s", event.IP),
  296. fmt.Sprintf("SFTPGO_ACTION_SESSION_ID=%s", event.SessionID),
  297. fmt.Sprintf("SFTPGO_ACTION_OPEN_FLAGS=%d", event.OpenFlags),
  298. fmt.Sprintf("SFTPGO_ACTION_TIMESTAMP=%d", event.Timestamp),
  299. fmt.Sprintf("SFTPGO_ACTION_ROLE=%s", event.Role),
  300. }
  301. }