| 1 | |
| 2 | |
| 3 | package guestos |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "os" |
| 15 | "path/filepath" |
| 16 | "runtime" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "time" |
| 20 | "unsafe" |
| 21 | |
| 22 | "github.com/Microsoft/go-winio" |
| 23 | "github.com/google/uuid" |
| 24 | "golang.org/x/sys/windows" |
| 25 | |
| 26 | "github.com/sylvinus/agent-vm/internal/paths" |
| 27 | ) |
| 28 | |
| 29 | |
| 30 | |
| 31 | type WindowsHostManagerBinding struct { |
| 32 | Version int `json:"version"` |
| 33 | VMID uuid.UUID `json:"vm_id"` |
| 34 | HostSID string `json:"host_sid"` |
| 35 | DiskPath string `json:"disk_path"` |
| 36 | DiskVolume uint32 `json:"disk_volume"` |
| 37 | DiskFileID uint64 `json:"disk_file_id"` |
| 38 | } |
| 39 | |
| 40 | func WindowsHostManagerServiceName(id uuid.UUID) string { return "CageHV-" + id.String() } |
| 41 | |
| 42 | func managerKnownFolder(id *windows.KNOWNFOLDERID) string { |
| 43 | p, err := windows.KnownFolderPath(id, 0) |
| 44 | if err != nil { |
| 45 | return "" |
| 46 | } |
| 47 | return p |
| 48 | } |
| 49 | |
| 50 | func WindowsHostManagerBindingPath(id uuid.UUID) string { |
| 51 | return filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramData), "Cage", "HyperVManager", id.String(), "binding.json") |
| 52 | } |
| 53 | |
| 54 | func WindowsHostManagerExecutablePath(id uuid.UUID) string { |
| 55 | return filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramFiles), "Cage Host Manager", id.String(), "Cage.HyperVManager.exe") |
| 56 | } |
| 57 | |
| 58 | func managerProtected(path, hostSID string) error { |
| 59 | return managerProtectedAccess(path, hostSID, false) |
| 60 | } |
| 61 | |
| 62 | func managerSharedProtected(path, hostSID string) error { |
| 63 | return managerProtectedAccess(path, hostSID, true) |
| 64 | } |
| 65 | |
| 66 | func managerProtectedAccess(path, hostSID string, shared bool) error { |
| 67 | for p := path; p != filepath.Dir(p); p = filepath.Dir(p) { |
| 68 | name, err := windows.UTF16PtrFromString(p) |
| 69 | if err != nil { |
| 70 | return errors.New("binding_invalid") |
| 71 | } |
| 72 | attributes, err := windows.GetFileAttributes(name) |
| 73 | if err != nil || attributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 { |
| 74 | return errors.New("binding_invalid") |
| 75 | } |
| 76 | } |
| 77 | sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION) |
| 78 | if err != nil { |
| 79 | return errors.New("binding_invalid") |
| 80 | } |
| 81 | owner, _, err := sd.Owner() |
| 82 | if err != nil || owner == nil || !(owner.IsWellKnown(windows.WinLocalSystemSid) || owner.IsWellKnown(windows.WinBuiltinAdministratorsSid)) { |
| 83 | return errors.New("binding_invalid") |
| 84 | } |
| 85 | control, _, err := sd.Control() |
| 86 | if err != nil || control&windows.SE_DACL_PROTECTED == 0 { |
| 87 | return errors.New("binding_invalid") |
| 88 | } |
| 89 | acl, _, err := sd.DACL() |
| 90 | if err != nil || acl == nil || acl.AceCount == 0 { |
| 91 | return errors.New("binding_invalid") |
| 92 | } |
| 93 | for index := uint32(0); index < uint32(acl.AceCount); index++ { |
| 94 | var ace *windows.ACCESS_ALLOWED_ACE |
| 95 | if windows.GetAce(acl, index, &ace) != nil || ace.Header.AceType != windows.ACCESS_ALLOWED_ACE_TYPE { |
| 96 | return errors.New("binding_invalid") |
| 97 | } |
| 98 | sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) |
| 99 | if sid.IsWellKnown(windows.WinLocalSystemSid) || sid.IsWellKnown(windows.WinBuiltinAdministratorsSid) { |
| 100 | continue |
| 101 | } |
| 102 | const deleteChild = 0x40 |
| 103 | const modify = windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA | windows.FILE_WRITE_EA | windows.FILE_WRITE_ATTRIBUTES | deleteChild | windows.DELETE | windows.WRITE_DAC | windows.WRITE_OWNER | windows.GENERIC_WRITE | windows.GENERIC_ALL |
| 104 | if (!shared && sid.String() != hostSID) || ace.Mask&modify != 0 { |
| 105 | return errors.New("binding_invalid") |
| 106 | } |
| 107 | } |
| 108 | return nil |
| 109 | } |
| 110 | |
| 111 | func LoadWindowsHostManagerBinding(path string) (WindowsHostManagerBinding, error) { |
| 112 | var binding WindowsHostManagerBinding |
| 113 | file, err := os.Open(path) |
| 114 | if err != nil { |
| 115 | return binding, errors.New("binding_invalid") |
| 116 | } |
| 117 | defer file.Close() |
| 118 | info, err := file.Stat() |
| 119 | if err != nil || !info.Mode().IsRegular() || info.Size() > windowsHostManagerWireLimit { |
| 120 | return binding, errors.New("binding_invalid") |
| 121 | } |
| 122 | decoder := json.NewDecoder(io.LimitReader(file, windowsHostManagerWireLimit+1)) |
| 123 | decoder.DisallowUnknownFields() |
| 124 | if decoder.Decode(&binding) != nil || decoder.Decode(new(any)) != io.EOF || binding.Version != windowsHostManagerVersion || binding.VMID == uuid.Nil || binding.DiskFileID == 0 || binding.DiskVolume == 0 || !filepath.IsAbs(binding.DiskPath) || strings.HasPrefix(binding.DiskPath, `\\`) || !strings.EqualFold(filepath.Ext(binding.DiskPath), ".vhdx") { |
| 125 | return binding, errors.New("binding_invalid") |
| 126 | } |
| 127 | sid, err := windows.StringToSid(binding.HostSID) |
| 128 | if err != nil || !(strings.HasPrefix(sid.String(), "S-1-5-21-") || strings.HasPrefix(sid.String(), "S-1-12-1-")) || !strings.EqualFold(filepath.Clean(path), WindowsHostManagerBindingPath(binding.VMID)) { |
| 129 | return binding, errors.New("binding_invalid") |
| 130 | } |
| 131 | if err = managerProtected(path, binding.HostSID); err != nil { |
| 132 | return binding, err |
| 133 | } |
| 134 | if err = managerProtected(filepath.Dir(path), binding.HostSID); err != nil { |
| 135 | return binding, err |
| 136 | } |
| 137 | if err = managerSharedProtected(filepath.Dir(filepath.Dir(path)), binding.HostSID); err != nil { |
| 138 | return binding, err |
| 139 | } |
| 140 | if err = managerSharedProtected(filepath.Dir(filepath.Dir(filepath.Dir(path))), binding.HostSID); err != nil { |
| 141 | return binding, err |
| 142 | } |
| 143 | return binding, nil |
| 144 | } |
| 145 | |
| 146 | func managerDiskIdentity(path string) (uint32, uint64, error) { |
| 147 | name, err := windows.UTF16PtrFromString(path) |
| 148 | if err != nil { |
| 149 | return 0, 0, errors.New("vm_changed") |
| 150 | } |
| 151 | handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) |
| 152 | if err != nil { |
| 153 | return 0, 0, errors.New("vm_changed") |
| 154 | } |
| 155 | defer windows.CloseHandle(handle) |
| 156 | var info windows.ByHandleFileInformation |
| 157 | if windows.GetFileInformationByHandle(handle, &info) != nil || info.FileAttributes&(windows.FILE_ATTRIBUTE_DIRECTORY|windows.FILE_ATTRIBUTE_REPARSE_POINT) != 0 { |
| 158 | return 0, 0, errors.New("vm_changed") |
| 159 | } |
| 160 | return info.VolumeSerialNumber, uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil |
| 161 | } |
| 162 | |
| 163 | func managerVMDisk(ctx context.Context, id uuid.UUID) (string, error) { |
| 164 | script := fmt.Sprintf("$ErrorActionPreference='Stop';$v=Get-VM -Id ([guid]'%s');$d=@(Get-VMHardDiskDrive -VM $v);if($d.Count -ne 1){throw 'bound_disk_invalid'};[pscustomobject]@{path=$d[0].Path}|ConvertTo-Json -Compress", id.String()) |
| 165 | cmd, err := systemPowerShellQuery(ctx, script) |
| 166 | if err != nil { |
| 167 | return "", errors.New("vm_changed") |
| 168 | } |
| 169 | data, err := cmd.Output() |
| 170 | if err != nil || len(data) > 16384 { |
| 171 | return "", errors.New("vm_changed") |
| 172 | } |
| 173 | var disk struct { |
| 174 | Path string `json:"path"` |
| 175 | } |
| 176 | if json.Unmarshal(data, &disk) != nil { |
| 177 | return "", errors.New("vm_changed") |
| 178 | } |
| 179 | return disk.Path, nil |
| 180 | } |
| 181 | |
| 182 | func managerValidateVM(ctx context.Context, binding WindowsHostManagerBinding) (HyperVInspection, error) { |
| 183 | state, err := inspectHyperVNative(ctx, binding.VMID) |
| 184 | if err != nil || state.Lookup != "found" || state.VM == nil || state.VM.Generation != 2 || !state.VM.SecureBoot || !state.VM.VirtualTPM || state.VM.NetworkAdapterCount != 0 || state.VM.DiskCount != 1 || state.VM.SingleLocalVHDX == nil || !*state.VM.SingleLocalVHDX { |
| 185 | return state, errors.New("vm_changed") |
| 186 | } |
| 187 | disk, err := managerVMDisk(ctx, binding.VMID) |
| 188 | if err != nil { |
| 189 | return state, err |
| 190 | } |
| 191 | real, err := paths.Resolve(disk) |
| 192 | if err != nil || !strings.EqualFold(real, binding.DiskPath) { |
| 193 | return state, errors.New("vm_changed") |
| 194 | } |
| 195 | volume, id, err := managerDiskIdentity(real) |
| 196 | if err != nil || volume != binding.DiskVolume || id != binding.DiskFileID { |
| 197 | return state, errors.New("vm_changed") |
| 198 | } |
| 199 | return state, nil |
| 200 | } |
| 201 | |
| 202 | func PrepareWindowsHostManagerBinding(ctx context.Context, id uuid.UUID, hostSID string) (WindowsHostManagerBinding, error) { |
| 203 | var binding WindowsHostManagerBinding |
| 204 | token := windows.GetCurrentProcessToken() |
| 205 | host, err := windows.StringToSid(hostSID) |
| 206 | if err != nil || !token.IsElevated() || !(strings.HasPrefix(host.String(), "S-1-5-21-") || strings.HasPrefix(host.String(), "S-1-12-1-")) { |
| 207 | return binding, errors.New("installation_requires_administrator") |
| 208 | } |
| 209 | state, err := inspectHyperVNative(ctx, id) |
| 210 | if err != nil || state.Lookup != "found" || state.VM == nil || state.VM.Generation != 2 || !state.VM.SecureBoot || !state.VM.VirtualTPM || state.VM.NetworkAdapterCount != 0 || state.VM.DiskCount != 1 { |
| 211 | return binding, errors.New("vm_changed") |
| 212 | } |
| 213 | disk, err := managerVMDisk(ctx, id) |
| 214 | if err != nil { |
| 215 | return binding, err |
| 216 | } |
| 217 | real, err := paths.Resolve(disk) |
| 218 | if err != nil || strings.HasPrefix(real, `\\`) || !strings.EqualFold(filepath.Ext(real), ".vhdx") { |
| 219 | return binding, errors.New("vm_changed") |
| 220 | } |
| 221 | volume, fileID, err := managerDiskIdentity(real) |
| 222 | if err != nil { |
| 223 | return binding, err |
| 224 | } |
| 225 | return WindowsHostManagerBinding{Version: windowsHostManagerVersion, VMID: id, HostSID: hostSID, DiskPath: real, DiskVolume: volume, DiskFileID: fileID}, nil |
| 226 | } |
| 227 | |
| 228 | func managerClientSID(conn net.Conn) (string, error) { |
| 229 | file, ok := conn.(interface{ Fd() uintptr }) |
| 230 | if !ok { |
| 231 | return "", errors.New("unauthorized") |
| 232 | } |
| 233 | var pid uint32 |
| 234 | if windows.GetNamedPipeClientProcessId(windows.Handle(file.Fd()), &pid) != nil || pid == 0 { |
| 235 | return "", errors.New("unauthorized") |
| 236 | } |
| 237 | process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) |
| 238 | if err != nil { |
| 239 | return "", errors.New("unauthorized") |
| 240 | } |
| 241 | defer windows.CloseHandle(process) |
| 242 | var token windows.Token |
| 243 | if windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token) != nil { |
| 244 | return "", errors.New("unauthorized") |
| 245 | } |
| 246 | defer token.Close() |
| 247 | user, err := token.GetTokenUser() |
| 248 | if err != nil { |
| 249 | return "", errors.New("unauthorized") |
| 250 | } |
| 251 | return user.User.Sid.String(), nil |
| 252 | } |
| 253 | |
| 254 | type windowsHostManagerServer struct { |
| 255 | binding WindowsHostManagerBinding |
| 256 | mutate sync.RWMutex |
| 257 | } |
| 258 | |
| 259 | func managerHostMemoryGiB() int { |
| 260 | var memory struct { |
| 261 | Length, Load uint32 |
| 262 | TotalPhysical, AvailablePhysical, TotalPage, AvailablePage, TotalVirtual, AvailableVirtual, AvailableExtended uint64 |
| 263 | } |
| 264 | memory.Length = uint32(unsafe.Sizeof(memory)) |
| 265 | result, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx").Call(uintptr(unsafe.Pointer(&memory))) |
| 266 | if result == 0 { |
| 267 | return 0 |
| 268 | } |
| 269 | return int(memory.TotalPhysical >> 30) |
| 270 | } |
| 271 | |
| 272 | func (server *windowsHostManagerServer) request(ctx context.Context, request windowsHostManagerRequest, conn net.Conn) (any, error) { |
| 273 | if request.validate() != nil || request.VMID != server.binding.VMID { |
| 274 | return nil, errors.New("invalid_request") |
| 275 | } |
| 276 | if request.Operation == "storage" || request.Operation == "start" || request.Operation == "shutdown" || request.Operation == "resources" && request.CPUs != 0 { |
| 277 | server.mutate.Lock() |
| 278 | defer server.mutate.Unlock() |
| 279 | } else { |
| 280 | server.mutate.RLock() |
| 281 | defer server.mutate.RUnlock() |
| 282 | } |
| 283 | journal, err := server.loadStorageJournal() |
| 284 | if err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | if request.Storage != nil { |
| 288 | return server.storageRequest(ctx, *request.Storage, journal, conn) |
| 289 | } |
| 290 | if journal != nil && journal.Phase == "pending" { |
| 291 | return nil, errors.New("storage_pending") |
| 292 | } |
| 293 | state, err := managerValidateVM(ctx, server.binding) |
| 294 | if err != nil { |
| 295 | return nil, err |
| 296 | } |
| 297 | name, err := windows.UTF16PtrFromString(server.binding.DiskPath) |
| 298 | if err != nil { |
| 299 | return nil, errors.New("vm_changed") |
| 300 | } |
| 301 | |
| 302 | |
| 303 | lockedDisk, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) |
| 304 | if err != nil { |
| 305 | return nil, errors.New("vm_changed") |
| 306 | } |
| 307 | defer windows.CloseHandle(lockedDisk) |
| 308 | var pinned windows.ByHandleFileInformation |
| 309 | if windows.GetFileInformationByHandle(lockedDisk, &pinned) != nil || pinned.VolumeSerialNumber != server.binding.DiskVolume || uint64(pinned.FileIndexHigh)<<32|uint64(pinned.FileIndexLow) != server.binding.DiskFileID { |
| 310 | return nil, errors.New("vm_changed") |
| 311 | } |
| 312 | switch request.Operation { |
| 313 | case "inspect": |
| 314 | return state, nil |
| 315 | case "resources": |
| 316 | if request.CPUs != 0 { |
| 317 | maxMemory, maxCPUs := WindowsVMResourceCeiling(managerHostMemoryGiB(), runtime.NumCPU()) |
| 318 | if request.CPUs > maxCPUs || request.MemoryGiB > maxMemory { |
| 319 | return nil, errors.New("resources_out_of_bounds") |
| 320 | } |
| 321 | } |
| 322 | return windowsVMResourcesNative(ctx, server.binding.VMID, request.MemoryGiB, request.CPUs) |
| 323 | case "start", "shutdown": |
| 324 | action := "start" |
| 325 | if request.Operation == "shutdown" { |
| 326 | action = "stop" |
| 327 | } |
| 328 | if err := windowsVMActionNative(ctx, server.binding.VMID, action); err != nil { |
| 329 | return nil, errors.New("operation_failed") |
| 330 | } |
| 331 | if _, err = managerValidateVM(ctx, server.binding); err != nil { |
| 332 | return nil, err |
| 333 | } |
| 334 | return windowsVMResourcesNative(ctx, server.binding.VMID, 0, 0) |
| 335 | } |
| 336 | return nil, errors.New("invalid_operation") |
| 337 | } |
| 338 | |
| 339 | func (server *windowsHostManagerServer) connection(ctx context.Context, conn net.Conn) { |
| 340 | defer conn.Close() |
| 341 | response := windowsHostManagerResponse{Version: windowsHostManagerVersion, VMID: server.binding.VMID} |
| 342 | write := func() { |
| 343 | conn.SetWriteDeadline(time.Now().Add(10 * time.Second)) |
| 344 | _ = json.NewEncoder(conn).Encode(response) |
| 345 | } |
| 346 | sid, err := managerClientSID(conn) |
| 347 | if err != nil || sid != server.binding.HostSID { |
| 348 | response.Error = "unauthorized" |
| 349 | write() |
| 350 | return |
| 351 | } |
| 352 | conn.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 353 | reader := bufio.NewReaderSize(conn, windowsHostManagerWireLimit+1) |
| 354 | line, err := reader.ReadSlice('\n') |
| 355 | if err != nil || len(line) > windowsHostManagerWireLimit || reader.Buffered() != 0 { |
| 356 | response.Error = "invalid_request" |
| 357 | write() |
| 358 | return |
| 359 | } |
| 360 | var request windowsHostManagerRequest |
| 361 | decoder := json.NewDecoder(bytes.NewReader(line)) |
| 362 | decoder.DisallowUnknownFields() |
| 363 | if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF { |
| 364 | response.Error = "invalid_request" |
| 365 | write() |
| 366 | return |
| 367 | } |
| 368 | conn.SetReadDeadline(time.Time{}) |
| 369 | deadline := time.Minute |
| 370 | if request.Storage != nil { |
| 371 | deadline = 3 * time.Minute |
| 372 | } |
| 373 | operation, cancel := context.WithTimeout(ctx, deadline) |
| 374 | defer cancel() |
| 375 | |
| 376 | disconnected := make(chan struct{}) |
| 377 | go func() { defer close(disconnected); var extra [1]byte; _, _ = conn.Read(extra[:]); cancel() }() |
| 378 | result, err := server.request(operation, request, conn) |
| 379 | if err != nil { |
| 380 | response.Error = "operation_failed" |
| 381 | for _, code := range []string{"invalid_request", "invalid_operation", "vm_changed", "resources_out_of_bounds", "storage_pending", "vm_running"} { |
| 382 | if err.Error() == code { |
| 383 | response.Error = code |
| 384 | } |
| 385 | } |
| 386 | if operation.Err() != nil { |
| 387 | response.Error = "cancelled" |
| 388 | } |
| 389 | } else { |
| 390 | response.Result, err = json.Marshal(result) |
| 391 | response.OK = err == nil |
| 392 | if err != nil { |
| 393 | response.Error = "operation_failed" |
| 394 | } |
| 395 | } |
| 396 | write() |
| 397 | conn.Close() |
| 398 | <-disconnected |
| 399 | } |
| 400 | |
| 401 | func ServeWindowsHostManager(parent context.Context, path string) error { |
| 402 | return serveWindowsHostManager(parent, path, nil) |
| 403 | } |
| 404 | |
| 405 | func serveWindowsHostManager(parent context.Context, path string, ready chan<- struct{}) error { |
| 406 | ctx, cancel := context.WithCancel(parent) |
| 407 | defer cancel() |
| 408 | user, err := windows.GetCurrentProcessToken().GetTokenUser() |
| 409 | if err != nil || !user.User.Sid.IsWellKnown(windows.WinLocalSystemSid) { |
| 410 | return errors.New("service_requires_system") |
| 411 | } |
| 412 | binding, err := LoadWindowsHostManagerBinding(path) |
| 413 | if err != nil { |
| 414 | return err |
| 415 | } |
| 416 | exe, err := os.Executable() |
| 417 | if err != nil || !strings.EqualFold(exe, WindowsHostManagerExecutablePath(binding.VMID)) { |
| 418 | return errors.New("binding_invalid") |
| 419 | } |
| 420 | if err = managerProtected(exe, binding.HostSID); err != nil { |
| 421 | return err |
| 422 | } |
| 423 | if err = managerProtected(filepath.Dir(exe), binding.HostSID); err != nil { |
| 424 | return err |
| 425 | } |
| 426 | if err = managerSharedProtected(filepath.Dir(filepath.Dir(exe)), binding.HostSID); err != nil { |
| 427 | return err |
| 428 | } |
| 429 | server := windowsHostManagerServer{binding: binding} |
| 430 | listener, err := winio.ListenPipe(`\\.\pipe\Cage.HyperV.`+binding.VMID.String(), &winio.PipeConfig{SecurityDescriptor: "O:SYG:SYD:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12019b;;;" + binding.HostSID + ")", InputBufferSize: windowsHostManagerWireLimit, OutputBufferSize: windowsHostManagerWireLimit}) |
| 431 | if err != nil { |
| 432 | return errors.New("service_pipe_unavailable") |
| 433 | } |
| 434 | defer listener.Close() |
| 435 | if ready != nil { |
| 436 | close(ready) |
| 437 | } |
| 438 | var active sync.WaitGroup |
| 439 | var connections sync.Map |
| 440 | go func() { |
| 441 | <-ctx.Done() |
| 442 | listener.Close() |
| 443 | connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) |
| 444 | }() |
| 445 | slots := make(chan struct{}, 16) |
| 446 | defer func() { |
| 447 | cancel() |
| 448 | listener.Close() |
| 449 | connections.Range(func(key, _ any) bool { key.(net.Conn).Close(); return true }) |
| 450 | active.Wait() |
| 451 | }() |
| 452 | for { |
| 453 | conn, err := listener.Accept() |
| 454 | if err != nil { |
| 455 | if ctx.Err() != nil { |
| 456 | return nil |
| 457 | } |
| 458 | return errors.New("service_pipe_unavailable") |
| 459 | } |
| 460 | select { |
| 461 | case slots <- struct{}{}: |
| 462 | default: |
| 463 | conn.Close() |
| 464 | continue |
| 465 | } |
| 466 | connections.Store(conn, struct{}{}) |
| 467 | active.Add(1) |
| 468 | go func() { |
| 469 | defer active.Done() |
| 470 | defer func() { <-slots; connections.Delete(conn) }() |
| 471 | server.connection(ctx, conn) |
| 472 | }() |
| 473 | } |
| 474 | } |