package main import ( "fmt" "io" "net/http" "os" "path/filepath" "runtime" "strings" ) func privatePath(name string) bool { if strings.ContainsAny(name, "\\:\x00<>\"|?*") || name == "" { return false } for _, r := range name { if r < 32 || r == 127 { return false } } parts := strings.Split(name, "/") leaf := parts[len(parts)-1] for _, part := range parts { if strings.TrimRight(part, ". ") != part { return false } } if strings.EqualFold(leaf, ".gitignore") || strings.EqualFold(leaf, ".gitattributes") || (reservedSource(leaf) && !strings.HasSuffix(strings.ToLower(leaf), ".jks") && !strings.HasSuffix(strings.ToLower(leaf), ".keystore") && leaf != "local.properties" && leaf != "key.properties" && leaf != "keystore.properties" && !strings.HasPrefix(leaf, ".env")) { return false } parts[len(parts)-1] = "private.asset" return validPath(strings.Join(parts, "/")) && leaf != "." && leaf != ".." && validPath("file/"+strings.TrimSuffix(leaf, filepath.Ext(leaf))+".asset") } func parsePrivateList(content string) ([]string, error) { if len(content) > 64<<10 { return nil, fmt.Errorf("私有文件清单不能超过64KiB") } names := []string{} seen := map[string]bool{} for n, line := range strings.Split(strings.TrimPrefix(content, "\ufeff"), "\n") { line = strings.TrimSpace(line) if line == "" || strings.HasPrefix(line, "#") { continue } if !privatePath(line) { return nil, fmt.Errorf("清单第%d行路径非法:%s;请填写工程内相对文件路径,使用/,禁止绝对路径、../及缓存目录", n+1, line) } key := line if runtime.GOOS == "windows" { key = strings.ToLower(key) } if seen[key] { return nil, fmt.Errorf("私有文件重复:%s", line) } seen[key] = true names = append(names, line) if len(names) > 256 { return nil, fmt.Errorf("私有文件清单最多256项") } } return names, nil } func (s *Server) privateList(source string) (string, string, error) { key := filepath.Clean(source) if runtime.GOOS == "windows" { key = strings.ToLower(key) } path := filepath.Join(s.root, "private-files", digest([]byte(key))+".txt") data, e := os.ReadFile(path) if os.IsNotExist(e) { return path, "", nil } return path, string(data), e } func privateSource(source, name string) (string, error) { path := filepath.Join(source, filepath.FromSlash(name)) for current := path; current != source; current = filepath.Dir(current) { info, e := os.Lstat(current) if e != nil { return "", fmt.Errorf("来源目录缺少文件或无法读取:%s", name) } if info.Mode()&os.ModeSymlink != 0 { return "", fmt.Errorf("私有文件不允许符号链接:%s", name) } resolved, e := filepath.EvalSymlinks(current) if e != nil || !sameAccessValue(resolved, current) { return "", fmt.Errorf("私有文件路径被重定向:%s", name) } } f, e := os.Open(path) if e != nil { return "", fmt.Errorf("服务账户不能读取私有文件:%s", name) } defer f.Close() info, e := f.Stat() if e != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 { return "", fmt.Errorf("私有文件须为不超过16MiB的普通文件:%s", name) } return path, nil } func (s *Server) privateReport(source, content, path string, exists bool) map[string]any { names, e := parsePrivateList(content) entries := []map[string]string{} ready := e == nil if e == nil { for _, name := range names { status := "ok" message := "存在且服务账户可读" if _, err := privateSource(source, name); err != nil { status = "error" message = err.Error() ready = false } entries = append(entries, map[string]string{"path": name, "status": status, "message": message}) } } message := "私有文件清单已读取;路径相对于服务端工程来源目录" if !exists { message = "尚未创建私有文件清单;点击编辑后保存到服务端" } if e != nil { message = e.Error() } return map[string]any{"workspacePath": source, "manifestPath": path, "exists": exists, "content": content, "hash": digest([]byte(content)), "ready": ready, "entries": entries, "message": message} } func (s *Server) servePrivateFiles(w http.ResponseWriter, r *http.Request) { source := r.URL.Query().Get("workspacePath") var req struct { WorkspacePath string `json:"workspacePath"` Content string `json:"content"` BaseHash string `json:"baseHash"` } if r.Method == "PUT" { if e := decode(w, r, &req); e != nil { http.Error(w, e.Error(), 400) return } source = req.WorkspacePath } else if r.Method != "GET" { http.Error(w, "method not allowed", 405) return } source, e := s.validateWorkspace(source) if e != nil { http.Error(w, e.Error(), 400) return } path, content, e := s.privateList(source) if e != nil { http.Error(w, e.Error(), 400) return } if r.Method == "PUT" { names, e := parsePrivateList(req.Content) if e != nil { http.Error(w, e.Error(), 400) return } if req.BaseHash != digest([]byte(content)) { http.Error(w, "服务端清单已被其他编辑修改,请备份本地内容后重新读取清单", 409) return } for _, pr := range s.projects { if sameAccessValue(pr.WorkspacePath, source) { if pr.Busy { http.Error(w, "该工程正在构建,请结束后保存清单", 409) return } for _, name := range names { if pr.Pending != nil && privateConflict(pr.Pending.Files, name) { http.Error(w, "私有文件与未完成的同步任务冲突:"+name, 409) return } if privateConflict(pr.Files, name) { http.Error(w, "私有文件与普通源码同步冲突:"+name+";请先在本机忽略并重新同步移除后再配置", 409) return } } } } if e = os.MkdirAll(filepath.Dir(path), 0700); e == nil { var f *os.File f, e = os.CreateTemp(filepath.Dir(path), ".list-*") if e == nil { temp := f.Name() _, e = io.WriteString(f, req.Content) closeErr := f.Close() if e == nil { e = closeErr } if e == nil { e = os.Rename(temp, path) } os.Remove(temp) } } if e != nil { http.Error(w, e.Error(), 400) return } content = req.Content } _, statErr := os.Stat(path) jsonOut(w, s.privateReport(source, content, path, statErr == nil)) } func (s *Server) privateNames(p string) ([]string, error) { _, content, e := s.privateList(s.projects[p].WorkspacePath) if e != nil { return nil, e } return parsePrivateList(content) } func (s *Server) projectInventory(p string) (map[string]File, error) { files, e := dedicatedInventory(s.work(p)) if e != nil { return nil, e } for name := range s.projects[p].PrivateFiles { if _, managed := s.projects[p].Files[name]; !managed { delete(files, name) } } return files, nil } func (s *Server) preparePrivateFiles(p string) error { pr := s.projects[p] if !pr.Dedicated { return nil } names, e := s.privateNames(p) if e != nil { return e } if len(names) == 0 && len(pr.PrivateFiles) == 0 { return nil } source, e := s.validateWorkspace(pr.WorkspacePath) if e != nil { return e } wanted := map[string]string{} for _, name := range names { if privateConflict(pr.Files, name) { return fmt.Errorf("私有文件与源码同步冲突:%s", name) } path, err := privateSource(source, name) if err != nil { return err } wanted[name] = path } root := s.work(p) if e = noLinks(root); e != nil { return e } if pr.PrivateFiles == nil { pr.PrivateFiles = map[string]File{} } for name, old := range pr.PrivateFiles { if _, keep := wanted[name]; !keep { dest := filepath.Join(root, filepath.FromSlash(name)) data, err := os.ReadFile(dest) if err == nil { if digest(data) != old.Hash { return fmt.Errorf("已移出清单的私有文件与保存摘要不一致,无法自动删除:%s", name) } if err = os.Remove(dest); err != nil { return err } } else if !os.IsNotExist(err) { return err } delete(pr.PrivateFiles, name) } } for name, path := range wanted { input, err := os.Open(path) if err != nil { return fmt.Errorf("读取私有文件失败:%s", name) } data, err := io.ReadAll(io.LimitReader(input, (16<<20)+1)) input.Close() if err != nil { return fmt.Errorf("读取私有文件失败:%s", name) } if len(data) > 16<<20 { return fmt.Errorf("私有文件超过16MiB:%s", name) } // Journal names before copying so a restart can distinguish private files from extra source edits. pr.PrivateFiles[name] = File{Hash: digest(data)} if err = s.save(p); err != nil { return err } dest := filepath.Join(root, filepath.FromSlash(name)) if err = os.MkdirAll(filepath.Dir(dest), 0700); err != nil { return err } f, err := os.CreateTemp(filepath.Dir(dest), ".private-*") if err != nil { return err } temp := f.Name() _, err = f.Write(data) closeErr := f.Close() if err == nil { err = closeErr } if err == nil { err = os.Rename(temp, dest) } os.Remove(temp) if err != nil { return err } } return s.save(p) } func privateConflict(files map[string]File, name string) bool { for path := range files { if path == name || (runtime.GOOS == "windows" && strings.EqualFold(path, name)) { return true } } return false } func (s *Server) privatePreflight(report *Preflight, source string) { path, content, e := s.privateList(source) if e != nil { report.add("私有文件清单", "error", path, e.Error()) return } _, statErr := os.Stat(path) result := s.privateReport(source, content, path, statErr == nil) if _, e := parsePrivateList(content); e != nil { report.add("私有文件清单", "error", path, e.Error()) return } if statErr != nil { report.add("私有文件清单", "warning", path, "尚未创建;如需未跟踪签名文件,请在侧边栏编辑私有文件清单并保存到服务端") return } for _, entry := range result["entries"].([]map[string]string) { report.add("私有文件", entry["status"], entry["path"], entry["message"]) } }