You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

278 lines
6.5 KiB

  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package webhook
  5. import (
  6. "context"
  7. "crypto/tls"
  8. "fmt"
  9. "io/ioutil"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "sync"
  15. "time"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/graceful"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. "github.com/gobwas/glob"
  21. "github.com/unknwon/com"
  22. )
  23. // Deliver deliver hook task
  24. func Deliver(t *models.HookTask) error {
  25. defer func() {
  26. err := recover()
  27. if err == nil {
  28. return
  29. }
  30. // There was a panic whilst delivering a hook...
  31. log.Error("PANIC whilst trying to deliver webhook[%d] for repo[%d] to %s Panic: %v\nStacktrace: %s", t.ID, t.RepoID, t.URL, err, log.Stack(2))
  32. }()
  33. t.IsDelivered = true
  34. var req *http.Request
  35. var err error
  36. switch t.HTTPMethod {
  37. case "":
  38. log.Info("HTTP Method for webhook %d empty, setting to POST as default", t.ID)
  39. fallthrough
  40. case http.MethodPost:
  41. switch t.ContentType {
  42. case models.ContentTypeJSON:
  43. req, err = http.NewRequest("POST", t.URL, strings.NewReader(t.PayloadContent))
  44. if err != nil {
  45. return err
  46. }
  47. req.Header.Set("Content-Type", "application/json")
  48. case models.ContentTypeForm:
  49. var forms = url.Values{
  50. "payload": []string{t.PayloadContent},
  51. }
  52. req, err = http.NewRequest("POST", t.URL, strings.NewReader(forms.Encode()))
  53. if err != nil {
  54. return err
  55. }
  56. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  57. }
  58. case http.MethodGet:
  59. u, err := url.Parse(t.URL)
  60. if err != nil {
  61. return err
  62. }
  63. vals := u.Query()
  64. vals["payload"] = []string{t.PayloadContent}
  65. u.RawQuery = vals.Encode()
  66. req, err = http.NewRequest("GET", u.String(), nil)
  67. if err != nil {
  68. return err
  69. }
  70. default:
  71. return fmt.Errorf("Invalid http method for webhook: [%d] %v", t.ID, t.HTTPMethod)
  72. }
  73. if t.Type == models.MATRIX {
  74. req, err = getMatrixHookRequest(t)
  75. if err != nil {
  76. return err
  77. }
  78. }
  79. req.Header.Add("X-Gitea-Delivery", t.UUID)
  80. req.Header.Add("X-Gitea-Event", t.EventType.Event())
  81. req.Header.Add("X-Gitea-Signature", t.Signature)
  82. req.Header.Add("X-Gogs-Delivery", t.UUID)
  83. req.Header.Add("X-Gogs-Event", t.EventType.Event())
  84. req.Header.Add("X-Gogs-Signature", t.Signature)
  85. req.Header["X-GitHub-Delivery"] = []string{t.UUID}
  86. req.Header["X-GitHub-Event"] = []string{t.EventType.Event()}
  87. // Record delivery information.
  88. t.RequestInfo = &models.HookRequest{
  89. Headers: map[string]string{},
  90. }
  91. for k, vals := range req.Header {
  92. t.RequestInfo.Headers[k] = strings.Join(vals, ",")
  93. }
  94. t.ResponseInfo = &models.HookResponse{
  95. Headers: map[string]string{},
  96. }
  97. defer func() {
  98. t.Delivered = time.Now().UnixNano()
  99. if t.IsSucceed {
  100. log.Trace("Hook delivered: %s", t.UUID)
  101. } else {
  102. log.Trace("Hook delivery failed: %s", t.UUID)
  103. }
  104. if err := models.UpdateHookTask(t); err != nil {
  105. log.Error("UpdateHookTask [%d]: %v", t.ID, err)
  106. }
  107. // Update webhook last delivery status.
  108. w, err := models.GetWebhookByID(t.HookID)
  109. if err != nil {
  110. log.Error("GetWebhookByID: %v", err)
  111. return
  112. }
  113. if t.IsSucceed {
  114. w.LastStatus = models.HookStatusSucceed
  115. } else {
  116. w.LastStatus = models.HookStatusFail
  117. }
  118. if err = models.UpdateWebhookLastStatus(w); err != nil {
  119. log.Error("UpdateWebhookLastStatus: %v", err)
  120. return
  121. }
  122. }()
  123. resp, err := webhookHTTPClient.Do(req)
  124. if err != nil {
  125. t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
  126. return err
  127. }
  128. defer resp.Body.Close()
  129. // Status code is 20x can be seen as succeed.
  130. t.IsSucceed = resp.StatusCode/100 == 2
  131. t.ResponseInfo.Status = resp.StatusCode
  132. for k, vals := range resp.Header {
  133. t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
  134. }
  135. p, err := ioutil.ReadAll(resp.Body)
  136. if err != nil {
  137. t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
  138. return err
  139. }
  140. t.ResponseInfo.Body = string(p)
  141. return nil
  142. }
  143. // DeliverHooks checks and delivers undelivered hooks.
  144. // FIXME: graceful: This would likely benefit from either a worker pool with dummy queue
  145. // or a full queue. Then more hooks could be sent at same time.
  146. func DeliverHooks(ctx context.Context) {
  147. select {
  148. case <-ctx.Done():
  149. return
  150. default:
  151. }
  152. tasks, err := models.FindUndeliveredHookTasks()
  153. if err != nil {
  154. log.Error("DeliverHooks: %v", err)
  155. return
  156. }
  157. // Update hook task status.
  158. for _, t := range tasks {
  159. select {
  160. case <-ctx.Done():
  161. return
  162. default:
  163. }
  164. if err = Deliver(t); err != nil {
  165. log.Error("deliver: %v", err)
  166. }
  167. }
  168. // Start listening on new hook requests.
  169. for {
  170. select {
  171. case <-ctx.Done():
  172. hookQueue.Close()
  173. return
  174. case repoIDStr := <-hookQueue.Queue():
  175. log.Trace("DeliverHooks [repo_id: %v]", repoIDStr)
  176. hookQueue.Remove(repoIDStr)
  177. repoID, err := com.StrTo(repoIDStr).Int64()
  178. if err != nil {
  179. log.Error("Invalid repo ID: %s", repoIDStr)
  180. continue
  181. }
  182. tasks, err := models.FindRepoUndeliveredHookTasks(repoID)
  183. if err != nil {
  184. log.Error("Get repository [%d] hook tasks: %v", repoID, err)
  185. continue
  186. }
  187. for _, t := range tasks {
  188. select {
  189. case <-ctx.Done():
  190. return
  191. default:
  192. }
  193. if err = Deliver(t); err != nil {
  194. log.Error("deliver: %v", err)
  195. }
  196. }
  197. }
  198. }
  199. }
  200. var (
  201. webhookHTTPClient *http.Client
  202. once sync.Once
  203. hostMatchers []glob.Glob
  204. )
  205. func webhookProxy() func(req *http.Request) (*url.URL, error) {
  206. if setting.Webhook.ProxyURL == "" {
  207. return http.ProxyFromEnvironment
  208. }
  209. once.Do(func() {
  210. for _, h := range setting.Webhook.ProxyHosts {
  211. if g, err := glob.Compile(h); err == nil {
  212. hostMatchers = append(hostMatchers, g)
  213. } else {
  214. log.Error("glob.Compile %s failed: %v", h, err)
  215. }
  216. }
  217. })
  218. return func(req *http.Request) (*url.URL, error) {
  219. for _, v := range hostMatchers {
  220. if v.Match(req.URL.Host) {
  221. return http.ProxyURL(setting.Webhook.ProxyURLFixed)(req)
  222. }
  223. }
  224. return http.ProxyFromEnvironment(req)
  225. }
  226. }
  227. // InitDeliverHooks starts the hooks delivery thread
  228. func InitDeliverHooks() {
  229. timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
  230. webhookHTTPClient = &http.Client{
  231. Transport: &http.Transport{
  232. TLSClientConfig: &tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify},
  233. Proxy: webhookProxy(),
  234. Dial: func(netw, addr string) (net.Conn, error) {
  235. conn, err := net.DialTimeout(netw, addr, timeout)
  236. if err != nil {
  237. return nil, err
  238. }
  239. return conn, conn.SetDeadline(time.Now().Add(timeout))
  240. },
  241. },
  242. }
  243. go graceful.GetManager().RunWithShutdownContext(DeliverHooks)
  244. }