| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "path/filepath" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 19 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 20 | ) |
| 21 | |
| 22 | type windowsProjectBinding struct{ ID, Grant, Path string } |
| 23 | |
| 24 | func windowsProjectIdentity(profile, hostPath string) windowsProjectBinding { |
| 25 | digest := sha256.Sum256([]byte(filepath.Clean(profile) + "\x00" + filepath.Clean(hostPath))) |
| 26 | return windowsProjectBinding{ID: fmt.Sprintf("%x", digest[:8]), Grant: randomToken()} |
| 27 | } |
| 28 | |
| 29 | type bufferedProjectOutput struct { |
| 30 | *bufio.Reader |
| 31 | io.Closer |
| 32 | } |
| 33 | |
| 34 | func startWindowsProjectTransport(cmd *exec.Cmd, hostPath string, binding windowsProjectBinding) (*projectShare, error) { |
| 35 | output, err := cmd.StdoutPipe() |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | input, err := cmd.StdinPipe() |
| 40 | if err != nil { |
| 41 | output.Close() |
| 42 | return nil, err |
| 43 | } |
| 44 | cmd.Stderr = io.Discard |
| 45 | if err = cmd.Start(); err != nil { |
| 46 | input.Close() |
| 47 | output.Close() |
| 48 | return nil, err |
| 49 | } |
| 50 | timeoutDone := make(chan struct{}) |
| 51 | timeout := time.AfterFunc(15*time.Second, func() { defer close(timeoutDone); _ = cmd.Process.Kill(); _ = input.Close() }) |
| 52 | admitted := false |
| 53 | defer func() { |
| 54 | if !admitted { |
| 55 | cancelWindowsAdmissionDeadline(timeout, timeoutDone) |
| 56 | } |
| 57 | }() |
| 58 | data, _ := json.Marshal(map[string]any{"action": "mount", "id": binding.ID, "grant": binding.Grant}) |
| 59 | if _, err = input.Write(append(data, '\n')); err != nil { |
| 60 | _ = cmd.Process.Kill() |
| 61 | _ = cmd.Wait() |
| 62 | return nil, err |
| 63 | } |
| 64 | reader := bufio.NewReaderSize(output, 16384) |
| 65 | line, err := reader.ReadSlice('\n') |
| 66 | var started struct { |
| 67 | Started bool `json:"started"` |
| 68 | ID string `json:"id"` |
| 69 | Path string `json:"path"` |
| 70 | } |
| 71 | if err != nil || len(line) > 16384 || json.Unmarshal(line, &started) != nil || !started.Started || started.ID != binding.ID || !validWindowsProjectPath(started.Path, binding.ID) { |
| 72 | _ = cmd.Process.Kill() |
| 73 | _ = input.Close() |
| 74 | _ = output.Close() |
| 75 | _ = cmd.Wait() |
| 76 | return nil, errors.New("Windows 项目助手尚未准备好挂载") |
| 77 | } |
| 78 | if !cancelWindowsAdmissionDeadline(timeout, timeoutDone) { |
| 79 | _ = cmd.Process.Kill() |
| 80 | _ = input.Close() |
| 81 | _ = output.Close() |
| 82 | _ = cmd.Wait() |
| 83 | return nil, errors.New("Windows 项目连接超时") |
| 84 | } |
| 85 | admitted = true |
| 86 | binding.Path = started.Path |
| 87 | share := &projectShare{cmd: cmd, transport: projectTransport{bufferedProjectOutput{reader, output}, input}, done: make(chan struct{}), windowsProject: &binding} |
| 88 | go func() { |
| 89 | defer close(share.done) |
| 90 | _ = reversesshfs.ServeConfinedVirtual(share.transport, hostPath, false, nil) |
| 91 | share.stop() |
| 92 | _ = cmd.Wait() |
| 93 | }() |
| 94 | return share, nil |
| 95 | } |
| 96 | func validWindowsProjectPath(path, id string) bool { |
| 97 | return len(path) < 4096 && len(path) > 3 && path[1] == ':' && path[2] == '\\' && !strings.ContainsAny(path, "\x00\r\n") && strings.HasSuffix(path, "\\Cage\\Projects\\"+id) && !strings.Contains(path, "\\..\\") |
| 98 | } |
| 99 | func (s *Server) windowsProjectRequest(ctx context.Context, action string, binding windowsProjectBinding, probe string) (map[string]any, error) { |
| 100 | cmd, err := guestos.WindowsRelayCommand(ctx, s.profile, "project-mount") |
| 101 | if err != nil { |
| 102 | return nil, err |
| 103 | } |
| 104 | data, err := json.Marshal(map[string]any{"action": action, "id": binding.ID, "grant": binding.Grant, "probe_name": probe}) |
| 105 | if err != nil { |
| 106 | return nil, err |
| 107 | } |
| 108 | cmd.Stdin = bytes.NewReader(append(data, '\n')) |
| 109 | cmd.Stderr = io.Discard |
| 110 | var output bytes.Buffer |
| 111 | cmd.Stdout = &boundedWindowsStatusWriter{buffer: &output, remaining: 16384} |
| 112 | if err = cmd.Run(); err != nil { |
| 113 | return nil, errors.New("Windows 项目助手尚未连接") |
| 114 | } |
| 115 | var result map[string]any |
| 116 | decoder := json.NewDecoder(&output) |
| 117 | if decoder.Decode(&result) != nil || decoder.Decode(new(any)) != io.EOF || result["error"] != nil { |
| 118 | return nil, errors.New("Windows 项目助手返回无效结果") |
| 119 | } |
| 120 | return result, nil |
| 121 | } |
| 122 | func (s *Server) ensureWindowsProjectShare(hostPath string) error { |
| 123 | s.mu.Lock() |
| 124 | current := s.projectShares[hostPath] |
| 125 | s.mu.Unlock() |
| 126 | if current != nil { |
| 127 | select { |
| 128 | case <-current.done: |
| 129 | current.close() |
| 130 | default: |
| 131 | return nil |
| 132 | } |
| 133 | } |
| 134 | probe, err := os.CreateTemp(hostPath, ".cage-mount-probe-*") |
| 135 | if err != nil { |
| 136 | return errors.New("无法验证项目目录读写权限") |
| 137 | } |
| 138 | defer os.Remove(probe.Name()) |
| 139 | challenge := randomToken() |
| 140 | if _, err = probe.WriteString(challenge); err != nil { |
| 141 | probe.Close() |
| 142 | return err |
| 143 | } |
| 144 | if err = probe.Close(); err != nil { |
| 145 | return err |
| 146 | } |
| 147 | binding := windowsProjectIdentity(s.profile, hostPath) |
| 148 | cmd, err := guestos.WindowsRelayCommand(s.lifetimeContext(), s.profile, "project-mount") |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| 152 | share, err := startWindowsProjectTransport(cmd, hostPath, binding) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | published := false |
| 157 | defer func() { |
| 158 | if !published { |
| 159 | share.close() |
| 160 | } |
| 161 | }() |
| 162 | ctx, cancel := context.WithTimeout(s.operationContext(), 15*time.Second) |
| 163 | defer cancel() |
| 164 | for { |
| 165 | result, probeErr := s.windowsProjectRequest(ctx, "probe", *share.windowsProject, filepath.Base(probe.Name())) |
| 166 | if probeErr == nil && result["mounted"] == true && result["id"] == binding.ID && result["path"] == share.windowsProject.Path && result["proof"] == challenge { |
| 167 | break |
| 168 | } |
| 169 | select { |
| 170 | case <-ctx.Done(): |
| 171 | return errors.New("Windows 项目文件夹连接超时,原有环境和会话保持运行") |
| 172 | case <-share.done: |
| 173 | return errors.New("Windows 项目挂载未能连接") |
| 174 | case <-time.After(100 * time.Millisecond): |
| 175 | } |
| 176 | } |
| 177 | s.mu.Lock() |
| 178 | if s.projectShares == nil { |
| 179 | s.projectShares = make(map[string]*projectShare) |
| 180 | } |
| 181 | s.projectShares[hostPath] = share |
| 182 | if s.windowsProjectHistory == nil { |
| 183 | s.windowsProjectHistory = map[string]string{} |
| 184 | } |
| 185 | s.windowsProjectHistory[share.windowsProject.Path] = hostPath |
| 186 | s.windowsProjectHistory[share.windowsProject.ID] = hostPath |
| 187 | s.mu.Unlock() |
| 188 | published = true |
| 189 | return nil |
| 190 | } |
| 191 | func (s *Server) windowsProjectForHost(hostPath string) (*windowsProjectBinding, error) { |
| 192 | |
| 193 | s.mu.Lock() |
| 194 | share := s.projectShares[hostPath] |
| 195 | s.mu.Unlock() |
| 196 | if share == nil || share.windowsProject == nil { |
| 197 | return nil, errors.New("Windows 项目尚未授权或已经断开") |
| 198 | } |
| 199 | select { |
| 200 | case <-share.done: |
| 201 | return nil, errors.New("Windows 项目连接已撤销") |
| 202 | default: |
| 203 | } |
| 204 | binding := *share.windowsProject |
| 205 | return &binding, nil |
| 206 | } |