repo_editor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. // Copyright 2016 The Gogs 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 db
  5. import (
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/pkg/errors"
  16. gouuid "github.com/satori/go.uuid"
  17. "github.com/unknwon/com"
  18. "github.com/gogs/git-module"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/cryptoutil"
  21. dberrors "gogs.io/gogs/internal/db/errors"
  22. "gogs.io/gogs/internal/gitutil"
  23. "gogs.io/gogs/internal/osutil"
  24. "gogs.io/gogs/internal/pathutil"
  25. "gogs.io/gogs/internal/process"
  26. "gogs.io/gogs/internal/tool"
  27. )
  28. const (
  29. ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID"
  30. ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME"
  31. ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL"
  32. ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME"
  33. ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5"
  34. ENV_REPO_ID = "GOGS_REPO_ID"
  35. ENV_REPO_NAME = "GOGS_REPO_NAME"
  36. ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH"
  37. )
  38. type ComposeHookEnvsOptions struct {
  39. AuthUser *User
  40. OwnerName string
  41. OwnerSalt string
  42. RepoID int64
  43. RepoName string
  44. RepoPath string
  45. }
  46. func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
  47. envs := []string{
  48. "SSH_ORIGINAL_COMMAND=1",
  49. ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
  50. ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
  51. ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
  52. ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
  53. ENV_REPO_OWNER_SALT_MD5 + "=" + cryptoutil.MD5(opts.OwnerSalt),
  54. ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
  55. ENV_REPO_NAME + "=" + opts.RepoName,
  56. ENV_REPO_CUSTOM_HOOKS_PATH + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
  57. }
  58. return envs
  59. }
  60. // ___________ .___.__ __ ___________.__.__
  61. // \_ _____/ __| _/|__|/ |_ \_ _____/|__| | ____
  62. // | __)_ / __ | | \ __\ | __) | | | _/ __ \
  63. // | \/ /_/ | | || | | \ | | |_\ ___/
  64. // /_______ /\____ | |__||__| \___ / |__|____/\___ >
  65. // \/ \/ \/ \/
  66. // discardLocalRepoBranchChanges discards local commits/changes of
  67. // given branch to make sure it is even to remote branch.
  68. func discardLocalRepoBranchChanges(localPath, branch string) error {
  69. if !com.IsExist(localPath) {
  70. return nil
  71. }
  72. // No need to check if nothing in the repository.
  73. if !git.RepoHasBranch(localPath, branch) {
  74. return nil
  75. }
  76. rev := "origin/" + branch
  77. if err := git.Reset(localPath, rev, git.ResetOptions{Hard: true}); err != nil {
  78. return fmt.Errorf("reset [revision: %s]: %v", rev, err)
  79. }
  80. return nil
  81. }
  82. func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  83. return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
  84. }
  85. // CheckoutNewBranch checks out to a new branch from the a branch name.
  86. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  87. if err := git.Checkout(repo.LocalCopyPath(), newBranch, git.CheckoutOptions{
  88. BaseBranch: oldBranch,
  89. Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
  90. }); err != nil {
  91. return fmt.Errorf("checkout [base: %s, new: %s]: %v", oldBranch, newBranch, err)
  92. }
  93. return nil
  94. }
  95. type UpdateRepoFileOptions struct {
  96. OldBranch string
  97. NewBranch string
  98. OldTreeName string
  99. NewTreeName string
  100. Message string
  101. Content string
  102. IsNewFile bool
  103. }
  104. // UpdateRepoFile adds or updates a file in repository.
  105. func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
  106. // 🚨 SECURITY: Prevent uploading files into the ".git" directory
  107. if isRepositoryGitPath(opts.NewTreeName) {
  108. return errors.Errorf("bad tree path %q", opts.NewTreeName)
  109. }
  110. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  111. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  112. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  113. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  114. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  115. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  116. }
  117. repoPath := repo.RepoPath()
  118. localPath := repo.LocalCopyPath()
  119. if opts.OldBranch != opts.NewBranch {
  120. // Directly return error if new branch already exists in the server
  121. if git.RepoHasBranch(repoPath, opts.NewBranch) {
  122. return dberrors.BranchAlreadyExists{Name: opts.NewBranch}
  123. }
  124. // Otherwise, delete branch from local copy in case out of sync
  125. if git.RepoHasBranch(localPath, opts.NewBranch) {
  126. if err = git.DeleteBranch(localPath, opts.NewBranch, git.DeleteBranchOptions{
  127. Force: true,
  128. }); err != nil {
  129. return fmt.Errorf("delete branch %q: %v", opts.NewBranch, err)
  130. }
  131. }
  132. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  133. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  134. }
  135. }
  136. oldFilePath := path.Join(localPath, opts.OldTreeName)
  137. filePath := path.Join(localPath, opts.NewTreeName)
  138. if err = os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil {
  139. return err
  140. }
  141. // If it's meant to be a new file, make sure it doesn't exist.
  142. if opts.IsNewFile {
  143. if com.IsExist(filePath) {
  144. return ErrRepoFileAlreadyExist{filePath}
  145. }
  146. }
  147. // Ignore move step if it's a new file under a directory.
  148. // Otherwise, move the file when name changed.
  149. if osutil.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
  150. if err = git.Move(localPath, opts.OldTreeName, opts.NewTreeName); err != nil {
  151. return fmt.Errorf("git mv %q %q: %v", opts.OldTreeName, opts.NewTreeName, err)
  152. }
  153. }
  154. if err = os.WriteFile(filePath, []byte(opts.Content), 0600); err != nil {
  155. return fmt.Errorf("write file: %v", err)
  156. }
  157. if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
  158. return fmt.Errorf("git add --all: %v", err)
  159. } else if err = git.CreateCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  160. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  161. }
  162. err = git.Push(localPath, "origin", opts.NewBranch,
  163. git.PushOptions{
  164. CommandOptions: git.CommandOptions{
  165. Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
  166. AuthUser: doer,
  167. OwnerName: repo.MustOwner().Name,
  168. OwnerSalt: repo.MustOwner().Salt,
  169. RepoID: repo.ID,
  170. RepoName: repo.Name,
  171. RepoPath: repo.RepoPath(),
  172. }),
  173. },
  174. },
  175. )
  176. if err != nil {
  177. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  178. }
  179. return nil
  180. }
  181. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  182. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
  183. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  184. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  185. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  186. return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
  187. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  188. return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
  189. }
  190. localPath := repo.LocalCopyPath()
  191. filePath := path.Join(localPath, treePath)
  192. if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
  193. return nil, err
  194. }
  195. if err = os.WriteFile(filePath, []byte(content), 0600); err != nil {
  196. return nil, fmt.Errorf("write file: %v", err)
  197. }
  198. cmd := exec.Command("git", "diff", treePath)
  199. cmd.Dir = localPath
  200. cmd.Stderr = os.Stderr
  201. stdout, err := cmd.StdoutPipe()
  202. if err != nil {
  203. return nil, fmt.Errorf("get stdout pipe: %v", err)
  204. }
  205. if err = cmd.Start(); err != nil {
  206. return nil, fmt.Errorf("start: %v", err)
  207. }
  208. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  209. defer process.Remove(pid)
  210. diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
  211. if err != nil {
  212. return nil, fmt.Errorf("parse diff: %v", err)
  213. }
  214. if err = cmd.Wait(); err != nil {
  215. return nil, fmt.Errorf("wait: %v", err)
  216. }
  217. return diff, nil
  218. }
  219. // ________ .__ __ ___________.__.__
  220. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  221. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  222. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  223. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  224. // \/ \/ \/ \/ \/ \/
  225. //
  226. type DeleteRepoFileOptions struct {
  227. LastCommitID string
  228. OldBranch string
  229. NewBranch string
  230. TreePath string
  231. Message string
  232. }
  233. func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  234. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  235. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  236. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  237. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  238. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  239. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  240. }
  241. if opts.OldBranch != opts.NewBranch {
  242. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  243. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  244. }
  245. }
  246. localPath := repo.LocalCopyPath()
  247. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  248. return fmt.Errorf("remove file %q: %v", opts.TreePath, err)
  249. }
  250. if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
  251. return fmt.Errorf("git add --all: %v", err)
  252. } else if err = git.CreateCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  253. return fmt.Errorf("commit changes to %q: %v", localPath, err)
  254. }
  255. err = git.Push(localPath, "origin", opts.NewBranch,
  256. git.PushOptions{
  257. CommandOptions: git.CommandOptions{
  258. Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
  259. AuthUser: doer,
  260. OwnerName: repo.MustOwner().Name,
  261. OwnerSalt: repo.MustOwner().Salt,
  262. RepoID: repo.ID,
  263. RepoName: repo.Name,
  264. RepoPath: repo.RepoPath(),
  265. }),
  266. },
  267. },
  268. )
  269. if err != nil {
  270. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  271. }
  272. return nil
  273. }
  274. // ____ ___ .__ .___ ___________.___.__
  275. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  276. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  277. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  278. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  279. // |__| \/ \/ \/ \/ \/
  280. //
  281. // Upload represent a uploaded file to a repo to be deleted when moved
  282. type Upload struct {
  283. ID int64
  284. UUID string `xorm:"uuid UNIQUE"`
  285. Name string
  286. }
  287. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  288. func UploadLocalPath(uuid string) string {
  289. return path.Join(conf.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  290. }
  291. // LocalPath returns where uploads are temporarily stored in local file system.
  292. func (upload *Upload) LocalPath() string {
  293. return UploadLocalPath(upload.UUID)
  294. }
  295. // NewUpload creates a new upload object.
  296. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  297. if tool.IsMaliciousPath(name) {
  298. return nil, fmt.Errorf("malicious path detected: %s", name)
  299. }
  300. upload := &Upload{
  301. UUID: gouuid.NewV4().String(),
  302. Name: name,
  303. }
  304. localPath := upload.LocalPath()
  305. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  306. return nil, fmt.Errorf("mkdir all: %v", err)
  307. }
  308. fw, err := os.Create(localPath)
  309. if err != nil {
  310. return nil, fmt.Errorf("create: %v", err)
  311. }
  312. defer func() { _ = fw.Close() }()
  313. if _, err = fw.Write(buf); err != nil {
  314. return nil, fmt.Errorf("write: %v", err)
  315. } else if _, err = io.Copy(fw, file); err != nil {
  316. return nil, fmt.Errorf("copy: %v", err)
  317. }
  318. if _, err := x.Insert(upload); err != nil {
  319. return nil, err
  320. }
  321. return upload, nil
  322. }
  323. func GetUploadByUUID(uuid string) (*Upload, error) {
  324. upload := &Upload{UUID: uuid}
  325. has, err := x.Get(upload)
  326. if err != nil {
  327. return nil, err
  328. } else if !has {
  329. return nil, ErrUploadNotExist{0, uuid}
  330. }
  331. return upload, nil
  332. }
  333. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  334. if len(uuids) == 0 {
  335. return []*Upload{}, nil
  336. }
  337. // Silently drop invalid uuids.
  338. uploads := make([]*Upload, 0, len(uuids))
  339. return uploads, x.In("uuid", uuids).Find(&uploads)
  340. }
  341. func DeleteUploads(uploads ...*Upload) (err error) {
  342. if len(uploads) == 0 {
  343. return nil
  344. }
  345. sess := x.NewSession()
  346. defer sess.Close()
  347. if err = sess.Begin(); err != nil {
  348. return err
  349. }
  350. ids := make([]int64, len(uploads))
  351. for i := 0; i < len(uploads); i++ {
  352. ids[i] = uploads[i].ID
  353. }
  354. if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
  355. return fmt.Errorf("delete uploads: %v", err)
  356. }
  357. for _, upload := range uploads {
  358. localPath := upload.LocalPath()
  359. if !osutil.IsFile(localPath) {
  360. continue
  361. }
  362. if err := os.Remove(localPath); err != nil {
  363. return fmt.Errorf("remove upload: %v", err)
  364. }
  365. }
  366. return sess.Commit()
  367. }
  368. func DeleteUpload(u *Upload) error {
  369. return DeleteUploads(u)
  370. }
  371. func DeleteUploadByUUID(uuid string) error {
  372. upload, err := GetUploadByUUID(uuid)
  373. if err != nil {
  374. if IsErrUploadNotExist(err) {
  375. return nil
  376. }
  377. return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err)
  378. }
  379. if err := DeleteUpload(upload); err != nil {
  380. return fmt.Errorf("delete upload: %v", err)
  381. }
  382. return nil
  383. }
  384. type UploadRepoFileOptions struct {
  385. LastCommitID string
  386. OldBranch string
  387. NewBranch string
  388. TreePath string
  389. Message string
  390. Files []string // In UUID format
  391. }
  392. // isRepositoryGitPath returns true if given path is or resides inside ".git"
  393. // path of the repository.
  394. func isRepositoryGitPath(path string) bool {
  395. return strings.HasSuffix(path, ".git") ||
  396. strings.Contains(path, ".git/") ||
  397. strings.Contains(path, `.git\`) ||
  398. // Windows treats ".git." the same as ".git"
  399. strings.HasSuffix(path, ".git.") ||
  400. strings.Contains(path, ".git./") ||
  401. strings.Contains(path, `.git.\`)
  402. }
  403. func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
  404. if len(opts.Files) == 0 {
  405. return nil
  406. }
  407. // 🚨 SECURITY: Prevent uploading files into the ".git" directory
  408. if isRepositoryGitPath(opts.TreePath) {
  409. return errors.Errorf("bad tree path %q", opts.TreePath)
  410. }
  411. uploads, err := GetUploadsByUUIDs(opts.Files)
  412. if err != nil {
  413. return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
  414. }
  415. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  416. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  417. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  418. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  419. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  420. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  421. }
  422. if opts.OldBranch != opts.NewBranch {
  423. if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  424. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  425. }
  426. }
  427. localPath := repo.LocalCopyPath()
  428. dirPath := path.Join(localPath, opts.TreePath)
  429. if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
  430. return err
  431. }
  432. // Copy uploaded files into repository
  433. for _, upload := range uploads {
  434. tmpPath := upload.LocalPath()
  435. if !osutil.IsFile(tmpPath) {
  436. continue
  437. }
  438. upload.Name = pathutil.Clean(upload.Name)
  439. // 🚨 SECURITY: Prevent uploading files into the ".git" directory
  440. if isRepositoryGitPath(upload.Name) {
  441. continue
  442. }
  443. targetPath := path.Join(dirPath, upload.Name)
  444. if err = com.Copy(tmpPath, targetPath); err != nil {
  445. return fmt.Errorf("copy: %v", err)
  446. }
  447. }
  448. if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
  449. return fmt.Errorf("git add --all: %v", err)
  450. } else if err = git.CreateCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  451. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  452. }
  453. err = git.Push(localPath, "origin", opts.NewBranch,
  454. git.PushOptions{
  455. CommandOptions: git.CommandOptions{
  456. Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
  457. AuthUser: doer,
  458. OwnerName: repo.MustOwner().Name,
  459. OwnerSalt: repo.MustOwner().Salt,
  460. RepoID: repo.ID,
  461. RepoName: repo.Name,
  462. RepoPath: repo.RepoPath(),
  463. }),
  464. },
  465. },
  466. )
  467. if err != nil {
  468. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  469. }
  470. return DeleteUploads(uploads...)
  471. }