1package wayland
2
3import (
4 "context"
5
6 "github.com/bnema/go-wayland-bindings/server/extsessionlock"
7 "github.com/bnema/go-wayland-bindings/server/wayland"
8 "github.com/bnema/neferwl/internal/ports"
9 "github.com/bnema/purego-libwayland/server"
10)
11
12// sessionLock is owned by the display goroutine. Resource destruction removes
13// its owner, never the protection gate. An ordinary new owner may take over.
14type sessionLock struct {
15 s *Server
16 res *extsessionlock.ExtSessionLockV1
17 state ports.SecurityState
18 locked bool
19 surfaces map[*output]*lockSurface
20}
21
22type sessionLockManager struct{ s *Server }
23
24// registerSessionLock is enabled only when the display and backend share
25// protection control and authoritative, non-dropping proof channels.
26func registerSessionLock(d *server.Display, s *Server) error {
27 return extsessionlock.NewExtSessionLockManagerV1Global(d, 1, func(c server.Client, version, id uint32) {
28 _, _ = extsessionlock.NewExtSessionLockManagerV1(c, int32(version), id, sessionLockManager{s})
29 })
30}
31func (sessionLockManager) Destroy(*extsessionlock.ExtSessionLockManagerV1) {}
32
33func (m sessionLockManager) Lock(r *extsessionlock.ExtSessionLockManagerV1, id uint32) {
34 s := m.s
35 l := &sessionLock{s: s, surfaces: make(map[*output]*lockSurface)}
36 res, err := extsessionlock.NewExtSessionLockV1(r.Client(), r.Version(), id, l)
37 if err != nil {
38 return
39 }
40 l.res = res
41 if s.securityController == nil || s.channels.SecurityChanges == nil || s.channels.SecurityEvents == nil || s.sessionLock != nil || len(s.securityPending) >= maxSecurityPending {
42 res.SendFinished()
43 return
44 }
45 // Engage before queueing any core event. No display-owned protocol
46 // admission can observe the old policy after this point.
47 state, err := s.securityController.Engage()
48 if err != nil {
49 res.SendFinished()
50 return
51 }
52 l.state = state
53 s.sessionLock = l
54 s.lockReadiness.Begin(state.Generation)
55 res.OnDestroy = l.orphan
56 s.resetProtectionInput()
57 s.endCaptureSessions()
58 for _, lease := range s.activeLeases {
59 lease.destroy()
60 }
61 // Preserve card tombstones until late replies are consumed/revoked, but
62 // revoke their protocol authority across both acquire and release.
63 for id, lease := range s.pendingLeases {
64 lease.finish()
65 delete(s.pendingLeases, id)
66 }
67 s.updateWorkspaceManagers(s.workspaceSnapshot)
68 s.emit(ports.SessionLockChanged{State: state})
69 s.requestBackendSecurity(state)
70 s.maybeLocked()
71}
72
73func (l *sessionLock) Destroy(r *extsessionlock.ExtSessionLockV1) {
74 if l.locked {
75 r.PostError(uint32(extsessionlock.ExtSessionLockV1ErrorInvalidDestroy), "destroy while locked")
76 }
77}
78func (l *sessionLock) UnlockAndDestroy(r *extsessionlock.ExtSessionLockV1) {
79 s := l.s
80 if !l.locked || s.sessionLock != l {
81 r.PostError(uint32(extsessionlock.ExtSessionLockV1ErrorInvalidUnlock), "unlock before protection confirmation")
82 return
83 }
84 state, err := s.securityController.Release(l.state.Generation)
85 if err != nil {
86 r.PostError(uint32(extsessionlock.ExtSessionLockV1ErrorInvalidUnlock), "protection release rejected")
87 return
88 }
89 // Clear input before any desktop focus enter; no password held keys.
90 s.resetProtectionInput()
91 s.lockReadiness.End(l.state.Generation)
92 s.sessionLock = nil
93 s.refreshToplevels()
94 s.updateWorkspaceManagers(s.workspaceSnapshot)
95 for _, surface := range l.surfaces {
96 surface.unmap()
97 }
98 s.emit(ports.SessionLockChanged{State: state})
99 s.requestBackendSecurity(state)
100}
101
102func (l *sessionLock) GetLockSurface(r *extsessionlock.ExtSessionLockV1, id uint32, wl *wayland.Surface, out *wayland.Output) {
103 s := l.s
104 if s.sessionLock != l {
105 _, _ = extsessionlock.NewExtSessionLockSurfaceV1(r.Client(), r.Version(), id, refusedLockSurface{})
106 return
107 }
108 surface, output := s.surfaceOf(wl), s.outputOf(out)
109 if surface == nil || output == nil || wl == nil || out == nil || wl.Client() != r.Client() || out.Client() != r.Client() {
110 r.PostError(uint32(extsessionlock.ExtSessionLockV1ErrorRole), "lock surface and output must belong to lock owner")
111 return
112 }
113 if _, exists := l.surfaces[output]; output != nil && exists {
114 r.PostError(uint32(extsessionlock.ExtSessionLockV1ErrorDuplicateOutput), "duplicate lock output")
115 return
116 }
117 ls, err := s.newLockSurface(r, id, surface, output, func(*lockSurface) { s.lockSurfaceChanged() })
118 if err != nil || ls == nil {
119 return
120 }
121 l.surfaces[output] = ls
122 s.lockSurfaceChanged()
123}
124
125func (l *sessionLock) orphan() {
126 s := l.s
127 if s.sessionLock != l {
128 return
129 }
130 // Never release or send finished merely because a client died.
131 s.resetProtectionInput()
132 s.sessionLock = nil
133 for _, surface := range l.surfaces {
134 surface.unmap()
135 }
136 s.emit(ports.SessionLockChanged{State: l.state})
137}
138
139func (s *Server) resetProtectionInput() {
140 s.changeFocus(0)
141 s.changePointerFocus(0, 0, 0)
142 s.deactivateText()
143 s.deactivateConstraint()
144 clear(s.seat.heldKeys)
145 clear(s.seat.grabKeys)
146 s.seat.modState = ports.ModState{}
147 s.seat.press, s.seat.pressClient = 0, server.Client{}
148 s.seat.wheelRest, s.seat.wheelHeld = [2]int32{}, [2]float64{}
149 s.cursorSurface = nil
150}
151
152// maxSecurityPending bounds takeover churn while the backend is stalled.
153// Acquire checks this bound before engaging; release retains a reserved slot.
154const maxSecurityPending = 16
155
156func (s *Server) requestBackendSecurity(state ports.SecurityState) {
157 s.securityPending = append(s.securityPending, state)
158 select {
159 case s.securityWake <- struct{}{}:
160 default:
161 }
162}
163
164// forwardBackendSecurity transfers immutable states without blocking display
165// dispatch. Queue mutation is always on the display owner, not this goroutine.
166func (s *Server) forwardBackendSecurity(ctx context.Context) {
167 for {
168 var state ports.SecurityState
169 var pending bool
170 if !s.display.Do(func() {
171 if len(s.securityPending) != 0 {
172 state, pending = s.securityPending[0], true
173 }
174 }) {
175 return
176 }
177 if !pending {
178 select {
179 case <-ctx.Done():
180 return
181 case <-s.display.Stopped():
182 return
183 case <-s.securityWake:
184 continue
185 }
186 }
187 select {
188 case <-ctx.Done():
189 return
190 case <-s.display.Stopped():
191 return
192 case s.channels.SecurityChanges <- state:
193 }
194 if !s.display.Do(func() {
195 // Only this sender pops; appending on display preserves the head.
196 if len(s.securityPending) != 0 && s.securityPending[0] == state {
197 s.securityPending[0] = ports.SecurityState{}
198 s.securityPending = s.securityPending[1:]
199 }
200 }) {
201 return
202 }
203 }
204}
205
206func (s *Server) forwardSecurityEvents(ctx context.Context) {
207 for {
208 select {
209 case <-ctx.Done():
210 return
211 case <-s.display.Stopped():
212 return
213 case event, ok := <-s.channels.SecurityEvents:
214 if !ok {
215 return
216 }
217 if !s.display.Do(func() { s.applySecurityEvent(event) }) {
218 return
219 }
220 }
221 }
222}
223
224func (s *Server) applySecurityEvent(event ports.SecurityBackendEvent) {
225 switch v := event.(type) {
226 case ports.SecurityOutputAdded:
227 s.lockReadiness.Add(v.Instance)
228 case ports.SecurityOutputRemoved:
229 s.lockReadiness.Remove(v.Instance)
230 case ports.SecurityOutputProof:
231 s.lockReadiness.Record(v.Proof)
232 case ports.SecurityOutputInvalidated:
233 s.lockReadiness.Invalidate(v.Generation, v.Instance)
234 case ports.SecurityBackendBarrier:
235 if v.Err == nil {
236 s.lockReadiness.BackendBarrier(v.Generation)
237 } else {
238 s.log.Error().Err(v.Err).Msg("session security backend barrier failed")
239 }
240 }
241 s.maybeLocked()
242}
243
244func (s *Server) lockInputTarget(id ports.WindowID) bool {
245 l := s.sessionLock
246 if l == nil || !l.locked {
247 return false
248 }
249 surface := s.lockSurfaces[id]
250 if surface == nil || !surface.mapped || surface.closed || !surface.resource.Alive() {
251 return false
252 }
253 for _, owned := range l.surfaces {
254 if surface == owned {
255 return true
256 }
257 }
258 return false
259}
260
261func (s *Server) maybeLocked() {
262 l := s.sessionLock
263 if l == nil || l.locked || !l.res.Alive() {
264 return
265 }
266 if len(s.captureInflight) == 0 {
267 s.lockReadiness.CaptureBarrier(l.state.Generation)
268 }
269 if !s.lockReadiness.Ready() {
270 return
271 }
272 l.locked = true
273 l.res.SendLocked()
274 s.lockSurfaceChanged()
275}