|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "os/signal" |
| 8 | + "runtime" |
| 9 | + "syscall" |
| 10 | + "unsafe" |
| 11 | + |
| 12 | + "github.com/djdv/go-filesystem-utils/internal/generic" |
| 13 | + "github.com/lxn/win" |
| 14 | + "golang.org/x/sys/windows" |
| 15 | +) |
| 16 | + |
| 17 | +// NOTE: On signal handling. |
| 18 | +// Go's default signal handler translates some messages |
| 19 | +// into `SIGTERM` (see [os/signal] documentation). |
| 20 | +// Windows has at least 3 forms of messaging that apply to us. |
| 21 | +// 1) Control signals. |
| 22 | +// 2) Window messages. |
| 23 | +// 3) Service events. |
| 24 | +// 1 applies to SIGTERM, with exceptions. |
| 25 | +// `HandlerRoutine` will not receive `CTRL_LOGOFF_EVENT` nor |
| 26 | +// `CTRL_SHUTDOWN_EVENT` for "interactive applications" |
| 27 | +// (applications which link with `user32`; |
| 28 | +// see `SetConsoleCtrlHandler` documentation). |
| 29 | +// |
| 30 | +// We utilize `user32` (indirectly through the [xdg] package) |
| 31 | +// which flags us as interactive. As such, we need to |
| 32 | +// initialize a window message queue (2) and monitor it for |
| 33 | +// these events. The console handler (1) can (and must) be |
| 34 | +// registered simultaneously, to handle the other signals |
| 35 | +// such as interrupt, break, close, etc. |
| 36 | +// |
| 37 | +// We do not yet handle case 3. |
| 38 | + |
| 39 | +type wndProcFunc func(win.HWND, uint32, uintptr, uintptr) uintptr |
| 40 | + |
| 41 | +func registerSystemStoppers(ctx context.Context, shutdownSend wgShutdown) { |
| 42 | + shutdownSend.Add(2) |
| 43 | + // NOTE: [Go 1.20] This must be `syscall.SIGTERM` |
| 44 | + // not `windows.SIGTERM`, otherwise the runtime |
| 45 | + // will not set up the console control handler. |
| 46 | + go stopOnSignalLinear(shutdownSend, syscall.SIGTERM) |
| 47 | + go stopOnSignalLinear(shutdownSend, os.Interrupt) |
| 48 | + if err := createAndWatchWindow(ctx, shutdownSend); err != nil { |
| 49 | + panic(err) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func stopOnSignalLinear(shutdownSend wgShutdown, sig os.Signal) { |
| 54 | + signals := make(chan os.Signal, 1) |
| 55 | + signal.Notify(signals, sig) |
| 56 | + defer func() { |
| 57 | + signal.Stop(signals) |
| 58 | + shutdownSend.Done() |
| 59 | + }() |
| 60 | + for count := minimumShutdown; count <= maximumShutdown; count++ { |
| 61 | + select { |
| 62 | + case <-signals: |
| 63 | + if !shutdownSend.send(count) { |
| 64 | + return |
| 65 | + } |
| 66 | + case <-shutdownSend.Closing(): |
| 67 | + return |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +func createAndWatchWindow(ctx context.Context, shutdownSend wgShutdown) error { |
| 73 | + errs := make(chan error, 1) |
| 74 | + go func() { |
| 75 | + defer shutdownSend.Done() |
| 76 | + runtime.LockOSThread() // The window and message processor |
| 77 | + defer runtime.UnlockOSThread() // must be on the same thread. |
| 78 | + hWnd, err := createEventWindow("go-fs", shutdownSend) |
| 79 | + errs <- err |
| 80 | + if err != nil { |
| 81 | + return |
| 82 | + } |
| 83 | + closeWindowWhenDone := func() { |
| 84 | + select { |
| 85 | + case <-ctx.Done(): |
| 86 | + case <-shutdownSend.Closing(): |
| 87 | + } |
| 88 | + const ( |
| 89 | + NULL = 0 |
| 90 | + wParam = NULL |
| 91 | + lParam = NULL |
| 92 | + ) |
| 93 | + win.SendMessage(hWnd, win.WM_CLOSE, wParam, lParam) |
| 94 | + } |
| 95 | + go closeWindowWhenDone() |
| 96 | + const ( |
| 97 | + // Ignore C's `BOOL` declaration for `GetMessage` |
| 98 | + // it actually returns a trinary value. See MSDN docs. |
| 99 | + failed = -1 |
| 100 | + wmQuit = 0 |
| 101 | + success = 1 |
| 102 | + NULL = 0 |
| 103 | + msgFilterMin = NULL |
| 104 | + msgFilterMax = NULL |
| 105 | + ) |
| 106 | + for { |
| 107 | + var msg win.MSG |
| 108 | + switch win.GetMessage(&msg, hWnd, msgFilterMin, msgFilterMax) { |
| 109 | + case failed, wmQuit: |
| 110 | + // NOTE: If we fail here the error |
| 111 | + // (`GetLastError`) is dropped. |
| 112 | + // Given our parameter set, failure |
| 113 | + // implies the window handle was (somehow) |
| 114 | + // invalidated, so we can't continue. |
| 115 | + // This is very unlikely to happen on accident. |
| 116 | + // Especially outside of development. |
| 117 | + return |
| 118 | + case success: |
| 119 | + win.TranslateMessage(&msg) |
| 120 | + win.DispatchMessage(&msg) |
| 121 | + } |
| 122 | + } |
| 123 | + }() |
| 124 | + return <-errs |
| 125 | +} |
| 126 | + |
| 127 | +func createEventWindow(name string, shutdownSend wgShutdown) (win.HWND, error) { |
| 128 | + const INVALID_HANDLE_VALUE win.HWND = ^win.HWND(0) |
| 129 | + lpClassName, err := windows.UTF16PtrFromString(name) |
| 130 | + if err != nil { |
| 131 | + return INVALID_HANDLE_VALUE, err |
| 132 | + } |
| 133 | + var ( |
| 134 | + hInstance = win.GetModuleHandle(nil) |
| 135 | + windowClass = win.WNDCLASSEX{ |
| 136 | + LpfnWndProc: newWndProc(shutdownSend), |
| 137 | + HInstance: hInstance, |
| 138 | + LpszClassName: lpClassName, |
| 139 | + } |
| 140 | + ) |
| 141 | + windowClass.CbSize = uint32(unsafe.Sizeof(windowClass)) |
| 142 | + _ = win.RegisterClassEx(&windowClass) |
| 143 | + const ( |
| 144 | + NULL = 0 |
| 145 | + dwExStyle = NULL |
| 146 | + dwStyle = NULL |
| 147 | + x = NULL |
| 148 | + y = NULL |
| 149 | + nWidth = NULL |
| 150 | + nHeight = NULL |
| 151 | + hWndParent = NULL |
| 152 | + hMenu = NULL |
| 153 | + ) |
| 154 | + var ( |
| 155 | + lpWindowName *uint16 = nil |
| 156 | + lpParam unsafe.Pointer = nil |
| 157 | + hWnd = win.CreateWindowEx( |
| 158 | + dwExStyle, |
| 159 | + lpClassName, lpWindowName, |
| 160 | + dwStyle, |
| 161 | + x, y, |
| 162 | + nWidth, nHeight, |
| 163 | + hWndParent, hMenu, |
| 164 | + hInstance, lpParam, |
| 165 | + ) |
| 166 | + ) |
| 167 | + if hWnd == NULL { |
| 168 | + var err error = generic.ConstError( |
| 169 | + "CreateWindowEx failed", |
| 170 | + ) |
| 171 | + if lErr := windows.GetLastError(); lErr != nil { |
| 172 | + err = fmt.Errorf("%w: %w", err, lErr) |
| 173 | + } |
| 174 | + return INVALID_HANDLE_VALUE, err |
| 175 | + } |
| 176 | + return hWnd, nil |
| 177 | +} |
| 178 | + |
| 179 | +func newWndProc(shutdownSend wgShutdown) uintptr { |
| 180 | + return windows.NewCallback( |
| 181 | + func(hWnd win.HWND, uMsg uint32, wParam uintptr, lParam uintptr) uintptr { |
| 182 | + switch uMsg { |
| 183 | + case win.WM_QUERYENDSESSION: |
| 184 | + const shutdownOrRestart = 0 |
| 185 | + var disposition shutdownDisposition |
| 186 | + switch { |
| 187 | + case lParam == shutdownOrRestart: |
| 188 | + disposition = immediateShutdown |
| 189 | + case lParam&win.ENDSESSION_LOGOFF != 0: |
| 190 | + disposition = shortShutdown |
| 191 | + case lParam&win.ENDSESSION_CRITICAL != 0: |
| 192 | + disposition = immediateShutdown |
| 193 | + default: |
| 194 | + disposition = immediateShutdown |
| 195 | + } |
| 196 | + shutdownSend.send(disposition) |
| 197 | + const ( |
| 198 | + FALSE = 0 |
| 199 | + canClose = FALSE |
| 200 | + ) |
| 201 | + return canClose |
| 202 | + case win.WM_CLOSE: |
| 203 | + const processedToken = 0 |
| 204 | + shutdownSend.send(immediateShutdown) |
| 205 | + win.DestroyWindow(hWnd) |
| 206 | + return processedToken |
| 207 | + case win.WM_DESTROY: |
| 208 | + const processedToken = 0 |
| 209 | + shutdownSend.send(immediateShutdown) |
| 210 | + const toCallingThread = 0 |
| 211 | + win.PostQuitMessage(toCallingThread) |
| 212 | + return processedToken |
| 213 | + default: |
| 214 | + return win.DefWindowProc(hWnd, uMsg, wParam, lParam) |
| 215 | + } |
| 216 | + }) |
| 217 | +} |
0 commit comments