editor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. // 🚨 SECURITY: Prevent path traversal.
  265. treePath := pathutil.Clean(c.Repo.TreePath)
  266. entry, err := c.Repo.Commit.TreeEntry(treePath)
  267. if err != nil {
  268. c.Error(err, "get tree entry")
  269. return
  270. } else if entry.IsTree() {
  271. c.Status(http.StatusUnprocessableEntity)
  272. return
  273. }
  274. diff, err := c.Repo.Repository.GetDiffPreview(c.Repo.BranchName, treePath, f.Content)
  275. if err != nil {
  276. c.Error(err, "get diff preview")
  277. return
  278. }
  279. if diff.NumFiles() == 0 {
  280. c.PlainText(http.StatusOK, c.Tr("repo.editor.no_changes_to_show"))
  281. return
  282. }
  283. c.Data["File"] = diff.Files[0]
  284. c.Success(tmplEditorDiffPreview)
  285. }
  286. func DeleteFile(c *context.Context) {
  287. c.PageIs("Delete")
  288. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  289. c.Data["TreePath"] = c.Repo.TreePath
  290. c.Data["commit_summary"] = ""
  291. c.Data["commit_message"] = ""
  292. c.Data["commit_choice"] = "direct"
  293. c.Data["new_branch_name"] = ""
  294. c.Success(tmplEditorDelete)
  295. }
  296. func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) {
  297. c.PageIs("Delete")
  298. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  299. // 🚨 SECURITY: Prevent path traversal.
  300. c.Repo.TreePath = pathutil.Clean(c.Repo.TreePath)
  301. c.Data["TreePath"] = c.Repo.TreePath
  302. oldBranchName := c.Repo.BranchName
  303. branchName := oldBranchName
  304. if f.IsNewBrnach() {
  305. branchName = f.NewBranchName
  306. }
  307. c.Data["commit_summary"] = f.CommitSummary
  308. c.Data["commit_message"] = f.CommitMessage
  309. c.Data["commit_choice"] = f.CommitChoice
  310. c.Data["new_branch_name"] = branchName
  311. if c.HasError() {
  312. c.Success(tmplEditorDelete)
  313. return
  314. }
  315. if oldBranchName != branchName {
  316. if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
  317. c.FormErr("NewBranchName")
  318. c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorDelete, &f)
  319. return
  320. }
  321. }
  322. message := strings.TrimSpace(f.CommitSummary)
  323. if message == "" {
  324. message = c.Tr("repo.editor.delete", c.Repo.TreePath)
  325. }
  326. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  327. if len(f.CommitMessage) > 0 {
  328. message += "\n\n" + f.CommitMessage
  329. }
  330. if err := c.Repo.Repository.DeleteRepoFile(c.User, database.DeleteRepoFileOptions{
  331. LastCommitID: c.Repo.CommitID,
  332. OldBranch: oldBranchName,
  333. NewBranch: branchName,
  334. TreePath: c.Repo.TreePath,
  335. Message: message,
  336. }); err != nil {
  337. log.Error("Failed to delete repo file: %v", err)
  338. c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.InternalServerError), tmplEditorDelete, &f)
  339. return
  340. }
  341. if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
  342. c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  343. } else {
  344. c.Flash.Success(c.Tr("repo.editor.file_delete_success", c.Repo.TreePath))
  345. c.Redirect(c.Repo.RepoLink + "/src/" + branchName)
  346. }
  347. }
  348. func renderUploadSettings(c *context.Context) {
  349. c.RequireDropzone()
  350. c.Data["UploadAllowedTypes"] = strings.Join(conf.Repository.Upload.AllowedTypes, ",")
  351. c.Data["UploadMaxSize"] = conf.Repository.Upload.FileMaxSize
  352. c.Data["UploadMaxFiles"] = conf.Repository.Upload.MaxFiles
  353. }
  354. func UploadFile(c *context.Context) {
  355. c.PageIs("Upload")
  356. renderUploadSettings(c)
  357. treeNames, treePaths := getParentTreeFields(c.Repo.TreePath)
  358. if len(treeNames) == 0 {
  359. // We must at least have one element for user to input.
  360. treeNames = []string{""}
  361. }
  362. c.Data["TreeNames"] = treeNames
  363. c.Data["TreePaths"] = treePaths
  364. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  365. c.Data["commit_summary"] = ""
  366. c.Data["commit_message"] = ""
  367. c.Data["commit_choice"] = "direct"
  368. c.Data["new_branch_name"] = ""
  369. c.Success(tmplEditorUpload)
  370. }
  371. func UploadFilePost(c *context.Context, f form.UploadRepoFile) {
  372. c.PageIs("Upload")
  373. renderUploadSettings(c)
  374. oldBranchName := c.Repo.BranchName
  375. branchName := oldBranchName
  376. if f.IsNewBrnach() {
  377. branchName = f.NewBranchName
  378. }
  379. // 🚨 SECURITY: Prevent path traversal.
  380. f.TreePath = pathutil.Clean(f.TreePath)
  381. treeNames, treePaths := getParentTreeFields(f.TreePath)
  382. if len(treeNames) == 0 {
  383. // We must at least have one element for user to input.
  384. treeNames = []string{""}
  385. }
  386. c.Data["TreePath"] = f.TreePath
  387. c.Data["TreeNames"] = treeNames
  388. c.Data["TreePaths"] = treePaths
  389. c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + branchName
  390. c.Data["commit_summary"] = f.CommitSummary
  391. c.Data["commit_message"] = f.CommitMessage
  392. c.Data["commit_choice"] = f.CommitChoice
  393. c.Data["new_branch_name"] = branchName
  394. if c.HasError() {
  395. c.Success(tmplEditorUpload)
  396. return
  397. }
  398. if oldBranchName != branchName {
  399. if _, err := c.Repo.Repository.GetBranch(branchName); err == nil {
  400. c.FormErr("NewBranchName")
  401. c.RenderWithErr(c.Tr("repo.editor.branch_already_exists", branchName), tmplEditorUpload, &f)
  402. return
  403. }
  404. }
  405. var newTreePath string
  406. for _, part := range treeNames {
  407. newTreePath = path.Join(newTreePath, part)
  408. entry, err := c.Repo.Commit.TreeEntry(newTreePath)
  409. if err != nil {
  410. if gitutil.IsErrRevisionNotExist(err) {
  411. // Means there is no item with that name, so we're good
  412. break
  413. }
  414. c.Error(err, "get tree entry")
  415. return
  416. }
  417. // User can only upload files to a directory.
  418. if !entry.IsTree() {
  419. c.FormErr("TreePath")
  420. c.RenderWithErr(c.Tr("repo.editor.directory_is_a_file", part), tmplEditorUpload, &f)
  421. return
  422. }
  423. }
  424. message := strings.TrimSpace(f.CommitSummary)
  425. if message == "" {
  426. message = c.Tr("repo.editor.upload_files_to_dir", f.TreePath)
  427. }
  428. f.CommitMessage = strings.TrimSpace(f.CommitMessage)
  429. if len(f.CommitMessage) > 0 {
  430. message += "\n\n" + f.CommitMessage
  431. }
  432. if err := c.Repo.Repository.UploadRepoFiles(c.User, database.UploadRepoFileOptions{
  433. LastCommitID: c.Repo.CommitID,
  434. OldBranch: oldBranchName,
  435. NewBranch: branchName,
  436. TreePath: f.TreePath,
  437. Message: message,
  438. Files: f.Files,
  439. }); err != nil {
  440. log.Error("Failed to upload files: %v", err)
  441. c.FormErr("TreePath")
  442. c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.InternalServerError), tmplEditorUpload, &f)
  443. return
  444. }
  445. if f.IsNewBrnach() && c.Repo.PullRequest.Allowed {
  446. c.Redirect(c.Repo.PullRequestURL(oldBranchName, f.NewBranchName))
  447. } else {
  448. c.Redirect(c.Repo.RepoLink + "/src/" + branchName + "/" + f.TreePath)
  449. }
  450. }
  451. func UploadFileToServer(c *context.Context) {
  452. file, header, err := c.Req.FormFile("file")
  453. if err != nil {
  454. c.Error(err, "get file")
  455. return
  456. }
  457. defer file.Close()
  458. buf := make([]byte, 1024)
  459. n, _ := file.Read(buf)
  460. if n > 0 {
  461. buf = buf[:n]
  462. }
  463. fileType := http.DetectContentType(buf)
  464. if len(conf.Repository.Upload.AllowedTypes) > 0 {
  465. allowed := false
  466. for _, t := range conf.Repository.Upload.AllowedTypes {
  467. t := strings.Trim(t, " ")
  468. if t == "*/*" || t == fileType {
  469. allowed = true
  470. break
  471. }
  472. }
  473. if !allowed {
  474. c.PlainText(http.StatusBadRequest, ErrFileTypeForbidden.Error())
  475. return
  476. }
  477. }
  478. upload, err := database.NewUpload(header.Filename, buf, file)
  479. if err != nil {
  480. c.Error(err, "new upload")
  481. return
  482. }
  483. log.Trace("New file uploaded by user[%d]: %s", c.UserID(), upload.UUID)
  484. c.JSONSuccess(map[string]string{
  485. "uuid": upload.UUID,
  486. })
  487. }
  488. func RemoveUploadFileFromServer(c *context.Context, f form.RemoveUploadFile) {
  489. if f.File == "" {
  490. c.Status(http.StatusNoContent)
  491. return
  492. }
  493. if err := database.DeleteUploadByUUID(f.File); err != nil {
  494. c.Error(err, "delete upload by UUID")
  495. return
  496. }
  497. log.Trace("Upload file removed: %s", f.File)
  498. c.Status(http.StatusNoContent)
  499. }