| @@ -0,0 +1,456 @@ |
| 1 | + | // Package control serves the v1 JSON-lines control protocol on a Unix socket. |
| 2 | + | package control |
| 3 | + | |
| 4 | + | import ( |
| 5 | + | "bufio" |
| 6 | + | "context" |
| 7 | + | "encoding/json" |
| 8 | + | "errors" |
| 9 | + | "fmt" |
| 10 | + | "net" |
| 11 | + | "os" |
| 12 | + | "path/filepath" |
| 13 | + | "sync" |
| 14 | + | "syscall" |
| 15 | + | "time" |
| 16 | + | |
| 17 | + | "github.com/bnema/neferwl/internal/adapters/logging" |
| 18 | + | "github.com/bnema/neferwl/internal/adapters/statewire" |
| 19 | + | "github.com/bnema/neferwl/internal/adapters/workspaceid" |
| 20 | + | "github.com/bnema/neferwl/internal/adapters/xkb" |
| 21 | + | "github.com/bnema/neferwl/internal/domain" |
| 22 | + | "github.com/bnema/neferwl/internal/ports" |
| 23 | + | "golang.org/x/sys/unix" |
| 24 | + | ) |
| 25 | + | |
| 26 | + | // Server owns a control listener. Requests on each connection are processed in |
| 27 | + | // order: the next line is read only after the preceding core reply is sent. |
| 28 | + | // Options supplies a dedicated control keymap, never the physical input map. |
| 29 | + | // Listen takes ownership of Keymap on success. The server takes ownership of |
| 30 | + | // each map it receives from Keymaps; producers own any maps left in the channel |
| 31 | + | // after shutdown. Security is sampled before every translated event. |
| 32 | + | type Options struct { |
| 33 | + | FramesDir string |
| 34 | + | Shooter *Shooter |
| 35 | + | Keymap *xkb.Keymap |
| 36 | + | Keymaps <-chan *xkb.Keymap |
| 37 | + | Security ports.SessionSecurity |
| 38 | + | } |
| 39 | + | |
| 40 | + | type Server struct { |
| 41 | + | framesDir string |
| 42 | + | shooter *Shooter |
| 43 | + | injectMu sync.Mutex |
| 44 | + | injector *injector |
| 45 | + | keymaps <-chan *xkb.Keymap |
| 46 | + | listener *net.UnixListener |
| 47 | + | ids *workspaceid.IDs |
| 48 | + | done chan struct{} |
| 49 | + | once sync.Once |
| 50 | + | err error |
| 51 | + | } |
| 52 | + | |
| 53 | + | // Listen creates a private socket using the same workspace IDs as statefile. |
| 54 | + | // An existing socket is removed only when connecting proves it has no listener. |
| 55 | + | func Listen(path string, ids *workspaceid.IDs, opts Options) (*Server, error) { |
| 56 | + | if ids == nil { |
| 57 | + | return nil, errors.New("workspace IDs are required") |
| 58 | + | } |
| 59 | + | if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| 60 | + | return nil, err |
| 61 | + | } |
| 62 | + | if info, err := os.Lstat(path); err == nil { |
| 63 | + | if info.Mode()&os.ModeSocket == 0 { |
| 64 | + | return nil, fmt.Errorf("control path is not a socket: %s", path) |
| 65 | + | } |
| 66 | + | conn, err := net.DialTimeout("unix", path, time.Second) |
| 67 | + | if err == nil { |
| 68 | + | conn.Close() |
| 69 | + | return nil, fmt.Errorf("control socket already listening: %s", path) |
| 70 | + | } |
| 71 | + | if !errors.Is(err, syscall.ECONNREFUSED) { |
| 72 | + | return nil, err |
| 73 | + | } |
| 74 | + | if err := os.Remove(path); err != nil { |
| 75 | + | return nil, err |
| 76 | + | } |
| 77 | + | } else if !errors.Is(err, os.ErrNotExist) { |
| 78 | + | return nil, err |
| 79 | + | } |
| 80 | + | listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) |
| 81 | + | if err != nil { |
| 82 | + | return nil, err |
| 83 | + | } |
| 84 | + | if err := os.Chmod(path, 0o600); err != nil { |
| 85 | + | listener.Close() |
| 86 | + | return nil, err |
| 87 | + | } |
| 88 | + | s := &Server{listener: listener, ids: ids, done: make(chan struct{})} |
| 89 | + | s.framesDir = opts.FramesDir |
| 90 | + | s.shooter = opts.Shooter |
| 91 | + | s.keymaps = opts.Keymaps |
| 92 | + | if opts.Keymap != nil { |
| 93 | + | s.injector = newInjector(opts.Keymap, opts.Security) |
| 94 | + | } |
| 95 | + | return s, nil |
| 96 | + | } |
| 97 | + | |
| 98 | + | // Close stops acceptance and all active connections. It is safe to call twice. |
| 99 | + | func (s *Server) Close() error { |
| 100 | + | s.once.Do(func() { |
| 101 | + | close(s.done) |
| 102 | + | s.err = s.listener.Close() |
| 103 | + | s.injectMu.Lock() |
| 104 | + | defer s.injectMu.Unlock() |
| 105 | + | if s.injector != nil { |
| 106 | + | s.injector.km.Close() |
| 107 | + | s.injector = nil |
| 108 | + | } |
| 109 | + | }) |
| 110 | + | return s.err |
| 111 | + | } |
| 112 | + | |
| 113 | + | // Run accepts connections until cancellation or Close, waiting for handlers to exit. |
| 114 | + | func (s *Server) Run(ctx context.Context, out chan<- ports.ControlRequest) error { |
| 115 | + | ctx, cancel := context.WithCancel(ctx) |
| 116 | + | stop := context.AfterFunc(ctx, func() { _ = s.Close() }) |
| 117 | + | defer stop() |
| 118 | + | var workers sync.WaitGroup |
| 119 | + | defer workers.Wait() |
| 120 | + | defer cancel() |
| 121 | + | log := logging.For(ctx, "control") |
| 122 | + | log.Info().Str("path", s.listener.Addr().String()).Msg("listening") |
| 123 | + | for { |
| 124 | + | conn, err := s.listener.AcceptUnix() |
| 125 | + | if err != nil { |
| 126 | + | if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { |
| 127 | + | return nil |
| 128 | + | } |
| 129 | + | return err |
| 130 | + | } |
| 131 | + | workers.Add(1) |
| 132 | + | go func() { |
| 133 | + | defer workers.Done() |
| 134 | + | defer conn.Close() |
| 135 | + | connCtx, cancel := context.WithCancel(ctx) |
| 136 | + | defer cancel() |
| 137 | + | go func() { |
| 138 | + | select { |
| 139 | + | case <-s.done: |
| 140 | + | cancel() |
| 141 | + | case <-connCtx.Done(): |
| 142 | + | } |
| 143 | + | }() |
| 144 | + | stop := context.AfterFunc(connCtx, func() { _ = conn.Close() }) |
| 145 | + | defer stop() |
| 146 | + | if !sameUID(conn) { |
| 147 | + | log.Warn().Msg("peer rejected") |
| 148 | + | return |
| 149 | + | } |
| 150 | + | s.serve(connCtx, conn, out) |
| 151 | + | }() |
| 152 | + | } |
| 153 | + | } |
| 154 | + | |
| 155 | + | func sameUID(conn *net.UnixConn) bool { |
| 156 | + | raw, err := conn.SyscallConn() |
| 157 | + | if err != nil { |
| 158 | + | return false |
| 159 | + | } |
| 160 | + | var cred *unix.Ucred |
| 161 | + | var credErr error |
| 162 | + | if err := raw.Control(func(fd uintptr) { cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) }); err != nil { |
| 163 | + | return false |
| 164 | + | } |
| 165 | + | return credErr == nil && cred != nil && cred.Uid == uint32(os.Getuid()) |
| 166 | + | } |
| 167 | + | |
| 168 | + | type request struct { |
| 169 | + | EveryFrame bool `json:"every_frame"` |
| 170 | + | Stop bool `json:"stop"` |
| 171 | + | Name string `json:"name"` |
| 172 | + | Mode string `json:"mode"` |
| 173 | + | Outputs []string `json:"outputs"` |
| 174 | + | Inline bool `json:"inline"` |
| 175 | + | Raw bool `json:"raw"` |
| 176 | + | Shot json.RawMessage `json:"shot"` |
| 177 | + | ID json.RawMessage `json:"id"` |
| 178 | + | Op string `json:"op"` |
| 179 | + | Action string `json:"action"` |
| 180 | + | What string `json:"what"` |
| 181 | + | Wait *string `json:"wait"` |
| 182 | + | Until *string `json:"until"` |
| 183 | + | Timeout *string `json:"timeout"` |
| 184 | + | Kind string `json:"kind"` |
| 185 | + | Combo string `json:"combo"` |
| 186 | + | Text string `json:"text"` |
| 187 | + | Cmd string `json:"cmd"` |
| 188 | + | Args []string `json:"args"` |
| 189 | + | Fingers int `json:"fingers"` |
| 190 | + | Dir string `json:"dir"` |
| 191 | + | } |
| 192 | + | |
| 193 | + | type reply struct { |
| 194 | + | Dir string `json:"dir,omitempty"` |
| 195 | + | Shots []Shot `json:"shots,omitempty"` |
| 196 | + | Detail string `json:"detail,omitempty"` |
| 197 | + | ID json.RawMessage `json:"id"` |
| 198 | + | OK bool `json:"ok"` |
| 199 | + | Done string `json:"done"` |
| 200 | + | Diff diff `json:"diff"` |
| 201 | + | State statewire.State `json:"state"` |
| 202 | + | Late []domain.WindowID `json:"late"` |
| 203 | + | Error string `json:"error,omitempty"` |
| 204 | + | } |
| 205 | + | |
| 206 | + | type command struct { |
| 207 | + | Name string `json:"name"` |
| 208 | + | Arg string `json:"arg"` |
| 209 | + | Kind string `json:"kind"` |
| 210 | + | Caps []string `json:"caps"` |
| 211 | + | Summary string `json:"summary"` |
| 212 | + | } |
| 213 | + | |
| 214 | + | func capNames(c domain.Caps) []string { |
| 215 | + | names := []string{} |
| 216 | + | for _, item := range []struct { |
| 217 | + | bit domain.Caps |
| 218 | + | name string |
| 219 | + | }{{domain.CapRead, "read"}, {domain.CapAct, "act"}, {domain.CapInput, "input"}, {domain.CapCapture, "capture"}, {domain.CapAdmin, "admin"}} { |
| 220 | + | if c&item.bit != 0 { |
| 221 | + | names = append(names, item.name) |
| 222 | + | } |
| 223 | + | } |
| 224 | + | return names |
| 225 | + | } |
| 226 | + | |
| 227 | + | var nullID = json.RawMessage("null") |
| 228 | + | |
| 229 | + | // maxRequestTimeout caps the client-supplied timeout: core and the shooter |
| 230 | + | // hold a request at most this long. |
| 231 | + | const maxRequestTimeout = domain.MaxControlTimeout |
| 232 | + | |
| 233 | + | func (s *Server) serve(ctx context.Context, conn *net.UnixConn, out chan<- ports.ControlRequest) { |
| 234 | + | scanner := bufio.NewScanner(conn) |
| 235 | + | scanner.Buffer(make([]byte, 4096), 1024*1024) |
| 236 | + | encoder := json.NewEncoder(conn) |
| 237 | + | announced := false |
| 238 | + | for scanner.Scan() { |
| 239 | + | var req request |
| 240 | + | if err := json.Unmarshal(scanner.Bytes(), &req); err != nil { |
| 241 | + | if encoder.Encode(reply{ID: nullID, Error: ports.ControlErrBadRequest}) != nil { |
| 242 | + | return |
| 243 | + | } |
| 244 | + | continue |
| 245 | + | } |
| 246 | + | // The id is optional: a request without one gets "id": null back. |
| 247 | + | if len(req.ID) == 0 { |
| 248 | + | req.ID = nullID |
| 249 | + | } |
| 250 | + | if req.Op == "hello" { |
| 251 | + | commands := []command{} |
| 252 | + | for _, spec := range domain.Commands() { |
| 253 | + | commands = append(commands, command{spec.Name, spec.Arg, spec.Kind.String(), capNames(spec.Caps), spec.Summary}) |
| 254 | + | } |
| 255 | + | if encoder.Encode(struct { |
| 256 | + | ID json.RawMessage `json:"id"` |
| 257 | + | OK bool `json:"ok"` |
| 258 | + | V int `json:"v"` |
| 259 | + | Caps []string `json:"caps"` |
| 260 | + | Commands []command `json:"commands"` |
| 261 | + | }{req.ID, true, 1, capNames(domain.CapsAll), commands}) != nil { |
| 262 | + | return |
| 263 | + | } |
| 264 | + | continue |
| 265 | + | } |
| 266 | + | response := s.dispatch(ctx, req, out, &announced) |
| 267 | + | if ctx.Err() != nil { |
| 268 | + | return |
| 269 | + | } |
| 270 | + | if encoder.Encode(response) != nil { |
| 271 | + | return |
| 272 | + | } |
| 273 | + | } |
| 274 | + | } |
| 275 | + | |
| 276 | + | func (s *Server) dispatch(ctx context.Context, req request, out chan<- ports.ControlRequest, announced *bool) reply { |
| 277 | + | // The request deadline covers the core wait and the capture together. |
| 278 | + | start := time.Now() |
| 279 | + | response := reply{ID: req.ID, Error: ports.ControlErrBadRequest} |
| 280 | + | if req.Op == "shot" && (req.EveryFrame || req.Stop) { |
| 281 | + | return s.continuousCapture(ctx, req, out) |
| 282 | + | } |
| 283 | + | ch := make(chan ports.ControlReply, 1) |
| 284 | + | var message ports.ControlRequest |
| 285 | + | timeout := domain.DefaultControlTimeout |
| 286 | + | switch req.Op { |
| 287 | + | case "output-add", "output-rm": |
| 288 | + | mode := domain.OutputMode{} |
| 289 | + | if req.Op == "output-add" { |
| 290 | + | var err error |
| 291 | + | mode, err = domain.ParseOutputMode(req.Mode) |
| 292 | + | if err != nil { |
| 293 | + | return response |
| 294 | + | } |
| 295 | + | } else if req.Name == "" { |
| 296 | + | return response |
| 297 | + | } |
| 298 | + | message = ports.ControlOutput{Name: req.Name, Mode: mode, Remove: req.Op == "output-rm", Caps: domain.CapsAll, Reply: ch} |
| 299 | + | |
| 300 | + | case "do", "inject", "shot": |
| 301 | + | shots, err := requestShots(req) |
| 302 | + | if err != nil { |
| 303 | + | response.Detail = err.Error() |
| 304 | + | return response |
| 305 | + | } |
| 306 | + | if len(shots) > 0 && s.shooter == nil { |
| 307 | + | response.Detail = "capture unavailable" |
| 308 | + | return response |
| 309 | + | } |
| 310 | + | wait := domain.DefaultWait |
| 311 | + | if req.Wait != nil { |
| 312 | + | var err error |
| 313 | + | wait, err = domain.ParseWaitLevel(*req.Wait) |
| 314 | + | if err != nil { |
| 315 | + | return response |
| 316 | + | } |
| 317 | + | } |
| 318 | + | var until *domain.Until |
| 319 | + | if req.Until != nil { |
| 320 | + | parsed, err := domain.ParseUntil(*req.Until) |
| 321 | + | if err != nil { |
| 322 | + | return response |
| 323 | + | } |
| 324 | + | until = &parsed |
| 325 | + | } |
| 326 | + | if req.Timeout != nil { |
| 327 | + | var err error |
| 328 | + | timeout, err = time.ParseDuration(*req.Timeout) |
| 329 | + | if err != nil || timeout <= 0 { |
| 330 | + | return response |
| 331 | + | } |
| 332 | + | if timeout > maxRequestTimeout { |
| 333 | + | response.Detail = "timeout exceeds 5m" |
| 334 | + | return response |
| 335 | + | } |
| 336 | + | } |
| 337 | + | if len(shots) > 0 { |
| 338 | + | wait = domain.WaitPresented |
| 339 | + | } |
| 340 | + | if req.Op == "inject" { |
| 341 | + | events, err := s.translate(req, !*announced) |
| 342 | + | if err != nil { |
| 343 | + | return response |
| 344 | + | } |
| 345 | + | message = ports.ControlInject{Shots: shots, Events: events, Wait: wait, Until: until, Timeout: timeout, Caps: domain.CapsAll, Reply: ch} |
| 346 | + | } else { |
| 347 | + | if req.Op == "shot" { |
| 348 | + | req.Action = "none" |
| 349 | + | } |
| 350 | + | if req.Action == "" { |
| 351 | + | return response |
| 352 | + | } |
| 353 | + | message = ports.ControlDo{Shots: shots, Action: req.Action, Wait: wait, Until: until, Timeout: timeout, Caps: domain.CapsAll, Reply: ch} |
| 354 | + | } |
| 355 | + | case "query": |
| 356 | + | if req.What == "" { |
| 357 | + | return response |
| 358 | + | } |
| 359 | + | message = ports.ControlQuery{What: req.What, Caps: domain.CapsAll, Reply: ch} |
| 360 | + | default: |
| 361 | + | return response |
| 362 | + | } |
| 363 | + | select { |
| 364 | + | case out <- message: |
| 365 | + | case <-ctx.Done(): |
| 366 | + | return response |
| 367 | + | } |
| 368 | + | var result ports.ControlReply |
| 369 | + | select { |
| 370 | + | case result = <-ch: |
| 371 | + | case <-ctx.Done(): |
| 372 | + | return response |
| 373 | + | } |
| 374 | + | // The device announcement went through only if core ran the batch. |
| 375 | + | code := result.Err |
| 376 | + | if _, inject := message.(ports.ControlInject); inject && (code == "" || code == ports.ControlErrTimeout) { |
| 377 | + | *announced = true |
| 378 | + | } |
| 379 | + | response = reply{ID: req.ID, OK: code == "", Done: result.Done.String(), Diff: wireDiff(result.Diff), State: statewire.FromDomain(result.State, s.ids), Late: result.Late, Error: code} |
| 380 | + | if len(result.Shots) > 0 { |
| 381 | + | if s.shooter == nil { |
| 382 | + | response.OK = false |
| 383 | + | response.Error = ports.ControlErrBadRequest |
| 384 | + | response.Detail = "capture unavailable" |
| 385 | + | return response |
| 386 | + | } |
| 387 | + | // The capture gets what the core wait left of the request deadline. |
| 388 | + | shotCtx, cancel := context.WithDeadline(ctx, start.Add(timeout)) |
| 389 | + | shots, err := s.shooter.Shoot(shotCtx, result.Shots, req.Inline) |
| 390 | + | cancel() |
| 391 | + | response.Shots = shots |
| 392 | + | if err != nil { |
| 393 | + | response.OK = false |
| 394 | + | response.Error = ports.ControlErrCaptureFailed |
| 395 | + | response.Detail = err.Error() |
| 396 | + | } |
| 397 | + | } |
| 398 | + | return response |
| 399 | + | } |
| 400 | + | |
| 401 | + | func requestShots(req request) ([]domain.ShotRequest, error) { |
| 402 | + | var outputs []string |
| 403 | + | if req.Op == "shot" { |
| 404 | + | if req.Raw { |
| 405 | + | return nil, errors.New("raw shots need --every-frame") |
| 406 | + | } |
| 407 | + | outputs = req.Outputs |
| 408 | + | if len(outputs) == 0 { |
| 409 | + | outputs = []string{""} |
| 410 | + | } |
| 411 | + | } else if len(req.Shot) > 0 { |
| 412 | + | var enabled bool |
| 413 | + | if err := json.Unmarshal(req.Shot, &enabled); err == nil { |
| 414 | + | if !enabled { |
| 415 | + | return nil, nil |
| 416 | + | } |
| 417 | + | outputs = []string{""} |
| 418 | + | } else { |
| 419 | + | if err := json.Unmarshal(req.Shot, &outputs); err != nil || outputs == nil { |
| 420 | + | return nil, errors.New("shot must be true, false or an output list") |
| 421 | + | } |
| 422 | + | } |
| 423 | + | } |
| 424 | + | shots := make([]domain.ShotRequest, 0, len(outputs)) |
| 425 | + | for _, output := range outputs { |
| 426 | + | shots = append(shots, domain.ShotRequest{Output: output}) |
| 427 | + | } |
| 428 | + | return shots, nil |
| 429 | + | } |
| 430 | + | |
| 431 | + | // continuousCapture forwards an every-frame start or stop to core, which |
| 432 | + | // decides it; the default directory is the session's frames directory. |
| 433 | + | func (s *Server) continuousCapture(ctx context.Context, req request, out chan<- ports.ControlRequest) reply { |
| 434 | + | response := reply{ID: req.ID, Error: ports.ControlErrBadRequest} |
| 435 | + | if (req.EveryFrame && req.Stop) || req.Inline { |
| 436 | + | return response |
| 437 | + | } |
| 438 | + | dir := req.Dir |
| 439 | + | if dir == "" { |
| 440 | + | dir = s.framesDir |
| 441 | + | } |
| 442 | + | ack := make(chan ports.ContinuousCaptureResult, 1) |
| 443 | + | select { |
| 444 | + | case out <- ports.ControlCapture{Outputs: req.Outputs, Dir: dir, Raw: req.Raw, Stop: req.Stop, Caps: domain.CapsAll, Reply: ack}: |
| 445 | + | case <-ctx.Done(): |
| 446 | + | return response |
| 447 | + | } |
| 448 | + | select { |
| 449 | + | case result := <-ack: |
| 450 | + | response.OK = result.Err == "" |
| 451 | + | response.Error = result.Err |
| 452 | + | response.Dir = result.Dir |
| 453 | + | case <-ctx.Done(): |
| 454 | + | } |
| 455 | + | return response |
| 456 | + | } |