repo_editor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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.RepoReset(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.RepoCheckout(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.RepoDeleteBranch(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.RepoMove(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.RepoAdd(localPath, git.AddOptions{All: true}); err != nil {
  160. return fmt.Errorf("git add --all: %v", err)
  161. } else if err = git.RepoCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  162. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  163. }
  164. envs := ComposeHookEnvs(ComposeHookEnvsOptions{
  165. AuthUser: doer,
  166. OwnerName: repo.MustOwner().Name,
  167. OwnerSalt: repo.MustOwner().Salt,
  168. RepoID: repo.ID,
  169. RepoName: repo.Name,
  170. RepoPath: repo.RepoPath(),
  171. })
  172. if err = git.RepoPush(localPath, "origin", opts.NewBranch, git.PushOptions{Envs: envs}); err != nil {
  173. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  174. }
  175. return nil
  176. }
  177. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  178. func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
  179. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  180. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  181. if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
  182. return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
  183. } else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
  184. return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
  185. }
  186. localPath := repo.LocalCopyPath()
  187. filePath := path.Join(localPath, treePath)
  188. if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
  189. return nil, err
  190. }
  191. if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
  192. return nil, fmt.Errorf("write file: %v", err)
  193. }
  194. cmd := exec.Command("git", "diff", treePath)
  195. cmd.Dir = localPath
  196. cmd.Stderr = os.Stderr
  197. stdout, err := cmd.StdoutPipe()
  198. if err != nil {
  199. return nil, fmt.Errorf("get stdout pipe: %v", err)
  200. }
  201. if err = cmd.Start(); err != nil {
  202. return nil, fmt.Errorf("start: %v", err)
  203. }
  204. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
  205. defer process.Remove(pid)
  206. diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
  207. if err != nil {
  208. return nil, fmt.Errorf("parse diff: %v", err)
  209. }
  210. if err = cmd.Wait(); err != nil {
  211. return nil, fmt.Errorf("wait: %v", err)
  212. }
  213. return diff, nil
  214. }
  215. // ________ .__ __ ___________.__.__
  216. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  217. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  218. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  219. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  220. // \/ \/ \/ \/ \/ \/
  221. //
  222. type DeleteRepoFileOptions struct {
  223. LastCommitID string
  224. OldBranch string
  225. NewBranch string
  226. TreePath string
  227. Message string
  228. }
  229. func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  230. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  231. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  232. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  233. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  234. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  235. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  236. }
  237. if opts.OldBranch != opts.NewBranch {
  238. if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  239. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  240. }
  241. }
  242. localPath := repo.LocalCopyPath()
  243. if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
  244. return fmt.Errorf("remove file %q: %v", opts.TreePath, err)
  245. }
  246. if err = git.RepoAdd(localPath, git.AddOptions{All: true}); err != nil {
  247. return fmt.Errorf("git add --all: %v", err)
  248. } else if err = git.RepoCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  249. return fmt.Errorf("commit changes to %q: %v", localPath, err)
  250. }
  251. envs := ComposeHookEnvs(ComposeHookEnvsOptions{
  252. AuthUser: doer,
  253. OwnerName: repo.MustOwner().Name,
  254. OwnerSalt: repo.MustOwner().Salt,
  255. RepoID: repo.ID,
  256. RepoName: repo.Name,
  257. RepoPath: repo.RepoPath(),
  258. })
  259. if err = git.RepoPush(localPath, "origin", opts.NewBranch, git.PushOptions{Envs: envs}); err != nil {
  260. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  261. }
  262. return nil
  263. }
  264. // ____ ___ .__ .___ ___________.___.__
  265. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  266. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  267. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  268. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  269. // |__| \/ \/ \/ \/ \/
  270. //
  271. // Upload represent a uploaded file to a repo to be deleted when moved
  272. type Upload struct {
  273. ID int64
  274. UUID string `xorm:"uuid UNIQUE"`
  275. Name string
  276. }
  277. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  278. func UploadLocalPath(uuid string) string {
  279. return path.Join(conf.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  280. }
  281. // LocalPath returns where uploads are temporarily stored in local file system.
  282. func (upload *Upload) LocalPath() string {
  283. return UploadLocalPath(upload.UUID)
  284. }
  285. // NewUpload creates a new upload object.
  286. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  287. if tool.IsMaliciousPath(name) {
  288. return nil, fmt.Errorf("malicious path detected: %s", name)
  289. }
  290. upload := &Upload{
  291. UUID: gouuid.NewV4().String(),
  292. Name: name,
  293. }
  294. localPath := upload.LocalPath()
  295. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  296. return nil, fmt.Errorf("mkdir all: %v", err)
  297. }
  298. fw, err := os.Create(localPath)
  299. if err != nil {
  300. return nil, fmt.Errorf("create: %v", err)
  301. }
  302. defer fw.Close()
  303. if _, err = fw.Write(buf); err != nil {
  304. return nil, fmt.Errorf("write: %v", err)
  305. } else if _, err = io.Copy(fw, file); err != nil {
  306. return nil, fmt.Errorf("copy: %v", err)
  307. }
  308. if _, err := x.Insert(upload); err != nil {
  309. return nil, err
  310. }
  311. return upload, nil
  312. }
  313. func GetUploadByUUID(uuid string) (*Upload, error) {
  314. upload := &Upload{UUID: uuid}
  315. has, err := x.Get(upload)
  316. if err != nil {
  317. return nil, err
  318. } else if !has {
  319. return nil, ErrUploadNotExist{0, uuid}
  320. }
  321. return upload, nil
  322. }
  323. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  324. if len(uuids) == 0 {
  325. return []*Upload{}, nil
  326. }
  327. // Silently drop invalid uuids.
  328. uploads := make([]*Upload, 0, len(uuids))
  329. return uploads, x.In("uuid", uuids).Find(&uploads)
  330. }
  331. func DeleteUploads(uploads ...*Upload) (err error) {
  332. if len(uploads) == 0 {
  333. return nil
  334. }
  335. sess := x.NewSession()
  336. defer sess.Close()
  337. if err = sess.Begin(); err != nil {
  338. return err
  339. }
  340. ids := make([]int64, len(uploads))
  341. for i := 0; i < len(uploads); i++ {
  342. ids[i] = uploads[i].ID
  343. }
  344. if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
  345. return fmt.Errorf("delete uploads: %v", err)
  346. }
  347. for _, upload := range uploads {
  348. localPath := upload.LocalPath()
  349. if !osutil.IsFile(localPath) {
  350. continue
  351. }
  352. if err := os.Remove(localPath); err != nil {
  353. return fmt.Errorf("remove upload: %v", err)
  354. }
  355. }
  356. return sess.Commit()
  357. }
  358. func DeleteUpload(u *Upload) error {
  359. return DeleteUploads(u)
  360. }
  361. func DeleteUploadByUUID(uuid string) error {
  362. upload, err := GetUploadByUUID(uuid)
  363. if err != nil {
  364. if IsErrUploadNotExist(err) {
  365. return nil
  366. }
  367. return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err)
  368. }
  369. if err := DeleteUpload(upload); err != nil {
  370. return fmt.Errorf("delete upload: %v", err)
  371. }
  372. return nil
  373. }
  374. type UploadRepoFileOptions struct {
  375. LastCommitID string
  376. OldBranch string
  377. NewBranch string
  378. TreePath string
  379. Message string
  380. Files []string // In UUID format
  381. }
  382. // isRepositoryGitPath returns true if given path is or resides inside ".git"
  383. // path of the repository.
  384. //
  385. // TODO(unknwon): Move to repoutil during refactoring for this file.
  386. func isRepositoryGitPath(path string) bool {
  387. path = strings.ToLower(path)
  388. return strings.HasSuffix(path, ".git") ||
  389. strings.Contains(path, ".git/") ||
  390. strings.Contains(path, `.git\`) ||
  391. // Windows treats ".git." the same as ".git"
  392. strings.HasSuffix(path, ".git.") ||
  393. strings.Contains(path, ".git./") ||
  394. strings.Contains(path, `.git.\`)
  395. }
  396. func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
  397. if len(opts.Files) == 0 {
  398. return nil
  399. }
  400. // 🚨 SECURITY: Prevent uploading files into the ".git" directory
  401. if isRepositoryGitPath(opts.TreePath) {
  402. return errors.Errorf("bad tree path %q", opts.TreePath)
  403. }
  404. uploads, err := GetUploadsByUUIDs(opts.Files)
  405. if err != nil {
  406. return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
  407. }
  408. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  409. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  410. if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  411. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  412. } else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  413. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  414. }
  415. if opts.OldBranch != opts.NewBranch {
  416. if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  417. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  418. }
  419. }
  420. localPath := repo.LocalCopyPath()
  421. dirPath := path.Join(localPath, opts.TreePath)
  422. if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
  423. return err
  424. }
  425. // Copy uploaded files into repository
  426. for _, upload := range uploads {
  427. tmpPath := upload.LocalPath()
  428. if !osutil.IsFile(tmpPath) {
  429. continue
  430. }
  431. upload.Name = pathutil.Clean(upload.Name)
  432. // 🚨 SECURITY: Prevent uploading files into the ".git" directory
  433. if isRepositoryGitPath(upload.Name) {
  434. continue
  435. }
  436. targetPath := path.Join(dirPath, upload.Name)
  437. if err = com.Copy(tmpPath, targetPath); err != nil {
  438. return fmt.Errorf("copy: %v", err)
  439. }
  440. }
  441. if err = git.RepoAdd(localPath, git.AddOptions{All: true}); err != nil {
  442. return fmt.Errorf("git add --all: %v", err)
  443. } else if err = git.RepoCommit(localPath, doer.NewGitSig(), opts.Message); err != nil {
  444. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  445. }
  446. envs := ComposeHookEnvs(ComposeHookEnvsOptions{
  447. AuthUser: doer,
  448. OwnerName: repo.MustOwner().Name,
  449. OwnerSalt: repo.MustOwner().Salt,
  450. RepoID: repo.ID,
  451. RepoName: repo.Name,
  452. RepoPath: repo.RepoPath(),
  453. })
  454. if err = git.RepoPush(localPath, "origin", opts.NewBranch, git.PushOptions{Envs: envs}); err != nil {
  455. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  456. }
  457. return DeleteUploads(uploads...)
  458. }