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

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