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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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. hookOptions := private.HookOptions{
  170. UserID: userID,
  171. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  172. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  173. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  174. GitPushOptions: pushOptions(),
  175. PullRequestID: prID,
  176. DeployKeyID: deployKeyID,
  177. }
  178. scanner := bufio.NewScanner(os.Stdin)
  179. oldCommitIDs := make([]string, hookBatchSize)
  180. newCommitIDs := make([]string, hookBatchSize)
  181. refFullNames := make([]string, hookBatchSize)
  182. count := 0
  183. total := 0
  184. lastline := 0
  185. var out io.Writer
  186. out = &nilWriter{}
  187. if setting.Git.VerbosePush {
  188. if setting.Git.VerbosePushDelay > 0 {
  189. dWriter := newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  190. defer dWriter.Close()
  191. out = dWriter
  192. } else {
  193. out = os.Stdout
  194. }
  195. }
  196. supportProcReceive := false
  197. if git.CheckGitVersionAtLeast("2.29") == nil {
  198. supportProcReceive = true
  199. }
  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 := string(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 || strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
  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. statusCode, msg := private.HookPreReceive(ctx, username, reponame, hookOptions)
  229. switch statusCode {
  230. case http.StatusOK:
  231. // no-op
  232. case http.StatusInternalServerError:
  233. return fail("Internal Server Error", msg)
  234. default:
  235. return fail(msg, "")
  236. }
  237. count = 0
  238. lastline = 0
  239. }
  240. } else {
  241. fmt.Fprintf(out, ".")
  242. }
  243. if lastline >= hookBatchSize {
  244. fmt.Fprintf(out, "\n")
  245. lastline = 0
  246. }
  247. }
  248. if count > 0 {
  249. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  250. hookOptions.NewCommitIDs = newCommitIDs[:count]
  251. hookOptions.RefFullNames = refFullNames[:count]
  252. fmt.Fprintf(out, " Checking %d references\n", count)
  253. statusCode, msg := private.HookPreReceive(ctx, username, reponame, hookOptions)
  254. switch statusCode {
  255. case http.StatusInternalServerError:
  256. return fail("Internal Server Error", msg)
  257. case http.StatusForbidden:
  258. return fail(msg, "")
  259. }
  260. } else if lastline > 0 {
  261. fmt.Fprintf(out, "\n")
  262. }
  263. fmt.Fprintf(out, "Checked %d references in total\n", total)
  264. return nil
  265. }
  266. func runHookUpdate(c *cli.Context) error {
  267. // Update is empty and is kept only for backwards compatibility
  268. return nil
  269. }
  270. func runHookPostReceive(c *cli.Context) error {
  271. ctx, cancel := installSignals()
  272. defer cancel()
  273. setup("hooks/post-receive.log", c.Bool("debug"))
  274. // First of all run update-server-info no matter what
  275. if _, _, err := git.NewCommand(ctx, "update-server-info").RunStdString(nil); err != nil {
  276. return fmt.Errorf("Failed to call 'git update-server-info': %w", err)
  277. }
  278. // Now if we're an internal don't do anything else
  279. if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {
  280. return nil
  281. }
  282. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  283. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  284. return fail(`Rejecting changes as Gitea environment not set.
  285. If you are pushing over SSH you must push with a key managed by
  286. Gitea or set your environment appropriately.`, "")
  287. }
  288. return nil
  289. }
  290. var out io.Writer
  291. var dWriter *delayWriter
  292. out = &nilWriter{}
  293. if setting.Git.VerbosePush {
  294. if setting.Git.VerbosePushDelay > 0 {
  295. dWriter = newDelayWriter(os.Stdout, setting.Git.VerbosePushDelay)
  296. defer dWriter.Close()
  297. out = dWriter
  298. } else {
  299. out = os.Stdout
  300. }
  301. }
  302. // the environment is set by serv command
  303. repoUser := os.Getenv(repo_module.EnvRepoUsername)
  304. isWiki, _ := strconv.ParseBool(os.Getenv(repo_module.EnvRepoIsWiki))
  305. repoName := os.Getenv(repo_module.EnvRepoName)
  306. pusherID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  307. pusherName := os.Getenv(repo_module.EnvPusherName)
  308. hookOptions := private.HookOptions{
  309. UserName: pusherName,
  310. UserID: pusherID,
  311. GitAlternativeObjectDirectories: os.Getenv(private.GitAlternativeObjectDirectories),
  312. GitObjectDirectory: os.Getenv(private.GitObjectDirectory),
  313. GitQuarantinePath: os.Getenv(private.GitQuarantinePath),
  314. GitPushOptions: pushOptions(),
  315. }
  316. oldCommitIDs := make([]string, hookBatchSize)
  317. newCommitIDs := make([]string, hookBatchSize)
  318. refFullNames := make([]string, hookBatchSize)
  319. count := 0
  320. total := 0
  321. wasEmpty := false
  322. masterPushed := false
  323. results := make([]private.HookPostReceiveBranchResult, 0)
  324. scanner := bufio.NewScanner(os.Stdin)
  325. for scanner.Scan() {
  326. // TODO: support news feeds for wiki
  327. if isWiki {
  328. continue
  329. }
  330. fields := bytes.Fields(scanner.Bytes())
  331. if len(fields) != 3 {
  332. continue
  333. }
  334. fmt.Fprintf(out, ".")
  335. oldCommitIDs[count] = string(fields[0])
  336. newCommitIDs[count] = string(fields[1])
  337. refFullNames[count] = string(fields[2])
  338. if refFullNames[count] == git.BranchPrefix+"master" && newCommitIDs[count] != git.EmptySHA && count == total {
  339. masterPushed = true
  340. }
  341. count++
  342. total++
  343. if count >= hookBatchSize {
  344. fmt.Fprintf(out, " Processing %d references\n", count)
  345. hookOptions.OldCommitIDs = oldCommitIDs
  346. hookOptions.NewCommitIDs = newCommitIDs
  347. hookOptions.RefFullNames = refFullNames
  348. resp, err := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
  349. if resp == nil {
  350. _ = dWriter.Close()
  351. hookPrintResults(results)
  352. return fail("Internal Server Error", err)
  353. }
  354. wasEmpty = wasEmpty || resp.RepoWasEmpty
  355. results = append(results, resp.Results...)
  356. count = 0
  357. }
  358. }
  359. if count == 0 {
  360. if wasEmpty && masterPushed {
  361. // We need to tell the repo to reset the default branch to master
  362. err := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
  363. if err != nil {
  364. return fail("Internal Server Error", "SetDefaultBranch failed with Error: %v", err)
  365. }
  366. }
  367. fmt.Fprintf(out, "Processed %d references in total\n", total)
  368. _ = dWriter.Close()
  369. hookPrintResults(results)
  370. return nil
  371. }
  372. hookOptions.OldCommitIDs = oldCommitIDs[:count]
  373. hookOptions.NewCommitIDs = newCommitIDs[:count]
  374. hookOptions.RefFullNames = refFullNames[:count]
  375. fmt.Fprintf(out, " Processing %d references\n", count)
  376. resp, err := private.HookPostReceive(ctx, repoUser, repoName, hookOptions)
  377. if resp == nil {
  378. _ = dWriter.Close()
  379. hookPrintResults(results)
  380. return fail("Internal Server Error", err)
  381. }
  382. wasEmpty = wasEmpty || resp.RepoWasEmpty
  383. results = append(results, resp.Results...)
  384. fmt.Fprintf(out, "Processed %d references in total\n", total)
  385. if wasEmpty && masterPushed {
  386. // We need to tell the repo to reset the default branch to master
  387. err := private.SetDefaultBranch(ctx, repoUser, repoName, "master")
  388. if err != nil {
  389. return fail("Internal Server Error", "SetDefaultBranch failed with Error: %v", err)
  390. }
  391. }
  392. _ = dWriter.Close()
  393. hookPrintResults(results)
  394. return nil
  395. }
  396. func hookPrintResults(results []private.HookPostReceiveBranchResult) {
  397. for _, res := range results {
  398. if !res.Message {
  399. continue
  400. }
  401. fmt.Fprintln(os.Stderr, "")
  402. if res.Create {
  403. fmt.Fprintf(os.Stderr, "Create a new pull request for '%s':\n", res.Branch)
  404. fmt.Fprintf(os.Stderr, " %s\n", res.URL)
  405. } else {
  406. fmt.Fprint(os.Stderr, "Visit the existing pull request:\n")
  407. fmt.Fprintf(os.Stderr, " %s\n", res.URL)
  408. }
  409. fmt.Fprintln(os.Stderr, "")
  410. os.Stderr.Sync()
  411. }
  412. }
  413. func pushOptions() map[string]string {
  414. opts := make(map[string]string)
  415. if pushCount, err := strconv.Atoi(os.Getenv(private.GitPushOptionCount)); err == nil {
  416. for idx := 0; idx < pushCount; idx++ {
  417. opt := os.Getenv(fmt.Sprintf("GIT_PUSH_OPTION_%d", idx))
  418. kv := strings.SplitN(opt, "=", 2)
  419. if len(kv) == 2 {
  420. opts[kv[0]] = kv[1]
  421. }
  422. }
  423. }
  424. return opts
  425. }
  426. func runHookProcReceive(c *cli.Context) error {
  427. setup("hooks/proc-receive.log", c.Bool("debug"))
  428. if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
  429. if setting.OnlyAllowPushIfGiteaEnvironmentSet {
  430. return fail(`Rejecting changes as Gitea environment not set.
  431. If you are pushing over SSH you must push with a key managed by
  432. Gitea or set your environment appropriately.`, "")
  433. }
  434. return nil
  435. }
  436. ctx, cancel := installSignals()
  437. defer cancel()
  438. if git.CheckGitVersionAtLeast("2.29") != nil {
  439. return fail("Internal Server Error", "git not support proc-receive.")
  440. }
  441. reader := bufio.NewReader(os.Stdin)
  442. repoUser := os.Getenv(repo_module.EnvRepoUsername)
  443. repoName := os.Getenv(repo_module.EnvRepoName)
  444. pusherID, _ := strconv.ParseInt(os.Getenv(repo_module.EnvPusherID), 10, 64)
  445. pusherName := os.Getenv(repo_module.EnvPusherName)
  446. // 1. Version and features negotiation.
  447. // S: PKT-LINE(version=1\0push-options atomic...) / PKT-LINE(version=1\n)
  448. // S: flush-pkt
  449. // H: PKT-LINE(version=1\0push-options...)
  450. // H: flush-pkt
  451. rs, err := readPktLine(reader, pktLineTypeData)
  452. if err != nil {
  453. return err
  454. }
  455. const VersionHead string = "version=1"
  456. var (
  457. hasPushOptions bool
  458. response = []byte(VersionHead)
  459. requestOptions []string
  460. )
  461. index := bytes.IndexByte(rs.Data, byte(0))
  462. if index >= len(rs.Data) {
  463. return fail("Internal Server Error", "pkt-line: format error "+fmt.Sprint(rs.Data))
  464. }
  465. if index < 0 {
  466. if len(rs.Data) == 10 && rs.Data[9] == '\n' {
  467. index = 9
  468. } else {
  469. return fail("Internal Server Error", "pkt-line: format error "+fmt.Sprint(rs.Data))
  470. }
  471. }
  472. if string(rs.Data[0:index]) != VersionHead {
  473. return fail("Internal Server Error", "Received unsupported version: %s", string(rs.Data[0:index]))
  474. }
  475. requestOptions = strings.Split(string(rs.Data[index+1:]), " ")
  476. for _, option := range requestOptions {
  477. if strings.HasPrefix(option, "push-options") {
  478. response = append(response, byte(0))
  479. response = append(response, []byte("push-options")...)
  480. hasPushOptions = true
  481. }
  482. }
  483. response = append(response, '\n')
  484. _, err = readPktLine(reader, pktLineTypeFlush)
  485. if err != nil {
  486. return err
  487. }
  488. err = writeDataPktLine(os.Stdout, response)
  489. if err != nil {
  490. return err
  491. }
  492. err = writeFlushPktLine(os.Stdout)
  493. if err != nil {
  494. return err
  495. }
  496. // 2. receive commands from server.
  497. // S: PKT-LINE(<old-oid> <new-oid> <ref>)
  498. // S: ... ...
  499. // S: flush-pkt
  500. // # [receive push-options]
  501. // S: PKT-LINE(push-option)
  502. // S: ... ...
  503. // S: flush-pkt
  504. hookOptions := private.HookOptions{
  505. UserName: pusherName,
  506. UserID: pusherID,
  507. }
  508. hookOptions.OldCommitIDs = make([]string, 0, hookBatchSize)
  509. hookOptions.NewCommitIDs = make([]string, 0, hookBatchSize)
  510. hookOptions.RefFullNames = make([]string, 0, hookBatchSize)
  511. for {
  512. // note: pktLineTypeUnknow means pktLineTypeFlush and pktLineTypeData all allowed
  513. rs, err = readPktLine(reader, pktLineTypeUnknow)
  514. if err != nil {
  515. return err
  516. }
  517. if rs.Type == pktLineTypeFlush {
  518. break
  519. }
  520. t := strings.SplitN(string(rs.Data), " ", 3)
  521. if len(t) != 3 {
  522. continue
  523. }
  524. hookOptions.OldCommitIDs = append(hookOptions.OldCommitIDs, t[0])
  525. hookOptions.NewCommitIDs = append(hookOptions.NewCommitIDs, t[1])
  526. hookOptions.RefFullNames = append(hookOptions.RefFullNames, t[2])
  527. }
  528. hookOptions.GitPushOptions = make(map[string]string)
  529. if hasPushOptions {
  530. for {
  531. rs, err = readPktLine(reader, pktLineTypeUnknow)
  532. if err != nil {
  533. return err
  534. }
  535. if rs.Type == pktLineTypeFlush {
  536. break
  537. }
  538. kv := strings.SplitN(string(rs.Data), "=", 2)
  539. if len(kv) == 2 {
  540. hookOptions.GitPushOptions[kv[0]] = kv[1]
  541. }
  542. }
  543. }
  544. // 3. run hook
  545. resp, err := private.HookProcReceive(ctx, repoUser, repoName, hookOptions)
  546. if err != nil {
  547. return fail("Internal Server Error", "run proc-receive hook failed :%v", err)
  548. }
  549. // 4. response result to service
  550. // # a. OK, but has an alternate reference. The alternate reference name
  551. // # and other status can be given in option directives.
  552. // H: PKT-LINE(ok <ref>)
  553. // H: PKT-LINE(option refname <refname>)
  554. // H: PKT-LINE(option old-oid <old-oid>)
  555. // H: PKT-LINE(option new-oid <new-oid>)
  556. // H: PKT-LINE(option forced-update)
  557. // H: ... ...
  558. // H: flush-pkt
  559. // # b. NO, I reject it.
  560. // H: PKT-LINE(ng <ref> <reason>)
  561. // # c. Fall through, let 'receive-pack' to execute it.
  562. // H: PKT-LINE(ok <ref>)
  563. // H: PKT-LINE(option fall-through)
  564. for _, rs := range resp.Results {
  565. if len(rs.Err) > 0 {
  566. err = writeDataPktLine(os.Stdout, []byte("ng "+rs.OriginalRef+" "+rs.Err))
  567. if err != nil {
  568. return err
  569. }
  570. continue
  571. }
  572. if rs.IsNotMatched {
  573. err = writeDataPktLine(os.Stdout, []byte("ok "+rs.OriginalRef))
  574. if err != nil {
  575. return err
  576. }
  577. err = writeDataPktLine(os.Stdout, []byte("option fall-through"))
  578. if err != nil {
  579. return err
  580. }
  581. continue
  582. }
  583. err = writeDataPktLine(os.Stdout, []byte("ok "+rs.OriginalRef))
  584. if err != nil {
  585. return err
  586. }
  587. err = writeDataPktLine(os.Stdout, []byte("option refname "+rs.Ref))
  588. if err != nil {
  589. return err
  590. }
  591. if rs.OldOID != git.EmptySHA {
  592. err = writeDataPktLine(os.Stdout, []byte("option old-oid "+rs.OldOID))
  593. if err != nil {
  594. return err
  595. }
  596. }
  597. err = writeDataPktLine(os.Stdout, []byte("option new-oid "+rs.NewOID))
  598. if err != nil {
  599. return err
  600. }
  601. if rs.IsForcePush {
  602. err = writeDataPktLine(os.Stdout, []byte("option forced-update"))
  603. if err != nil {
  604. return err
  605. }
  606. }
  607. }
  608. err = writeFlushPktLine(os.Stdout)
  609. return err
  610. }
  611. // git PKT-Line api
  612. // pktLineType message type of pkt-line
  613. type pktLineType int64
  614. const (
  615. // UnKnow type
  616. pktLineTypeUnknow pktLineType = 0
  617. // flush-pkt "0000"
  618. pktLineTypeFlush pktLineType = iota
  619. // data line
  620. pktLineTypeData
  621. )
  622. // gitPktLine pkt-line api
  623. type gitPktLine struct {
  624. Type pktLineType
  625. Length uint64
  626. Data []byte
  627. }
  628. func readPktLine(in *bufio.Reader, requestType pktLineType) (*gitPktLine, error) {
  629. var (
  630. err error
  631. r *gitPktLine
  632. )
  633. // read prefix
  634. lengthBytes := make([]byte, 4)
  635. for i := 0; i < 4; i++ {
  636. lengthBytes[i], err = in.ReadByte()
  637. if err != nil {
  638. return nil, fail("Internal Server Error", "Pkt-Line: read stdin failed : %v", err)
  639. }
  640. }
  641. r = new(gitPktLine)
  642. r.Length, err = strconv.ParseUint(string(lengthBytes), 16, 32)
  643. if err != nil {
  644. return nil, fail("Internal Server Error", "Pkt-Line format is wrong :%v", err)
  645. }
  646. if r.Length == 0 {
  647. if requestType == pktLineTypeData {
  648. return nil, fail("Internal Server Error", "Pkt-Line format is wrong")
  649. }
  650. r.Type = pktLineTypeFlush
  651. return r, nil
  652. }
  653. if r.Length <= 4 || r.Length > 65520 || requestType == pktLineTypeFlush {
  654. return nil, fail("Internal Server Error", "Pkt-Line format is wrong")
  655. }
  656. r.Data = make([]byte, r.Length-4)
  657. for i := range r.Data {
  658. r.Data[i], err = in.ReadByte()
  659. if err != nil {
  660. return nil, fail("Internal Server Error", "Pkt-Line: read stdin failed : %v", err)
  661. }
  662. }
  663. r.Type = pktLineTypeData
  664. return r, nil
  665. }
  666. func writeFlushPktLine(out io.Writer) error {
  667. l, err := out.Write([]byte("0000"))
  668. if err != nil {
  669. return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
  670. }
  671. if l != 4 {
  672. return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
  673. }
  674. return nil
  675. }
  676. func writeDataPktLine(out io.Writer, data []byte) error {
  677. hexchar := []byte("0123456789abcdef")
  678. hex := func(n uint64) byte {
  679. return hexchar[(n)&15]
  680. }
  681. length := uint64(len(data) + 4)
  682. tmp := make([]byte, 4)
  683. tmp[0] = hex(length >> 12)
  684. tmp[1] = hex(length >> 8)
  685. tmp[2] = hex(length >> 4)
  686. tmp[3] = hex(length)
  687. lr, err := out.Write(tmp)
  688. if err != nil {
  689. return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
  690. }
  691. if lr != 4 {
  692. return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
  693. }
  694. lr, err = out.Write(data)
  695. if err != nil {
  696. return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
  697. }
  698. if int(length-4) != lr {
  699. return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
  700. }
  701. return nil
  702. }