gitea源码

hook.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "bufio"
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "io"
  10. "os"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/git/gitcmd"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/private"
  18. repo_module "code.gitea.io/gitea/modules/repository"
  19. "code.gitea.io/gitea/modules/setting"
  20. "github.com/urfave/cli/v3"
  21. )
  22. const (
  23. hookBatchSize = 500
  24. )
  25. var (
  26. // CmdHook represents the available hooks sub-command.
  27. CmdHook = &cli.Command{
  28. Name: "hook",
  29. Usage: "(internal) Should only be called by Git",
  30. Hidden: true, // internal commands shouldn't be visible
  31. Description: "Delegate commands to corresponding Git hooks",
  32. Before: PrepareConsoleLoggerLevel(log.FATAL),
  33. Commands: []*cli.Command{
  34. subcmdHookPreReceive,
  35. subcmdHookUpdate,
  36. subcmdHookPostReceive,
  37. subcmdHookProcReceive,
  38. },
  39. }
  40. subcmdHookPreReceive = &cli.Command{
  41. Name: "pre-receive",
  42. Usage: "Delegate pre-receive Git hook",
  43. Description: "This command should only be called by Git",
  44. Action: runHookPreReceive,
  45. Flags: []cli.Flag{
  46. &cli.BoolFlag{
  47. Name: "debug",
  48. },
  49. },
  50. }
  51. subcmdHookUpdate = &cli.Command{
  52. Name: "update",
  53. Usage: "Delegate update Git hook",
  54. Description: "This command should only be called by Git",
  55. Action: runHookUpdate,
  56. Flags: []cli.Flag{
  57. &cli.BoolFlag{
  58. Name: "debug",
  59. },
  60. },
  61. }
  62. subcmdHookPostReceive = &cli.Command{
  63. Name: "post-receive",
  64. Usage: "Delegate post-receive Git hook",
  65. Description: "This command should only be called by Git",
  66. Action: runHookPostReceive,
  67. Flags: []cli.Flag{
  68. &cli.BoolFlag{
  69. Name: "debug",
  70. },
  71. },
  72. }
  73. // Note: new hook since git 2.29
  74. subcmdHookProcReceive = &cli.Command{
  75. Name: "proc-receive",
  76. Usage: "Delegate proc-receive Git hook",
  77. Description: "This command should only be called by Git",
  78. Action: runHookProcReceive,
  79. Flags: []cli.Flag{
  80. &cli.BoolFlag{
  81. Name: "debug",
  82. },
  83. },
  84. }
  85. )
  86. type delayWriter struct {
  87. internal io.Writer
  88. buf *bytes.Buffer
  89. timer *time.Timer
  90. }
  91. func newDelayWriter(internal io.Writer, delay time.Duration) *delayWriter {
  92. timer := time.NewTimer(delay)
  93. return &delayWriter{
  94. internal: internal,
  95. buf: &bytes.Buffer{},
  96. timer: timer,
  97. }
  98. }
  99. func (d *delayWriter) Write(p []byte) (n int, err error) {
  100. if d.buf != nil {
  101. select {
  102. case <-d.timer.C:
  103. _, err := d.internal.Write(d.buf.Bytes())
  104. if err != nil {
  105. return 0, err
  106. }
  107. d.buf = nil
  108. return d.internal.Write(p)
  109. default:
  110. return d.buf.Write(p)
  111. }
  112. }
  113. return d.internal.Write(p)
  114. }
  115. func (d *delayWriter) WriteString(s string) (n int, err error) {
  116. if d.buf != nil {
  117. select {
  118. case <-d.timer.C:
  119. _, err := d.internal.Write(d.buf.Bytes())
  120. if err != nil {
  121. return 0, err
  122. }
  123. d.buf = nil
  124. return d.internal.Write([]byte(s))
  125. default:
  126. return d.buf.WriteString(s)
  127. }
  128. }
  129. return d.internal.Write([]byte(s))
  130. }
  131. func (d *delayWriter) Close() error {
  132. if d == nil {
  133. return nil
  134. }
  135. stopped := d.timer.Stop()
  136. if stopped || d.buf == nil {
  137. return nil
  138. }
  139. _, err := d.internal.Write(d.buf.Bytes())
  140. d.buf = nil
  141. return err
  142. }
  143. type nilWriter struct{}
  144. func (n *nilWriter) Write(p []byte) (int, error) {
  145. return len(p), nil
  146. }
  147. func (n *nilWriter) WriteString(s string) (int, error) {
  148. return len(s), nil
  149. }
  150. func runHookPreReceive(ctx context.Context, c *cli.Command) error {
  151. if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {
  152. return nil
  153. }
  154. setup(ctx, c.Bool("debug"))
  155. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  156. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  157. return fail(ctx, `Rejecting changes as Gitea environment not set.
  158. If you are pushing over SSH you must push with a key managed by
  159. Gitea or set your environment appropriately.`, "")
  160. }
  161. return nil
  162. }
  163. // the environment is set by serv command
  164. isWiki, _ := strconv.ParseBool(os.Getenv(repo_module.EnvRepoIsWiki))
  165. username := os.Getenv(repo_module.EnvRepoUsername)
  166. reponame := os.Getenv(repo_module.EnvRepoName)
  167. userID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  168. prID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPRID), 10, 64)
  169. deployKeyID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvDeployKeyID), 10, 64)
  170. actionPerm, _ := strconv.ParseInt(os.Getenv(repo_module.EnvActionPerm), 10, 64)
  171. hookOptions := private.HookOptions{
  172. UserID: userID,
  173. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  174. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  175. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  176. GitPushOptions: pushOptions(),
  177. PullRequestID: prID,
  178. DeployKeyID: deployKeyID,
  179. ActionPerm: int(actionPerm),
  180. }
  181. scanner := bufio.NewScanner(os.Stdin)
  182. oldCommitIDs := make([]string, hookBatchSize)
  183. newCommitIDs := make([]string, hookBatchSize)
  184. refFullNames := make([]git.RefName, hookBatchSize)
  185. count := 0
  186. total := 0
  187. lastline := 0
  188. var out io.Writer
  189. out = &nilWriter{}
  190. if setting.Git.VerbosePush {
  191. if setting.Git.VerbosePushDelay > 0 {
  192. dWriter := newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  193. defer dWriter.Close()
  194. out = dWriter
  195. } else {
  196. out = os.Stdout
  197. }
  198. }
  199. supportProcReceive := git.DefaultFeatures().SupportProcReceive
  200. for scanner.Scan() {
  201. // TODO: support news feeds for wiki
  202. if isWiki {
  203. continue
  204. }
  205. fields := bytes.Fields(scanner.Bytes())
  206. if len(fields) != 3 {
  207. continue
  208. }
  209. oldCommitID := string(fields[0])
  210. newCommitID := string(fields[1])
  211. refFullName := git.RefName(fields[2])
  212. total++
  213. lastline++
  214. // If the ref is a branch or tag, check if it's protected
  215. // if supportProcReceive all ref should be checked because
  216. // permission check was delayed
  217. if supportProcReceive || refFullName.IsBranch() || refFullName.IsTag() {
  218. oldCommitIDs[count] = oldCommitID
  219. newCommitIDs[count] = newCommitID
  220. refFullNames[count] = refFullName
  221. count++
  222. fmt.Fprintf(out, "*")
  223. if count >= hookBatchSize {
  224. fmt.Fprintf(out, " Checking %d references\n", count)
  225. hookOptions.OldCommitIDs = oldCommitIDs
  226. hookOptions.NewCommitIDs = newCommitIDs
  227. hookOptions.RefFullNames = refFullNames
  228. extra := private.HookPreReceive(ctx, username, reponame, hookOptions)
  229. if extra.HasError() {
  230. return fail(ctx, extra.UserMsg, "HookPreReceive(batch) failed: %v", extra.Error)
  231. }
  232. count = 0
  233. lastline = 0
  234. }
  235. } else {
  236. fmt.Fprintf(out, ".")
  237. }
  238. if lastline >= hookBatchSize {
  239. fmt.Fprintf(out, "\n")
  240. lastline = 0
  241. }
  242. }
  243. if count > 0 {
  244. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  245. hookOptions.NewCommitIDs = newCommitIDs[:count]
  246. hookOptions.RefFullNames = refFullNames[:count]
  247. fmt.Fprintf(out, " Checking %d references\n", count)
  248. extra := private.HookPreReceive(ctx, username, reponame, hookOptions)
  249. if extra.HasError() {
  250. return fail(ctx, extra.UserMsg, "HookPreReceive(last) failed: %v", extra.Error)
  251. }
  252. } else if lastline > 0 {
  253. fmt.Fprintf(out, "\n")
  254. }
  255. fmt.Fprintf(out, "Checked %d references in total\n", total)
  256. return nil
  257. }
  258. // runHookUpdate avoid to do heavy operations on update hook because it will be
  259. // invoked for every ref update which does not like pre-receive and post-receive
  260. func runHookUpdate(_ context.Context, c *cli.Command) error {
  261. if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {
  262. return nil
  263. }
  264. // Update is empty and is kept only for backwards compatibility
  265. if len(os.Args) < 3 {
  266. return nil
  267. }
  268. refName := git.RefName(os.Args[len(os.Args)-3])
  269. if refName.IsPull() {
  270. // ignore update to refs/pull/xxx/head, so we don't need to output any information
  271. os.Exit(1)
  272. }
  273. return nil
  274. }
  275. func runHookPostReceive(ctx context.Context, c *cli.Command) error {
  276. setup(ctx, c.Bool("debug"))
  277. // First of all run update-server-info no matter what
  278. if _, _, err := gitcmd.NewCommand("update-server-info").RunStdString(ctx, nil); err != nil {
  279. return fmt.Errorf("failed to call 'git update-server-info': %w", err)
  280. }
  281. // Now if we're an internal don't do anything else
  282. if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {
  283. return nil
  284. }
  285. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  286. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  287. return fail(ctx, `Rejecting changes as Gitea environment not set.
  288. If you are pushing over SSH you must push with a key managed by
  289. Gitea or set your environment appropriately.`, "")
  290. }
  291. return nil
  292. }
  293. var out io.Writer
  294. var dWriter *delayWriter
  295. out = &nilWriter{}
  296. if setting.Git.VerbosePush {
  297. if setting.Git.VerbosePushDelay > 0 {
  298. dWriter = newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  299. defer dWriter.Close()
  300. out = dWriter
  301. } else {
  302. out = os.Stdout
  303. }
  304. }
  305. // the environment is set by serv command
  306. repoUser := os.Getenv(repo_module.EnvRepoUsername)
  307. isWiki, _ := strconv.ParseBool(os.Getenv(repo_module.EnvRepoIsWiki))
  308. repoName := os.Getenv(repo_module.EnvRepoName)
  309. pusherID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  310. prID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPRID), 10, 64)
  311. pusherName := os.Getenv(repo_module.EnvPusherName)
  312. hookOptions := private.HookOptions{
  313. UserName: pusherName,
  314. UserID: pusherID,
  315. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  316. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  317. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  318. GitPushOptions: pushOptions(),
  319. PullRequestID: prID,
  320. PushTrigger: repo_module.PushTrigger(os.Getenv(repo_module.EnvPushTrigger)),
  321. }
  322. oldCommitIDs := make([]string, hookBatchSize)
  323. newCommitIDs := make([]string, hookBatchSize)
  324. refFullNames := make([]git.RefName, hookBatchSize)
  325. count := 0
  326. total := 0
  327. wasEmpty := false
  328. masterPushed := false
  329. results := make([]private.HookPostReceiveBranchResult, 0)
  330. scanner := bufio.NewScanner(os.Stdin)
  331. for scanner.Scan() {
  332. // TODO: support news feeds for wiki
  333. if isWiki {
  334. continue
  335. }
  336. fields := bytes.Fields(scanner.Bytes())
  337. if len(fields) != 3 {
  338. continue
  339. }
  340. fmt.Fprintf(out, ".")
  341. oldCommitIDs[count] = string(fields[0])
  342. newCommitIDs[count] = string(fields[1])
  343. refFullNames[count] = git.RefName(fields[2])
  344. commitID, _ := git.NewIDFromString(newCommitIDs[count])
  345. if refFullNames[count] == git.BranchPrefix+"master" && !commitID.IsZero() && count == total {
  346. masterPushed = true
  347. }
  348. count++
  349. total++
  350. if count >= hookBatchSize {
  351. fmt.Fprintf(out, " Processing %d references\n", count)
  352. hookOptions.OldCommitIDs = oldCommitIDs
  353. hookOptions.NewCommitIDs = newCommitIDs
  354. hookOptions.RefFullNames = refFullNames
  355. resp, extra := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
  356. if extra.HasError() {
  357. _ = dWriter.Close()
  358. hookPrintResults(results)
  359. return fail(ctx, extra.UserMsg, "HookPostReceive failed: %v", extra.Error)
  360. }
  361. wasEmpty = wasEmpty || resp.RepoWasEmpty
  362. results = append(results, resp.Results...)
  363. count = 0
  364. }
  365. }
  366. if count == 0 {
  367. if wasEmpty && masterPushed {
  368. // We need to tell the repo to reset the default branch to master
  369. extra := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
  370. if extra.HasError() {
  371. return fail(ctx, extra.UserMsg, "SetDefaultBranch failed: %v", extra.Error)
  372. }
  373. }
  374. fmt.Fprintf(out, "Processed %d references in total\n", total)
  375. _ = dWriter.Close()
  376. hookPrintResults(results)
  377. return nil
  378. }
  379. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  380. hookOptions.NewCommitIDs = newCommitIDs[:count]
  381. hookOptions.RefFullNames = refFullNames[:count]
  382. fmt.Fprintf(out, " Processing %d references\n", count)
  383. resp, extra := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
  384. if resp == nil {
  385. _ = dWriter.Close()
  386. hookPrintResults(results)
  387. return fail(ctx, extra.UserMsg, "HookPostReceive failed: %v", extra.Error)
  388. }
  389. wasEmpty = wasEmpty || resp.RepoWasEmpty
  390. results = append(results, resp.Results...)
  391. fmt.Fprintf(out, "Processed %d references in total\n", total)
  392. if wasEmpty && masterPushed {
  393. // We need to tell the repo to reset the default branch to master
  394. extra := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
  395. if extra.HasError() {
  396. return fail(ctx, extra.UserMsg, "SetDefaultBranch failed: %v", extra.Error)
  397. }
  398. }
  399. _ = dWriter.Close()
  400. hookPrintResults(results)
  401. return nil
  402. }
  403. func hookPrintResults(results []private.HookPostReceiveBranchResult) {
  404. for _, res := range results {
  405. hookPrintResult(res.Message, res.Create, res.Branch, res.URL)
  406. }
  407. }
  408. func hookPrintResult(output, isCreate bool, branch, url string) {
  409. if !output {
  410. return
  411. }
  412. fmt.Fprintln(os.Stderr, "")
  413. if isCreate {
  414. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", branch)
  415. fmt.Fprintf(os.Stderr, " %s\n", url)
  416. } else {
  417. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  418. fmt.Fprintf(os.Stderr, " %s\n", url)
  419. }
  420. fmt.Fprintln(os.Stderr, "")
  421. _ = os.Stderr.Sync()
  422. }
  423. func pushOptions() map[string]string {
  424. opts := make(map[string]string)
  425. if pushCount, err := strconv.Atoi(os.Getenv(private.GitPushOptionCount)); err == nil {
  426. for idx := range pushCount {
  427. opt := os.Getenv(fmt.Sprintf("GIT_PUSH_OPTION_%d", idx))
  428. kv := strings.SplitN(opt, "=", 2)
  429. if len(kv) == 2 {
  430. opts[kv[0]] = kv[1]
  431. }
  432. }
  433. }
  434. return opts
  435. }
  436. func runHookProcReceive(ctx context.Context, c *cli.Command) error {
  437. setup(ctx, c.Bool("debug"))
  438. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  439. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  440. return fail(ctx, `Rejecting changes as Gitea environment not set.
  441. If you are pushing over SSH you must push with a key managed by
  442. Gitea or set your environment appropriately.`, "")
  443. }
  444. return nil
  445. }
  446. if !git.DefaultFeatures().SupportProcReceive {
  447. return fail(ctx, "No proc-receive support", "current git version doesn't support proc-receive.")
  448. }
  449. reader := bufio.NewReader(os.Stdin)
  450. repoUser := os.Getenv(repo_module.EnvRepoUsername)
  451. repoName := os.Getenv(repo_module.EnvRepoName)
  452. pusherID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  453. pusherName := os.Getenv(repo_module.EnvPusherName)
  454. // 1. Version and features negotiation.
  455. // S: PKT-LINE(version=1\0push-options atomic...) / PKT-LINE(version=1\n)
  456. // S: flush-pkt
  457. // H: PKT-LINE(version=1\0push-options...)
  458. // H: flush-pkt
  459. rs, err := readPktLine(ctx, reader, pktLineTypeData)
  460. if err != nil {
  461. return err
  462. }
  463. const VersionHead string = "version=1"
  464. var (
  465. hasPushOptions bool
  466. response = []byte(VersionHead)
  467. requestOptions []string
  468. )
  469. index := bytes.IndexByte(rs.Data, byte(0))
  470. if index >= len(rs.Data) {
  471. return fail(ctx, "Protocol: format error", "pkt-line: format error %s", rs.Data)
  472. }
  473. if index < 0 {
  474. if len(rs.Data) == 10 && rs.Data[9] == '\n' {
  475. index = 9
  476. } else {
  477. return fail(ctx, "Protocol: format error", "pkt-line: format error %s", rs.Data)
  478. }
  479. }
  480. if string(rs.Data[0:index]) != VersionHead {
  481. return fail(ctx, "Protocol: version error", "Received unsupported version: %s", string(rs.Data[0:index]))
  482. }
  483. requestOptions = strings.Split(string(rs.Data[index+1:]), " ")
  484. for _, option := range requestOptions {
  485. if strings.HasPrefix(option, "push-options") {
  486. response = append(response, byte(0))
  487. response = append(response, []byte("push-options")...)
  488. hasPushOptions = true
  489. }
  490. }
  491. response = append(response, '\n')
  492. _, err = readPktLine(ctx, reader, pktLineTypeFlush)
  493. if err != nil {
  494. return err
  495. }
  496. err = writeDataPktLine(ctx, os.Stdout, response)
  497. if err != nil {
  498. return err
  499. }
  500. err = writeFlushPktLine(ctx, os.Stdout)
  501. if err != nil {
  502. return err
  503. }
  504. // 2. receive commands from server.
  505. // S: PKT-LINE(<old-oid> <new-oid> <ref>)
  506. // S: ... ...
  507. // S: flush-pkt
  508. // # [receive push-options]
  509. // S: PKT-LINE(push-option)
  510. // S: ... ...
  511. // S: flush-pkt
  512. hookOptions := private.HookOptions{
  513. UserName: pusherName,
  514. UserID: pusherID,
  515. GitPushOptions: make(map[string]string),
  516. }
  517. hookOptions.OldCommitIDs = make([]string, 0, hookBatchSize)
  518. hookOptions.NewCommitIDs = make([]string, 0, hookBatchSize)
  519. hookOptions.RefFullNames = make([]git.RefName, 0, hookBatchSize)
  520. for {
  521. // note: pktLineTypeUnknow means pktLineTypeFlush and pktLineTypeData all allowed
  522. rs, err = readPktLine(ctx, reader, pktLineTypeUnknow)
  523. if err != nil {
  524. return err
  525. }
  526. if rs.Type == pktLineTypeFlush {
  527. break
  528. }
  529. t := strings.SplitN(string(rs.Data), " ", 3)
  530. if len(t) != 3 {
  531. continue
  532. }
  533. hookOptions.OldCommitIDs = append(hookOptions.OldCommitIDs, t[0])
  534. hookOptions.NewCommitIDs = append(hookOptions.NewCommitIDs, t[1])
  535. hookOptions.RefFullNames = append(hookOptions.RefFullNames, git.RefName(t[2]))
  536. }
  537. if hasPushOptions {
  538. for {
  539. rs, err = readPktLine(ctx, reader, pktLineTypeUnknow)
  540. if err != nil {
  541. return err
  542. }
  543. if rs.Type == pktLineTypeFlush {
  544. break
  545. }
  546. hookOptions.GitPushOptions.AddFromKeyValue(string(rs.Data))
  547. }
  548. }
  549. // 3. run hook
  550. resp, extra := private.HookProcReceive(ctx, repoUser, repoName, hookOptions)
  551. if extra.HasError() {
  552. return fail(ctx, extra.UserMsg, "HookProcReceive failed: %v", extra.Error)
  553. }
  554. // 4. response result to service
  555. // # a. OK, but has an alternate reference. The alternate reference name
  556. // # and other status can be given in option directives.
  557. // H: PKT-LINE(ok <ref>)
  558. // H: PKT-LINE(option refname <refname>)
  559. // H: PKT-LINE(option old-oid <old-oid>)
  560. // H: PKT-LINE(option new-oid <new-oid>)
  561. // H: PKT-LINE(option forced-update)
  562. // H: ... ...
  563. // H: flush-pkt
  564. // # b. NO, I reject it.
  565. // H: PKT-LINE(ng <ref> <reason>)
  566. // # c. Fall through, let 'receive-pack' to execute it.
  567. // H: PKT-LINE(ok <ref>)
  568. // H: PKT-LINE(option fall-through)
  569. for _, rs := range resp.Results {
  570. if len(rs.Err) > 0 {
  571. err = writeDataPktLine(ctx, os.Stdout, []byte("ng "+rs.OriginalRef.String()+" "+rs.Err))
  572. if err != nil {
  573. return err
  574. }
  575. continue
  576. }
  577. if rs.IsNotMatched {
  578. err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef.String()))
  579. if err != nil {
  580. return err
  581. }
  582. err = writeDataPktLine(ctx, os.Stdout, []byte("option fall-through"))
  583. if err != nil {
  584. return err
  585. }
  586. continue
  587. }
  588. err = writeDataPktLine(ctx, os.Stdout, []byte("ok "+rs.OriginalRef))
  589. if err != nil {
  590. return err
  591. }
  592. err = writeDataPktLine(ctx, os.Stdout, []byte("option refname "+rs.Ref))
  593. if err != nil {
  594. return err
  595. }
  596. commitID, _ := git.NewIDFromString(rs.OldOID)
  597. if !commitID.IsZero() {
  598. err = writeDataPktLine(ctx, os.Stdout, []byte("option old-oid "+rs.OldOID))
  599. if err != nil {
  600. return err
  601. }
  602. }
  603. err = writeDataPktLine(ctx, os.Stdout, []byte("option new-oid "+rs.NewOID))
  604. if err != nil {
  605. return err
  606. }
  607. if rs.IsForcePush {
  608. err = writeDataPktLine(ctx, os.Stdout, []byte("option forced-update"))
  609. if err != nil {
  610. return err
  611. }
  612. }
  613. }
  614. err = writeFlushPktLine(ctx, os.Stdout)
  615. if err == nil {
  616. for _, res := range resp.Results {
  617. hookPrintResult(res.ShouldShowMessage, res.IsCreatePR, res.HeadBranch, res.URL)
  618. }
  619. }
  620. return err
  621. }
  622. // git PKT-Line api
  623. // pktLineType message type of pkt-line
  624. type pktLineType int64
  625. const (
  626. // UnKnow type
  627. pktLineTypeUnknow pktLineType = 0
  628. // flush-pkt "0000"
  629. pktLineTypeFlush pktLineType = iota
  630. // data line
  631. pktLineTypeData
  632. )
  633. // gitPktLine pkt-line api
  634. type gitPktLine struct {
  635. Type pktLineType
  636. Length uint64
  637. Data []byte
  638. }
  639. func readPktLine(ctx context.Context, in *bufio.Reader, requestType pktLineType) (*gitPktLine, error) {
  640. var (
  641. err error
  642. r *gitPktLine
  643. )
  644. // read prefix
  645. lengthBytes := make([]byte, 4)
  646. for i := range 4 {
  647. lengthBytes[i], err = in.ReadByte()
  648. if err != nil {
  649. return nil, fail(ctx, "Protocol: stdin error", "Pkt-Line: read stdin failed : %v", err)
  650. }
  651. }
  652. r = new(gitPktLine)
  653. r.Length, err = strconv.ParseUint(string(lengthBytes), 16, 32)
  654. if err != nil {
  655. return nil, fail(ctx, "Protocol: format parse error", "Pkt-Line format is wrong :%v", err)
  656. }
  657. if r.Length == 0 {
  658. if requestType == pktLineTypeData {
  659. return nil, fail(ctx, "Protocol: format data error", "Pkt-Line format is wrong")
  660. }
  661. r.Type = pktLineTypeFlush
  662. return r, nil
  663. }
  664. if r.Length <= 4 || r.Length > 65520 || requestType == pktLineTypeFlush {
  665. return nil, fail(ctx, "Protocol: format length error", "Pkt-Line format is wrong")
  666. }
  667. r.Data = make([]byte, r.Length-4)
  668. for i := range r.Data {
  669. r.Data[i], err = in.ReadByte()
  670. if err != nil {
  671. return nil, fail(ctx, "Protocol: data error", "Pkt-Line: read stdin failed : %v", err)
  672. }
  673. }
  674. r.Type = pktLineTypeData
  675. return r, nil
  676. }
  677. func writeFlushPktLine(ctx context.Context, out io.Writer) error {
  678. l, err := out.Write([]byte("0000"))
  679. if err != nil || l != 4 {
  680. return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
  681. }
  682. return nil
  683. }
  684. func writeDataPktLine(ctx context.Context, out io.Writer, data []byte) error {
  685. hexchar := []byte("0123456789abcdef")
  686. hex := func(n uint64) byte {
  687. return hexchar[(n)&15]
  688. }
  689. length := uint64(len(data) + 4)
  690. tmp := make([]byte, 4)
  691. tmp[0] = hex(length >> 12)
  692. tmp[1] = hex(length >> 8)
  693. tmp[2] = hex(length >> 4)
  694. tmp[3] = hex(length)
  695. lr, err := out.Write(tmp)
  696. if err != nil || lr != 4 {
  697. return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
  698. }
  699. lr, err = out.Write(data)
  700. if err != nil || int(length-4) != lr {
  701. return fail(ctx, "Protocol: write error", "Pkt-Line response failed: %v", err)
  702. }
  703. return nil
  704. }