editor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 repo
  5. import (
  6. "fmt"
  7. "net/http"
  8. "path"
  9. "strings"
  10. log "unknwon.dev/clog/v2"
  11. "gogs.io/gogs/internal/conf"
  12. "gogs.io/gogs/internal/context"
  13. "gogs.io/gogs/internal/database"
  14. "gogs.io/gogs/internal/database/errors"
  15. "gogs.io/gogs/internal/form"
  16. "gogs.io/gogs/internal/gitutil"
  17. "gogs.io/gogs/internal/pathutil"
  18. "gogs.io/gogs/internal/template"
  19. "gogs.io/gogs/internal/tool"
  20. )
  21. const (
  22. tmplEditorEdit = "repo/editor/edit"
  23. tmplEditorDiffPreview = "repo/editor/diff_preview"
  24. tmplEditorDelete = "repo/editor/delete"
  25. tmplEditorUpload = "repo/editor/upload"
  26. )
  27. // getParentTreeFields returns list of parent tree names and corresponding tree paths
  28. // based on given tree path.
  29. func getParentTreeFields(treePath string) (treeNames, treePaths []string) {
  30. if treePath == "" {
  31. return treeNames, treePaths
  32. }
  33. treeNames = strings.Split(treePath, "/")
  34. treePaths = make([]string, len(treeNames))
  35. for i := range treeNames {
  36. treePaths[i] = strings.Join(treeNames[:i+1], "/")
  37. }
  38. return treeNames, treePaths
  39. }
  40. func editFile(c *context.Context, isNewFile bool) {
  41. c.PageIs("Edit")
  42. c.RequireHighlightJS()
  43. c.RequireSimpleMDE()
  44. c.Data["IsNewFile"] = isNewFile
  45. treeNames, treePaths := getParentTreeFields(c.Repo.TreePath)
  46. if !isNewFile {
  47. entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath)
  48. if err != nil {
  49. c.NotFoundOrError(gitutil.NewError(err), "get tree entry")
  50. return
  51. }
  52. // No way to edit a directory online.
  53. if entry.IsTree() {
  54. c.NotFound()
  55. return
  56. }
  57. blob := entry.Blob()
  58. p, err := blob.Bytes()
  59. if err != nil {
  60. c.Error(err, "get blob data")
  61. return
  62. }
  63. c.Data["FileSize"] = blob.Size()
  64. c.Data["FileName"] = blob.Name()
  65. // Only text file are editable online.
  66. if !tool.IsTextFile(p) {
  67. c.NotFound()
  68. return
  69. }
  70. if err, content := template.ToUTF8WithErr(p); err != nil {
  71. if err != nil {
  72. log.Error("Failed to convert encoding to UTF-8: %v", err)
  73. }
  74. c.Data["FileContent"] = string(p)
  75. } else {
  76. c.Data["FileContent"] = content
  77. }
  78. } else {
  79. treeNames = append(treeNames, "") // Append empty string to allow user name the new file.
  80. }
  81. c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath)
  82. c.Data["TreeNames"] = treeNames
  83. c.Data["TreePaths"] = treePaths
  84. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  85. c.Data["commit_summary"] = ""
  86. c.Data["commit_message"] = ""
  87. c.Data["commit_choice"] = "direct"
  88. c.Data["new_branch_name"] = ""
  89. c.Data["last_commit"] = c.Repo.Commit.ID
  90. c.Data["MarkdownFileExts"] = strings.Join(conf.Markdown.FileExtensions, ",")
  91. c.Data["LineWrapExtensions"] = strings.Join(conf.Repository.Editor.LineWrapExtensions, ",")
  92. c.Data["PreviewableFileModes"] = strings.Join(conf.Repository.Editor.PreviewableFileModes, ",")
  93. c.Data["EditorconfigURLPrefix"] = fmt.Sprintf("%s/api/v1/repos/%s/editorconfig/", conf.Server.Subpath, c.Repo.Repository.FullName())
  94. c.Success(tmplEditorEdit)
  95. }
  96. func EditFile(c *context.Context) {
  97. editFile(c, false)
  98. }
  99. func NewFile(c *context.Context) {
  100. editFile(c, true)
  101. }
  102. func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) {
  103. c.PageIs("Edit")
  104. c.RequireHighlightJS()
  105. c.RequireSimpleMDE()
  106. c.Data["IsNewFile"] = isNewFile
  107. oldBranchName := c.Repo.BranchName
  108. branchName := oldBranchName
  109. oldTreePath := c.Repo.TreePath
  110. lastCommit := f.LastCommit
  111. f.LastCommit = c.Repo.Commit.ID.String()
  112. if f.IsNewBrnach() {
  113. branchName = f.NewBranchName
  114. }
  115. // 🚨 SECURITY: Prevent path traversal.
  116. f.TreePath = pathutil.Clean(f.TreePath)
  117. treeNames, treePaths := getParentTreeFields(f.TreePath)
  118. c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath)
  119. c.Data["TreePath"] = f.TreePath
  120. c.Data["TreeNames"] = treeNames
  121. c.Data["TreePaths"] = treePaths
  122. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName
  123. c.Data["FileContent"] = f.Content
  124. c.Data["commit_summary"] = f.CommitSummary
  125. c.Data["commit_message"] = f.CommitMessage
  126. c.Data["commit_choice"] = f.CommitChoice
  127. c.Data["new_branch_name"] = branchName
  128. c.Data["last_commit"] = f.LastCommit
  129. c.Data["MarkdownFileExts"] = strings.Join(conf.Markdown.FileExtensions, ",")
  130. c.Data["LineWrapExtensions"] = strings.Join(conf.Repository.Editor.LineWrapExtensions, ",")
  131. c.Data["PreviewableFileModes"] = strings.Join(conf.Repository.Editor.PreviewableFileModes, ",")
  132. if c.HasError() {
  133. c.Success(tmplEditorEdit)
  134. return
  135. }
  136. if f.TreePath == "" {
  137. c.FormErr("TreePath")
  138. c.RenderWithErr(c.Tr("repo.editor.filename_cannot_be_empty"), tmplEditorEdit, &f)
  139. return
  140. }
  141. if oldBranchName != branchName {
  142. if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
  143. c.FormErr("NewBranchName")
  144. c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorEdit, &f)
  145. return
  146. }
  147. }
  148. var newTreePath string
  149. for index, part := range treeNames {
  150. newTreePath = path.Join(newTreePath, part)
  151. entry, err := c.Repo.Commit.TreeEntry(newTreePath)
  152. if err != nil {
  153. if gitutil.IsErrRevisionNotExist(err) {
  154. // Means there is no item with that name, so we're good
  155. break
  156. }
  157. c.Error(err, "get tree entry")
  158. return
  159. }
  160. if index != len(treeNames)-1 {
  161. if !entry.IsTree() {
  162. c.FormErr("TreePath")
  163. c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), tmplEditorEdit, &f)
  164. return
  165. }
  166. } else {
  167. // 🚨 SECURITY: Do not allow editing if the target file is a symlink.
  168. if entry.IsSymlink() {
  169. c.FormErr("TreePath")
  170. c.RenderWithErr(c.Tr("repo.editor.file_is_a_symlink", part), tmplEditorEdit, &f)
  171. return
  172. } else if entry.IsTree() {
  173. c.FormErr("TreePath")
  174. c.RenderWithErr(c.Tr("repo.editor.filename_is_a_directory", part), tmplEditorEdit, &f)
  175. return
  176. }
  177. }
  178. }
  179. if !isNewFile {
  180. entry, err := c.Repo.Commit.TreeEntry(oldTreePath)
  181. if err != nil {
  182. if gitutil.IsErrRevisionNotExist(err) {
  183. c.FormErr("TreePath")
  184. c.RenderWithErr(c.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), tmplEditorEdit, &f)
  185. } else {
  186. c.Error(err, "get tree entry")
  187. }
  188. return
  189. }
  190. // 🚨 SECURITY: Do not allow editing if the old file is a symlink.
  191. if entry.IsSymlink() {
  192. c.FormErr("TreePath")
  193. c.RenderWithErr(c.Tr("repo.editor.file_is_a_symlink", oldTreePath), tmplEditorEdit, &f)
  194. return
  195. }
  196. if lastCommit != c.Repo.CommitID {
  197. files, err := c.Repo.Commit.FilesChangedAfter(lastCommit)
  198. if err != nil {
  199. c.Error(err, "get changed files")
  200. return
  201. }
  202. for _, file := range files {
  203. if file == f.TreePath {
  204. c.RenderWithErr(c.Tr("repo.editor.file_changed_while_editing", c.Repo.RepoLink+"/compare/"+lastCommit+"..."+c.Repo.CommitID), tmplEditorEdit, &f)
  205. return
  206. }
  207. }
  208. }
  209. }
  210. if oldTreePath != f.TreePath {
  211. // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber.
  212. entry, err := c.Repo.Commit.TreeEntry(f.TreePath)
  213. if err != nil {
  214. if !gitutil.IsErrRevisionNotExist(err) {
  215. c.Error(err, "get tree entry")
  216. return
  217. }
  218. }
  219. if entry != nil {
  220. c.FormErr("TreePath")
  221. c.RenderWithErr(c.Tr("repo.editor.file_already_exists", f.TreePath), tmplEditorEdit, &f)
  222. return
  223. }
  224. }
  225. message := strings.TrimSpace(f.CommitSummary)
  226. if message == "" {
  227. if isNewFile {
  228. message = c.Tr("repo.editor.add", f.TreePath)
  229. } else {
  230. message = c.Tr("repo.editor.update", f.TreePath)
  231. }
  232. }
  233. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  234. if len(f.CommitMessage) > 0 {
  235. message += "\n\n" + f.CommitMessage
  236. }
  237. if err := c.Repo.Repository.UpdateRepoFile(c.User, database.UpdateRepoFileOptions{
  238. OldBranch: oldBranchName,
  239. NewBranch: branchName,
  240. OldTreeName: oldTreePath,
  241. NewTreeName: f.TreePath,
  242. Message: message,
  243. Content: strings.ReplaceAll(f.Content, "\r", ""),
  244. IsNewFile: isNewFile,
  245. }); err != nil {
  246. log.Error("Failed to update repo file: %v", err)
  247. c.FormErr("TreePath")
  248. c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.InternalServerError), tmplEditorEdit, &f)
  249. return
  250. }
  251. if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
  252. c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  253. } else {
  254. c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath)
  255. }
  256. }
  257. func EditFilePost(c *context.Context, f form.EditRepoFile) {
  258. editFilePost(c, f, false)
  259. }
  260. func NewFilePost(c *context.Context, f form.EditRepoFile) {
  261. editFilePost(c, f, true)
  262. }
  263. func DiffPreviewPost(c *context.Context, f form.EditPreviewDiff) {
  264. treePath := c.Repo.TreePath
  265. entry, err := c.Repo.Commit.TreeEntry(treePath)
  266. if err != nil {
  267. c.Error(err, "get tree entry")
  268. return
  269. } else if entry.IsTree() {
  270. c.Status(http.StatusUnprocessableEntity)
  271. return
  272. }
  273. diff, err := c.Repo.Repository.GetDiffPreview(c.Repo.BranchName, treePath, f.Content)
  274. if err != nil {
  275. c.Error(err, "get diff preview")
  276. return
  277. }
  278. if diff.NumFiles() == 0 {
  279. c.PlainText(http.StatusOK, c.Tr("repo.editor.no_changes_to_show"))
  280. return
  281. }
  282. c.Data["File"] = diff.Files[0]
  283. c.Success(tmplEditorDiffPreview)
  284. }
  285. func DeleteFile(c *context.Context) {
  286. c.PageIs("Delete")
  287. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  288. c.Data["TreePath"] = c.Repo.TreePath
  289. c.Data["commit_summary"] = ""
  290. c.Data["commit_message"] = ""
  291. c.Data["commit_choice"] = "direct"
  292. c.Data["new_branch_name"] = ""
  293. c.Success(tmplEditorDelete)
  294. }
  295. func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) {
  296. c.PageIs("Delete")
  297. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  298. // 🚨 SECURITY: Prevent path traversal.
  299. c.Repo.TreePath = pathutil.Clean(c.Repo.TreePath)
  300. c.Data["TreePath"] = c.Repo.TreePath
  301. oldBranchName := c.Repo.BranchName
  302. branchName := oldBranchName
  303. if f.IsNewBrnach() {
  304. branchName = f.NewBranchName
  305. }
  306. c.Data["commit_summary"] = f.CommitSummary
  307. c.Data["commit_message"] = f.CommitMessage
  308. c.Data["commit_choice"] = f.CommitChoice
  309. c.Data["new_branch_name"] = branchName
  310. if c.HasError() {
  311. c.Success(tmplEditorDelete)
  312. return
  313. }
  314. if oldBranchName != branchName {
  315. if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
  316. c.FormErr("NewBranchName")
  317. c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorDelete, &f)
  318. return
  319. }
  320. }
  321. message := strings.TrimSpace(f.CommitSummary)
  322. if message == "" {
  323. message = c.Tr("repo.editor.delete", c.Repo.TreePath)
  324. }
  325. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  326. if len(f.CommitMessage) > 0 {
  327. message += "\n\n" + f.CommitMessage
  328. }
  329. if err := c.Repo.Repository.DeleteRepoFile(c.User, database.DeleteRepoFileOptions{
  330. LastCommitID: c.Repo.CommitID,
  331. OldBranch: oldBranchName,
  332. NewBranch: branchName,
  333. TreePath: c.Repo.TreePath,
  334. Message: message,
  335. }); err != nil {
  336. log.Error("Failed to delete repo file: %v", err)
  337. c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.InternalServerError), tmplEditorDelete, &f)
  338. return
  339. }
  340. if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
  341. c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  342. } else {
  343. c.Flash.Success(c.Tr("repo.editor.file_delete_success", c.Repo.TreePath))
  344. c.Redirect(c.Repo.RepoLink + "/src/" + branchName)
  345. }
  346. }
  347. func renderUploadSettings(c *context.Context) {
  348. c.RequireDropzone()
  349. c.Data["UploadAllowedTypes"] = strings.Join(conf.Repository.Upload.AllowedTypes, ",")
  350. c.Data["UploadMaxSize"] = conf.Repository.Upload.FileMaxSize
  351. c.Data["UploadMaxFiles"] = conf.Repository.Upload.MaxFiles
  352. }
  353. func UploadFile(c *context.Context) {
  354. c.PageIs("Upload")
  355. renderUploadSettings(c)
  356. treeNames, treePaths := getParentTreeFields(c.Repo.TreePath)
  357. if len(treeNames) == 0 {
  358. // We must at least have one element for user to input.
  359. treeNames = []string{""}
  360. }
  361. c.Data["TreeNames"] = treeNames
  362. c.Data["TreePaths"] = treePaths
  363. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  364. c.Data["commit_summary"] = ""
  365. c.Data["commit_message"] = ""
  366. c.Data["commit_choice"] = "direct"
  367. c.Data["new_branch_name"] = ""
  368. c.Success(tmplEditorUpload)
  369. }
  370. func UploadFilePost(c *context.Context, f form.UploadRepoFile) {
  371. c.PageIs("Upload")
  372. renderUploadSettings(c)
  373. oldBranchName := c.Repo.BranchName
  374. branchName := oldBranchName
  375. if f.IsNewBrnach() {
  376. branchName = f.NewBranchName
  377. }
  378. // 🚨 SECURITY: Prevent path traversal.
  379. f.TreePath = pathutil.Clean(f.TreePath)
  380. treeNames, treePaths := getParentTreeFields(f.TreePath)
  381. if len(treeNames) == 0 {
  382. // We must at least have one element for user to input.
  383. treeNames = []string{""}
  384. }
  385. c.Data["TreePath"] = f.TreePath
  386. c.Data["TreeNames"] = treeNames
  387. c.Data["TreePaths"] = treePaths
  388. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName
  389. c.Data["commit_summary"] = f.CommitSummary
  390. c.Data["commit_message"] = f.CommitMessage
  391. c.Data["commit_choice"] = f.CommitChoice
  392. c.Data["new_branch_name"] = branchName
  393. if c.HasError() {
  394. c.Success(tmplEditorUpload)
  395. return
  396. }
  397. if oldBranchName != branchName {
  398. if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
  399. c.FormErr("NewBranchName")
  400. c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorUpload, &f)
  401. return
  402. }
  403. }
  404. var newTreePath string
  405. for _, part := range treeNames {
  406. newTreePath = path.Join(newTreePath, part)
  407. entry, err := c.Repo.Commit.TreeEntry(newTreePath)
  408. if err != nil {
  409. if gitutil.IsErrRevisionNotExist(err) {
  410. // Means there is no item with that name, so we're good
  411. break
  412. }
  413. c.Error(err, "get tree entry")
  414. return
  415. }
  416. // User can only upload files to a directory.
  417. if !entry.IsTree() {
  418. c.FormErr("TreePath")
  419. c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), tmplEditorUpload, &f)
  420. return
  421. }
  422. }
  423. message := strings.TrimSpace(f.CommitSummary)
  424. if message == "" {
  425. message = c.Tr("repo.editor.upload_files_to_dir", f.TreePath)
  426. }
  427. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  428. if len(f.CommitMessage) > 0 {
  429. message += "\n\n" + f.CommitMessage
  430. }
  431. if err := c.Repo.Repository.UploadRepoFiles(c.User, database.UploadRepoFileOptions{
  432. LastCommitID: c.Repo.CommitID,
  433. OldBranch: oldBranchName,
  434. NewBranch: branchName,
  435. TreePath: f.TreePath,
  436. Message: message,
  437. Files: f.Files,
  438. }); err != nil {
  439. log.Error("Failed to upload files: %v", err)
  440. c.FormErr("TreePath")
  441. c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.InternalServerError), tmplEditorUpload, &f)
  442. return
  443. }
  444. if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
  445. c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  446. } else {
  447. c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath)
  448. }
  449. }
  450. func UploadFileToServer(c *context.Context) {
  451. file, header, err := c.Req.FormFile("file")
  452. if err != nil {
  453. c.Error(err, "get file")
  454. return
  455. }
  456. defer file.Close()
  457. buf := make([]byte, 1024)
  458. n, _ := file.Read(buf)
  459. if n > 0 {
  460. buf = buf[:n]
  461. }
  462. fileType := http.DetectContentType(buf)
  463. if len(conf.Repository.Upload.AllowedTypes) > 0 {
  464. allowed := false
  465. for _, t := range conf.Repository.Upload.AllowedTypes {
  466. t := strings.Trim(t, " ")
  467. if t == "*/*" || t == fileType {
  468. allowed = true
  469. break
  470. }
  471. }
  472. if !allowed {
  473. c.PlainText(http.StatusBadRequest, ErrFileTypeForbidden.Error())
  474. return
  475. }
  476. }
  477. upload, err := database.NewUpload(header.Filename, buf, file)
  478. if err != nil {
  479. c.Error(err, "new upload")
  480. return
  481. }
  482. log.Trace("New file uploaded by user[%d]: %s", c.UserID(), upload.UUID)
  483. c.JSONSuccess(map[string]string{
  484. "uuid": upload.UUID,
  485. })
  486. }
  487. func RemoveUploadFileFromServer(c *context.Context, f form.RemoveUploadFile) {
  488. if f.File == "" {
  489. c.Status(http.StatusNoContent)
  490. return
  491. }
  492. if err := database.DeleteUploadByUUID(f.File); err != nil {
  493. c.Error(err, "delete upload by UUID")
  494. return
  495. }
  496. log.Trace("Upload file removed: %s", f.File)
  497. c.Status(http.StatusNoContent)
  498. }