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.

hook.go 21KB

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