Files
RemoteCompilation/server/workspace.go
T

553 lines
16 KiB
Go

package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
type GitSnapshot struct {
Head string `json:"head"`
Branch string `json:"branch"`
Dirty bool `json:"dirty"`
Upstream string `json:"upstream"`
AheadBehind string `json:"aheadBehind"`
}
type WorkspaceRequest struct {
WorkspacePath string `json:"workspacePath"`
ProjectID string `json:"projectId,omitempty"`
JavaHome string `json:"javaHome,omitempty"`
Git *GitSnapshot `json:"git,omitempty"`
}
func reservedSource(path string) bool {
for _, part := range strings.Split(filepath.ToSlash(path), "/") {
switch strings.ToLower(part) {
case ".git", ".gradle", ".idea", "build", ".remotecompile", ".kotlin", ".cxx", ".externalnativebuild", "node_modules", "local.properties", "key.properties", "keystore.properties":
return true
}
lower := strings.ToLower(part)
if strings.HasPrefix(lower, ".env") || strings.HasSuffix(lower, ".jks") || strings.HasSuffix(lower, ".keystore") {
return true
}
}
return false
}
func fileDigest(path string) (string, error) {
f, e := os.Open(path)
if e != nil {
return "", e
}
defer f.Close()
h := sha256.New()
if _, e = io.Copy(h, f); e != nil {
return "", e
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func (s *Server) strictManifest(p string) *Project {
pr := *s.projects[p]
pr.Files = map[string]File{}
// Never advertise a stale hash: Gradle or a human may have changed/removed a file.
for path, f := range s.projects[p].Files {
if !validPath(path) {
continue
}
if actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); e == nil && actual.Hash == f.Hash {
pr.Files[path] = actual
}
}
pr.WorkspacePath = s.work(p)
return &pr
}
// A clean checkout is a valid new sync base, even if HEAD did not move.
// Keep this read-only: a build must still match the last committed sync snapshot.
func (s *Server) manifest(p string) *Project {
result := s.strictManifest(p)
if s.projects[p].WorkspacePath == "" {
return result
}
remote, e := gitSnapshot(s.work(p))
if e != nil || remote == nil {
return result
}
if remote.Dirty {
for path, f := range s.projects[p].Files {
if !validPath(path) || f.TextHash == "" {
continue
}
if _, ok := result.Files[path]; ok {
continue
}
current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
if e == nil && current.TextHash == f.TextHash {
result.Files[path] = current
result.Revision = ""
}
}
return result
}
actual, e := sourceInventory(s.work(p))
if e != nil {
return result
}
result.Files = map[string]File{}
for path := range actual {
f, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
if e != nil {
return s.strictManifest(p)
}
result.Files[path] = f
}
if !sameSourceHashes(s.projects[p].Files, result.Files) {
result.Revision = ""
}
result.Git = remote
return result
}
func sameSourceHashes(a, b map[string]File) bool {
count := 0
for path, f := range a {
if !validPath(path) {
continue
}
count++
if b[path].Hash != f.Hash {
return false
}
}
return count == len(b)
}
// Include restored/deleted tracked files when syncing after a clean reset/checkout.
func (s *Server) syncBase(p string) (map[string]File, error) {
old := s.projects[p].Files
if s.projects[p].WorkspacePath == "" {
return old, nil
}
remote, e := gitSnapshot(s.work(p))
if e != nil {
return nil, e
}
if remote == nil || remote.Dirty {
return old, nil
}
actual, e := sourceInventory(s.work(p))
if e != nil {
return nil, e
}
base := map[string]File{}
for path, f := range old {
base[path] = f
}
for path, f := range actual {
base[path] = f
}
return base, nil
}
func (s *Server) validateWorkspace(path string) (string, error) {
if !filepath.IsAbs(path) {
return "", fmt.Errorf("请填写服务端已有文件夹的绝对路径")
}
path = filepath.Clean(path)
dataRel, dataErr := filepath.Rel(s.root, path)
if dataErr == nil && dataRel != ".." && !strings.HasPrefix(dataRel, ".."+string(filepath.Separator)) {
parts := strings.Split(filepath.ToSlash(dataRel), "/")
if len(parts) != 3 || parts[0] != "projects" || !safeID.MatchString(parts[1]) || parts[2] != "work" {
return "", fmt.Errorf("不能选择服务数据或元数据目录;旧工作区请精确选择 projects/<id>/work")
}
}
if _, ok := s.containingWorkspaceRoot(path, false); !ok {
return "", fmt.Errorf("远程文件夹必须位于管理员允许的根目录内:%s", strings.Join(s.allowedWorkspaceRoots(), ", "))
}
// Reject both final and ancestor symlink/junction redirection.
for current := path; ; current = filepath.Dir(current) {
i, e := os.Lstat(current)
if e != nil {
return "", fmt.Errorf("服务端文件夹不存在或不可访问:%s", current)
}
if !i.IsDir() || i.Mode()&os.ModeSymlink != 0 {
return "", fmt.Errorf("远程文件夹不允许符号链接或重解析路径")
}
if current == filepath.Dir(current) {
break
}
}
resolved, e := filepath.EvalSymlinks(path)
if e != nil {
return "", e
}
if !strings.EqualFold(filepath.Clean(resolved), path) {
return "", fmt.Errorf("远程文件夹经过链接重定向")
}
return path, nil
}
// Directory browsing is confined to the administrator's root. Files are never listed.
func (s *Server) browseDirectories(w http.ResponseWriter, r *http.Request) {
roots := s.allowedWorkspaceRoots()
path := r.URL.Query().Get("path")
if len(roots) > 1 && (path == "" || path == "@roots") {
dirs := []map[string]string{}
for _, root := range roots {
dirs = append(dirs, map[string]string{"name": root, "path": root})
}
jsonOut(w, map[string]any{"path": "", "root": "", "roots": roots, "parent": "", "selectable": false, "directories": dirs, "limit": 1000})
return
}
if path == "" {
path = roots[0]
}
path = filepath.Clean(path)
root, ok := s.containingWorkspaceRoot(path, true)
if !ok {
http.Error(w, "目录超出管理员允许的根目录", 400)
return
}
rel, _ := filepath.Rel(root, path)
resolved, e := filepath.EvalSymlinks(path)
if e != nil || !strings.EqualFold(filepath.Clean(resolved), path) {
http.Error(w, "目录不存在或经过链接重定向", 400)
return
}
entries, e := os.ReadDir(path)
if e != nil {
http.Error(w, "服务账户无法读取该目录", 400)
return
}
dirs := []map[string]string{}
for _, entry := range entries {
if entry.IsDir() && !reservedSource(entry.Name()) {
dirs = append(dirs, map[string]string{"name": entry.Name(), "path": filepath.Join(path, entry.Name())})
}
if len(dirs) >= 1000 {
break
}
}
parent := ""
if rel != "." {
parent = filepath.Dir(path)
} else if len(roots) > 1 {
parent = "@roots"
}
_, selectErr := s.validateWorkspace(path)
jsonOut(w, map[string]any{"path": path, "root": root, "roots": roots, "parent": parent, "selectable": selectErr == nil, "directories": dirs, "limit": 1000})
}
func gitCommand(work string, input []byte, args ...string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "safe.directory=" + work, "-C", work}, args...)...)
cmd.Stdin = bytes.NewReader(input)
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_OPTIONAL_LOCKS=0")
return cmd.Output()
}
func gitSnapshot(work string) (*GitSnapshot, error) {
// Only inspect the selected repository, never silently inherit its parent repository.
if _, e := os.Stat(filepath.Join(work, ".git")); os.IsNotExist(e) {
return nil, nil
}
if _, e := gitCommand(work, nil, "rev-parse", "--is-inside-work-tree"); e != nil {
return nil, fmt.Errorf("服务端 Git 仓库无法读取;请检查 Git 安装、仓库所有者及服务账户权限")
}
if _, e := gitCommand(work, nil, "status", "--porcelain", "--untracked-files=normal"); e != nil {
return nil, fmt.Errorf("无法读取服务端 Git 状态")
}
read := func(args ...string) string {
b, _ := gitCommand(work, nil, args...)
return strings.TrimSpace(string(b))
}
return &GitSnapshot{Head: read("rev-parse", "--verify", "HEAD"), Branch: read("symbolic-ref", "--short", "-q", "HEAD"), Dirty: read("status", "--porcelain", "--untracked-files=normal") != "", Upstream: read("rev-parse", "--abbrev-ref", "@{upstream}"), AheadBehind: read("rev-list", "--left-right", "--count", "HEAD...@{upstream}")}, nil
}
func sourceInventory(work string) (map[string]File, error) {
if e := noLinks(work); e != nil {
return nil, e
}
result := map[string]File{}
git, e := gitSnapshot(work)
if e != nil {
return nil, e
}
var paths []string
if git != nil {
b, e := gitCommand(work, nil, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
if e != nil {
return nil, fmt.Errorf("无法读取服务端 Git 文件清单")
}
paths = strings.Split(strings.TrimSuffix(string(b), "\x00"), "\x00")
ignored, e := gitCommand(work, b, "check-ignore", "--no-index", "-z", "--stdin")
if e != nil {
if exit, ok := e.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
return nil, fmt.Errorf("服务端 Git 忽略规则检查失败")
}
}
skip := map[string]bool{}
for _, p := range strings.Split(string(ignored), "\x00") {
skip[p] = true
}
filtered := paths[:0]
for _, p := range paths {
if !skip[p] {
filtered = append(filtered, p)
}
}
paths = filtered
} else {
e = filepath.WalkDir(work, func(path string, d os.DirEntry, e error) error {
if e != nil {
return e
}
rel, _ := filepath.Rel(work, path)
if rel == "." {
return nil
}
if reservedSource(rel) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if !d.IsDir() {
paths = append(paths, filepath.ToSlash(rel))
}
return nil
})
if e != nil {
return nil, e
}
}
for _, p := range paths {
if p == "" || reservedSource(p) {
continue
}
if !validPath(p) {
return nil, fmt.Errorf("服务端存在无法同步的路径:%s", p)
}
path := filepath.Join(work, filepath.FromSlash(p))
i, e := os.Lstat(path)
if os.IsNotExist(e) {
continue
}
if e != nil {
return nil, e
}
if !i.Mode().IsRegular() {
return nil, fmt.Errorf("服务端源码包含链接或特殊文件:%s", p)
}
h, e := fileDigest(path)
if e != nil {
return nil, e
}
result[p] = File{Hash: h}
}
return result, nil
}
func compareGit(local, remote *GitSnapshot) error {
if remote != nil && local == nil {
return fmt.Errorf("服务端存在 Git 仓库,但本机无法读取 Git 状态")
}
if local != nil && remote != nil && local.Head != remote.Head {
return fmt.Errorf("两边 Git 提交不同,请先手动同步仓库;本机 HEAD=%s,服务端 HEAD=%s", local.Head, remote.Head)
}
return nil
}
func (s *Server) checkGit(p string, local *GitSnapshot) error {
remote, e := gitSnapshot(s.work(p))
if e != nil {
return e
}
if e = compareGit(local, remote); e != nil {
return e
}
if s.projects[p].WorkspacePath == "" {
return nil
}
// A clean matching Git checkout may have been deliberately updated by its owner.
if remote != nil && !remote.Dirty {
return nil
}
// Detect remote edits even after a previous sync intentionally made the remote Git tree dirty.
actual, e := sourceInventory(s.work(p))
if e != nil {
return e
}
for path, f := range s.projects[p].Files {
if !validPath(path) {
continue
}
if actual[path].Hash != f.Hash {
if f.TextHash != "" {
if current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); e == nil && current.TextHash == f.TextHash {
continue
}
}
return fmt.Errorf("服务端源码已变化:%s;为避免覆盖,请先处理服务端修改", path)
}
}
for path := range actual {
if _, ok := s.projects[p].Files[path]; !ok {
return fmt.Errorf("服务端新增源码:%s;请先处理服务端修改", path)
}
}
return nil
}
func (s *Server) checkWorkspace(w http.ResponseWriter, r *http.Request) {
var req WorkspaceRequest
if e := decode(w, r, &req); e != nil {
http.Error(w, e.Error(), 400)
return
}
path, e := s.validateWorkspace(req.WorkspacePath)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
remote, e := gitSnapshot(path)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
e = compareGit(req.Git, remote)
if pr := s.projects[req.ProjectID]; pr != nil && filepath.Clean(s.work(req.ProjectID)) != path {
e = fmt.Errorf("工程ID与服务端文件夹不匹配,请重新保存配置以分配工作区")
}
if e == nil {
if pr := s.projects[req.ProjectID]; pr != nil && pr.Busy {
e = fmt.Errorf("工作区正在构建,请等待完成")
}
}
if e == nil {
if pr := s.projects[req.ProjectID]; pr != nil && filepath.Clean(s.work(req.ProjectID)) == path {
e = s.checkGit(req.ProjectID, req.Git)
} else if remote != nil && remote.Dirty {
e = fmt.Errorf("服务端仓库有未提交修改;首次绑定前请先处理,避免覆盖")
}
}
message := "检查通过;双方 Git HEAD 相同,未提交的本机源码将增量同步"
if remote == nil {
message = "服务端没有 .git,无法比较 Git 提交;同步时使用本机 Git 忽略规则"
}
if e != nil {
message = e.Error()
}
var report Preflight
if pr := s.projects[req.ProjectID]; pr != nil && pr.Busy {
report = Preflight{Ready: false, Items: []CheckItem{{Name: "工作区", Status: "error", Path: path, Message: "工作区正在构建,暂不执行写入探针"}}}
} else {
cfg, configErr := s.buildEnvironment()
if configErr == nil && req.JavaHome != "" {
cfg.JavaHome, configErr = s.selectedJDK(req.JavaHome)
}
if configErr != nil {
report = Preflight{Items: []CheckItem{{Name: "环境配置", Status: "error", Message: configErr.Error()}}}
} else {
report = s.preflight(path, cfg)
}
}
jsonOut(w, map[string]any{"workspacePath": path, "git": remote, "canSync": e == nil, "message": message, "preflight": report})
}
func (s *Server) createProject(w http.ResponseWriter, r *http.Request) {
var req WorkspaceRequest
if e := decode(w, r, &req); e != nil && e != io.EOF {
http.Error(w, e.Error(), 400)
return
}
p := id()
pr := &Project{Files: map[string]File{}}
if req.WorkspacePath != "" {
path, e := s.validateWorkspace(req.WorkspacePath)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
for other := range s.projects {
if strings.EqualFold(s.work(other), path) {
if s.projects[other].WorkspacePath == "" && !s.projects[other].Busy {
remote, e := gitSnapshot(path)
if e == nil {
e = compareGit(req.Git, remote)
}
if e == nil && remote != nil && remote.Dirty {
e = fmt.Errorf("服务端仓库有未提交修改,首次绑定前请先处理")
}
if e != nil {
http.Error(w, e.Error(), 409)
return
}
files, e := sourceInventory(path)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
s.projects[other].WorkspacePath = path
s.projects[other].Files = files
s.projects[other].Git = req.Git
if e = s.save(other); e != nil {
http.Error(w, e.Error(), 400)
return
}
jsonOut(w, map[string]string{"id": other, "workspacePath": path})
return
}
http.Error(w, "该服务端文件夹已绑定另一个工程,请选择独立工作区", 409)
return
}
}
for other := range s.projects {
a := strings.ToLower(filepath.Clean(s.work(other))) + string(filepath.Separator)
b := strings.ToLower(path) + string(filepath.Separator)
if strings.HasPrefix(a, b) || strings.HasPrefix(b, a) {
http.Error(w, "服务端工程目录不能与其他工作区重叠", 409)
return
}
}
remote, e := gitSnapshot(path)
if e == nil {
e = compareGit(req.Git, remote)
}
if e == nil && remote != nil && remote.Dirty {
e = fmt.Errorf("服务端仓库有未提交修改,首次绑定前请先处理")
}
if e != nil {
http.Error(w, e.Error(), 409)
return
}
files, e := sourceInventory(path)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
pr.WorkspacePath = path
pr.Files = files
pr.Git = req.Git
}
s.projects[p] = pr
if e := os.MkdirAll(filepath.Join(s.root, "projects", p), 0700); e != nil {
delete(s.projects, p)
http.Error(w, e.Error(), 400)
return
}
if req.WorkspacePath == "" {
if e := os.MkdirAll(s.work(p), 0700); e != nil {
delete(s.projects, p)
http.Error(w, e.Error(), 400)
return
}
}
if e := s.save(p); e != nil {
delete(s.projects, p)
http.Error(w, e.Error(), 400)
return
}
jsonOut(w, map[string]string{"id": p, "workspacePath": s.work(p)})
}