package main import ( "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "encoding/json" "errors" "flag" "fmt" "io" "log" "net/http" "os" "os/exec" "os/signal" "path/filepath" "regexp" "runtime" "strconv" "strings" "sync" "syscall" "time" ) type File struct { Hash string `json:"hash"` Data *string `json:"data,omitempty"` } type SyncRequest struct { Revision string `json:"revision"` Files map[string]File `json:"files"` } type Artifact struct { Name string `json:"name"` Hash string `json:"hash"` Size int64 `json:"size"` } type Build struct { ID string `json:"id"` Project string `json:"project"` Revision string `json:"revision"` Task string `json:"task"` Status string `json:"status"` Logs []string `json:"logs"` Artifacts []Artifact `json:"artifacts"` cmd *exec.Cmd cancelled bool } type Project struct { Revision string `json:"revision"` Files map[string]File `json:"files"` Busy bool `json:"-"` } type Server struct { mu sync.Mutex root, token string tasks map[string]bool projects map[string]*Project builds map[string]*Build } var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`) var safeTask = regexp.MustCompile(`^:?[A-Za-z0-9_]+(:[A-Za-z0-9_]+)*$`) func id() string { b := make([]byte, 16) if _, e := rand.Read(b); e != nil { panic(e) } return hex.EncodeToString(b) } func digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } func validPath(p string) bool { if p == "" || strings.ContainsAny(p, "\\:\x00<>\"|?*") || strings.HasPrefix(p, "/") { return false } for _, part := range strings.Split(p, "/") { if part == "" || part == "." || part == ".." || strings.TrimRight(part, ". ") != part { return false } base := strings.ToUpper(strings.Split(part, ".")[0]) if regexp.MustCompile(`^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$`).MatchString(base) { return false } } for _, part := range strings.Split(p, "/") { if part == ".git" || part == ".gradle" || part == "build" || part == ".idea" || part == "local.properties" { return false } } return true } func noLinks(root string) error { return filepath.WalkDir(root, func(p string, d os.DirEntry, e error) error { if e != nil { return e } if d.Type()&os.ModeSymlink != 0 { return fmt.Errorf("symlink forbidden: %s", p) } return nil }) } func jsonOut(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(v) } func decode(w http.ResponseWriter, r *http.Request, v any) error { r.Body = http.MaxBytesReader(w, r.Body, 256<<20) d := json.NewDecoder(r.Body) d.DisallowUnknownFields() return d.Decode(v) } func (s *Server) work(p string) string { return filepath.Join(s.root, "projects", p, "work") } func (s *Server) save(p string) error { b, e := json.Marshal(s.projects[p]) if e != nil { return e } path := filepath.Join(s.root, "projects", p, "state.json") if e = os.WriteFile(path+".tmp", b, 0600); e != nil { return e } return os.Rename(path+".tmp", path) } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.token)) != 1 { http.Error(w, "unauthorized", 401) return } if r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs") { s.streamLogs(w, r) return } s.mu.Lock() defer s.mu.Unlock() parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") fail := func(e error) { http.Error(w, e.Error(), 400) } if r.URL.Path == "/api/v1/health" { jsonOut(w, map[string]any{"version": "0.1.0", "os": runtime.GOOS, "sync": "http-manifest"}) return } if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" { http.NotFound(w, r) return } if parts[2] == "projects" { if len(parts) == 3 && r.Method == "POST" { p := id() if e := os.MkdirAll(s.work(p), 0700); e != nil { fail(e) return } s.projects[p] = &Project{Files: map[string]File{}} if e := s.save(p); e != nil { fail(e) return } jsonOut(w, map[string]string{"id": p}) return } if len(parts) != 5 || !safeID.MatchString(parts[3]) { http.NotFound(w, r) return } p := parts[3] pr := s.projects[p] if pr == nil { http.NotFound(w, r) return } if parts[4] == "manifest" && r.Method == "GET" { jsonOut(w, pr) return } if parts[4] == "sync" && r.Method == "POST" { if pr.Busy { http.Error(w, "workspace busy", 409) return } var req SyncRequest if e := decode(w, r, &req); e != nil { fail(e) return } if req.Revision == "" || req.Files == nil { fail(errors.New("revision and files required")) return } if e := noLinks(s.work(p)); e != nil { fail(e) return } staged := map[string][]byte{} seen := map[string]bool{} components := map[string]string{} for path, f := range req.Files { key := strings.ToLower(path) if !validPath(path) || seen[key] { fail(fmt.Errorf("invalid or colliding path: %s", path)) return } seen[key] = true segments := strings.Split(path, "/") for i := range segments { prefix := strings.Join(segments[:i+1], "/") lower := strings.ToLower(prefix) if previous, ok := components[lower]; ok && previous != prefix { fail(fmt.Errorf("inconsistent path casing: %s", path)) return } components[lower] = prefix } if f.Data != nil { b, e := base64.StdEncoding.DecodeString(*f.Data) if e != nil || digest(b) != f.Hash { fail(fmt.Errorf("hash mismatch: %s", path)) return } staged[path] = b } else { b, e := os.ReadFile(filepath.Join(s.work(p), filepath.FromSlash(path))) if e != nil || digest(b) != f.Hash { fail(fmt.Errorf("missing content: %s", path)) return } } } for path := range req.Files { segments := strings.Split(path, "/") for i := 1; i < len(segments); i++ { if seen[strings.ToLower(strings.Join(segments[:i], "/"))] { fail(fmt.Errorf("file/directory collision: %s", path)) return } } } // Validate the entire request before touching the working tree. Invalidate first: // an interrupted commit must never permit building a mixed source revision. pr.Revision = "" if e := s.save(p); e != nil { fail(e) return } for path := range pr.Files { if _, ok := req.Files[path]; !ok { if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) { fail(e) return } } } for path, b := range staged { dest := filepath.Join(s.work(p), filepath.FromSlash(path)) if e := os.MkdirAll(filepath.Dir(dest), 0700); e != nil { fail(e) return } if e := os.WriteFile(dest, b, 0600); e != nil { fail(e) return } } pr.Files = map[string]File{} for path, f := range req.Files { pr.Files[path] = File{Hash: f.Hash} } pr.Revision = req.Revision if e := s.save(p); e != nil { pr.Revision = "" fail(e) return } jsonOut(w, pr) return } if parts[4] == "builds" && r.Method == "POST" { var req struct { Revision string `json:"revision"` Task string `json:"task"` } if e := decode(w, r, &req); e != nil { fail(e) return } if !s.tasks[req.Task] || !safeTask.MatchString(req.Task) { fail(errors.New("task not allowed")) return } if pr.Busy || req.Revision == "" || pr.Revision != req.Revision { http.Error(w, "busy or revision mismatch", 409) return } b := &Build{ID: id(), Project: p, Revision: req.Revision, Task: req.Task, Status: "queued", Logs: []string{}, Artifacts: []Artifact{}} if e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil { fail(e) return } s.builds[b.ID] = b pr.Busy = true go s.run(b) jsonOut(w, b) return } } if parts[2] == "builds" && len(parts) >= 4 { b := s.builds[parts[3]] if b == nil { http.NotFound(w, r) return } if len(parts) == 4 && r.Method == "GET" { jsonOut(w, b) return } if len(parts) == 4 && r.Method == "DELETE" { if b.Status == "queued" || b.Status == "running" { b.cancelled = true if b.cmd != nil && b.cmd.Process != nil { killTree(b.cmd) } } jsonOut(w, b) return } if len(parts) == 6 && parts[4] == "artifacts" && r.Method == "GET" { for _, a := range b.Artifacts { if a.Name == parts[5] { s.mu.Unlock() http.ServeFile(w, r, filepath.Join(s.root, "artifacts", b.ID, a.Name)) s.mu.Lock() return } } } } http.NotFound(w, r) } func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") if len(parts) != 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "builds" { http.NotFound(w, r) return } offset, _ := strconv.Atoi(r.Header.Get("Last-Event-ID")) if offset < 0 { offset = 0 } s.mu.Lock() b := s.builds[parts[3]] s.mu.Unlock() if b == nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") ticker := time.NewTicker(400 * time.Millisecond) defer ticker.Stop() for { s.mu.Lock() lines := append([]string{}, b.Logs...) terminal := b.Status != "queued" && b.Status != "running" s.mu.Unlock() for offset < len(lines) { if _, e := fmt.Fprintf(w, "id: %d\ndata: %s\n\n", offset+1, mustJSON(lines[offset])); e != nil { return } offset++ } if f, ok := w.(http.Flusher); ok { f.Flush() } if terminal { return } select { case <-r.Context().Done(): return case <-ticker.C: } } } func isOutputAPK(work, p string) bool { rel, e := filepath.Rel(work, p) if e != nil { return false } return strings.Contains("/"+filepath.ToSlash(rel), "/build/outputs/") && strings.HasSuffix(strings.ToLower(p), ".apk") } func mustJSON(v any) string { b, _ := json.Marshal(v); return string(b) } type buildWriter struct { s *Server b *Build } func (w buildWriter) Write(p []byte) (int, error) { w.s.mu.Lock() defer w.s.mu.Unlock() w.b.Logs = append(w.b.Logs, string(p)) return len(p), nil } func (s *Server) run(b *Build) { s.mu.Lock() if b.cancelled { b.Status = "cancelled" s.projects[b.Project].Busy = false os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) s.mu.Unlock() return } b.Status = "running" s.mu.Unlock() work := s.work(b.Project) // Remove old APKs only. Retain compilation caches and all other Gradle outputs. err := noLinks(work) if err == nil { err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error { if e != nil { return e } if !d.IsDir() && isOutputAPK(work, p) { return os.Remove(p) } return nil }) } if err == nil { cmd := gradleCommand(work, b.Task) cmd.Dir = work cmd.Stdout = buildWriter{s, b} cmd.Stderr = cmd.Stdout s.mu.Lock() b.cmd = cmd if b.cancelled { err = errors.New("cancelled") } else { err = cmd.Start() } s.mu.Unlock() if err == nil { done := make(chan error, 1) go func() { done <- cmd.Wait() }() select { case err = <-done: case <-time.After(30 * time.Minute): killTree(cmd) err = <-done if err == nil { err = errors.New("build timeout") } } } } artifacts := []Artifact{} if err == nil { err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error { if e != nil { return e } if d.IsDir() || !isOutputAPK(work, p) { return nil } data, e := os.ReadFile(p) if e != nil { return e } name := fmt.Sprintf("%d-%s", len(artifacts), filepath.Base(p)) dest := filepath.Join(s.root, "artifacts", b.ID) if e = os.MkdirAll(dest, 0700); e != nil { return e } if e = os.WriteFile(filepath.Join(dest, name), data, 0600); e != nil { return e } artifacts = append(artifacts, Artifact{name, digest(data), int64(len(data))}) return nil }) } s.mu.Lock() defer s.mu.Unlock() b.cmd = nil b.Artifacts = artifacts b.Status = "success" if len(artifacts) == 0 && err == nil { err = errors.New("no APK produced") } if err != nil { b.Status = "failed" b.Logs = append(b.Logs, err.Error()) } if b.cancelled { b.Status = "cancelled" } s.projects[b.Project].Busy = false dir := filepath.Join(s.root, "artifacts", b.ID) os.MkdirAll(dir, 0700) data, _ := json.MarshalIndent(b, "", " ") os.WriteFile(filepath.Join(dir, "build.json"), data, 0600) os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) } func main() { addr := flag.String("listen", "127.0.0.1:8765", "HTTP bind address; use HTTPS proxy or SSH tunnel remotely") root := flag.String("data", "./data", "service data directory") tasks := flag.String("tasks", ":app:assembleDebug", "comma separated allowed Gradle tasks") flag.Parse() token := os.Getenv("REMOTE_BUILD_TOKEN") if len(token) < 24 { log.Fatal("REMOTE_BUILD_TOKEN must contain at least 24 characters") } abs, e := filepath.Abs(*root) if e != nil { log.Fatal(e) } s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}} for _, t := range strings.Split(*tasks, ",") { if !safeTask.MatchString(t) { log.Fatal("invalid task") } s.tasks[t] = true } entries, _ := os.ReadDir(filepath.Join(abs, "projects")) for _, entry := range entries { if !safeID.MatchString(entry.Name()) { continue } if _, e := os.Stat(filepath.Join(abs, "projects", entry.Name(), "active-build")); e == nil { log.Fatalf("unfinished build in project %s: stop its remaining Gradle processes, then remove active-build marker before restarting", entry.Name()) } data, e := os.ReadFile(filepath.Join(abs, "projects", entry.Name(), "state.json")) if e != nil { continue } var p Project if json.Unmarshal(data, &p) == nil { s.projects[entry.Name()] = &p } } entries, _ = os.ReadDir(filepath.Join(abs, "artifacts")) for _, entry := range entries { data, e := os.ReadFile(filepath.Join(abs, "artifacts", entry.Name(), "build.json")) if e != nil { continue } var b Build if json.Unmarshal(data, &b) == nil { s.builds[b.ID] = &b } } log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS) srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second} stop := make(chan os.Signal, 1) signal.Notify(stop, os.Interrupt, syscall.SIGTERM) go func() { <-stop s.mu.Lock() for _, b := range s.builds { if b.Status == "running" || b.Status == "queued" { b.cancelled = true if b.cmd != nil { killTree(b.cmd) } } } s.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() srv.Shutdown(ctx) }() if e := srv.ListenAndServe(); e != nil && e != http.ErrServerClosed { log.Fatal(e) } // Let workers persist terminal state and clear their active markers. deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { s.mu.Lock() busy := false for _, p := range s.projects { busy = busy || p.Busy } s.mu.Unlock() if !busy { return } time.Sleep(50 * time.Millisecond) } } var _ io.Writer = buildWriter{}