actions.go 11 KB

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