editor.go 16 KB

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