actions.go 11 KB

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