repo_editor.go 17 KB

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