-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain.go
More file actions
289 lines (253 loc) · 9.09 KB
/
main.go
File metadata and controls
289 lines (253 loc) · 9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//go:build windows
package main
import (
"fmt"
"os"
"strconv"
"syscall"
"time"
"unsafe"
"github.com/fosrl/windows/api"
"github.com/fosrl/windows/auth"
"github.com/fosrl/windows/config"
"github.com/fosrl/windows/elevate"
"github.com/fosrl/windows/managers"
"github.com/fosrl/windows/secrets"
"github.com/fosrl/windows/ui"
"github.com/fosrl/windows/version"
"github.com/fosrl/newt/logger"
"github.com/tailscale/walk"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/mgr"
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procMessageBoxW = user32.NewProc("MessageBoxW")
)
const mbOK = 0x00000000
// showMessageBox displays a message box (used when run without UI, e.g. RequestUILaunch failed).
func showMessageBox(text, caption string) {
textPtr, _ := windows.UTF16PtrFromString(text)
captionPtr, _ := windows.UTF16PtrFromString(caption)
procMessageBoxW.Call(0, uintptr(unsafe.Pointer(textPtr)), uintptr(unsafe.Pointer(captionPtr)), mbOK)
}
// waitForServiceRunning polls service state until Running or timeout. Returns true if Running.
func waitForServiceRunning(service *mgr.Service, timeout time.Duration) bool {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
status, err := service.Query()
if err != nil {
return false
}
if status.State == svc.Running {
return true
}
time.Sleep(300 * time.Millisecond)
}
return false
}
func execElevatedManagerServiceInstaller() error {
path, err := os.Executable()
if err != nil {
return err
}
err = elevate.ShellExecute(path, "/installmanagerservice", "", windows.SW_SHOW)
if err != nil && err != windows.ERROR_CANCELLED {
return err
}
os.Exit(0)
return windows.ERROR_UNHANDLED_EXCEPTION // Not reached
}
func main() {
// Setup logging first
setupLogging()
// Log version on startup
logger.Info("Pangolin version %s starting", version.Number)
// Check if we're being run as the manager service
if len(os.Args) >= 2 && os.Args[1] == "/managerservice" {
// Run as Windows service
logger.Info("Starting as manager service")
if err := managers.Run(); err != nil {
logger.Fatal("Manager service failed: %v", err)
}
return
}
// Check if we're being run as a tunnel service
if len(os.Args) >= 3 && os.Args[1] == "/tunnelservice" {
// Run as tunnel service
configPath := os.Args[2]
logger.Info("Starting as tunnel service with config: %s", configPath)
// Read config from file
configJSON, err := os.ReadFile(configPath)
if err != nil {
logger.Fatal("Failed to read tunnel config: %v", err)
}
// Run the tunnel service
if err := managers.RunTunnelService(string(configJSON)); err != nil {
logger.Fatal("Tunnel service failed: %v", err)
}
return
}
// Handle /installmanagerservice flag (called after elevation)
if len(os.Args) >= 2 && os.Args[1] == "/installmanagerservice" {
err := managers.InstallManager()
if err != nil {
if err == managers.ErrManagerAlreadyRunning {
logger.Info("Manager service is already running")
managers.RequestUILaunchWithRetry(15 * time.Second)
return
}
logger.Fatal("Failed to install manager service: %v", err)
}
logger.Info("Manager service installed successfully")
if managers.RequestUILaunchWithRetry(15 * time.Second) {
logger.Debug("UI launch requested successfully")
}
return
}
// Check if we're being launched by the manager service with /ui flag
if len(os.Args) >= 5 && os.Args[1] == "/ui" {
// We're being launched by the manager service
// Args: [exe, "/ui", readerFd, writerFd, eventsFd]
readerFd, err1 := strconv.ParseUint(os.Args[2], 10, 64)
writerFd, err2 := strconv.ParseUint(os.Args[3], 10, 64)
eventsFd, err3 := strconv.ParseUint(os.Args[4], 10, 64)
if err1 != nil || err2 != nil || err3 != nil {
logger.Fatal("Invalid file descriptors from manager service")
}
// Open the file descriptors as files
reader := os.NewFile(uintptr(readerFd), "reader")
writer := os.NewFile(uintptr(writerFd), "writer")
events := os.NewFile(uintptr(eventsFd), "events")
// Initialize IPC client to connect to manager service
managers.InitializeIPCClient(reader, writer, events)
logger.Info("Connected to manager service via IPC")
// Fall through to run UI
} else {
// No arguments - normal entry when user double-clicks the .exe.
// Try the named pipe first so standard users never need SCM or UAC when the manager is running.
if managers.RequestUILaunch() {
return
}
// Pipe connect failed (manager not running or not installed). Use SCM to install/start; may require UAC.
serviceName := config.AppName + "Manager"
m, err := mgr.Connect()
if err != nil {
if err == windows.ERROR_ACCESS_DENIED {
logger.Info("Cannot access service manager without admin privileges")
logger.Info("Attempting to install/start manager service (will show UAC prompt)...")
err = execElevatedManagerServiceInstaller()
if err != nil {
logger.Fatal("Failed to install/start manager service: %v\nPlease run as administrator to install the service.", err)
}
return
}
logger.Fatal("Failed to connect to service manager: %v", err)
}
defer m.Disconnect()
service, err := m.OpenService(serviceName)
if err != nil {
logger.Info("Manager service not found, installing...")
err = execElevatedManagerServiceInstaller()
if err != nil {
logger.Fatal("Failed to install manager service: %v", err)
}
return
}
defer service.Close()
status, err := service.Query()
if err != nil {
logger.Fatal("Failed to query service status: %v", err)
}
if status.State == svc.Running || status.State == svc.StartPending {
if managers.RequestUILaunchWithRetry(15 * time.Second) {
return
}
logger.Error("Could not start Pangolin. Please try again or contact your administrator.")
showMessageBox("Could not start Pangolin. Please try again or contact your administrator.", "Pangolin")
return
}
if status.State == svc.Stopped {
logger.Info("Manager service is stopped, starting...")
err = service.Start()
if err != nil {
if err == windows.ERROR_ACCESS_DENIED {
logger.Info("Need admin privileges to start service, requesting elevation...")
err = elevate.ShellExecute("cmd.exe", fmt.Sprintf("/c net start \"%s\"", serviceName), "", windows.SW_HIDE)
if err != nil && err != windows.ERROR_CANCELLED {
logger.Fatal("Failed to start manager service (access denied): %v\nPlease start the service manually or run as administrator.", err)
}
if err == windows.ERROR_CANCELLED {
logger.Info("User cancelled elevation, cannot start service")
return
}
if !waitForServiceRunning(service, 30*time.Second) {
status, err = service.Query()
if err != nil {
logger.Fatal("Failed to query service status after start: %v", err)
}
if status.State == svc.Stopped {
logger.Fatal("Service failed to start. Please start it manually or run as administrator.")
}
}
logger.Info("Manager service started via elevation, UI should appear shortly")
} else {
logger.Fatal("Failed to start manager service: %v", err)
}
} else {
logger.Info("Manager service started, UI should appear shortly")
waitForServiceRunning(service, 30*time.Second)
}
}
if managers.RequestUILaunchWithRetry(15 * time.Second) {
return
}
return
}
app, err := walk.InitApp()
if err != nil {
logger.Fatal("Failed to initialize app: %v", err)
}
// Create a hidden main window (required for NotifyIcon)
mw, err := walk.NewMainWindow()
if err != nil {
logger.Fatal("Failed to create main window: %v", err)
}
mw.SetVisible(false)
// Initialize managers
accountManager := config.NewAccountManager()
configManager := config.NewConfigManager()
secretManager := secrets.NewSecretManager()
var hostname string
if activeAccount, _ := accountManager.ActiveAccount(); activeAccount != nil {
hostname = activeAccount.Hostname
} else {
hostname = config.DefaultHostname
}
apiClient := api.NewAPIClient(hostname, "")
authManager := auth.NewAuthManager(apiClient, configManager, accountManager, secretManager)
// When any authenticated request gets 401/403, set session-expired on the UI thread
apiClient.SetOnUnauthorized(func() {
walk.App().Synchronize(authManager.MarkSessionExpired)
})
// Initialize auth manager (loads saved session token if available)
if err := authManager.Initialize(); err != nil {
logger.Error("Failed to initialize auth manager: %v", err)
}
// Setup tray icon and menu
if err := ui.SetupTray(mw, authManager, configManager, accountManager, apiClient, secretManager); err != nil {
logger.Fatal("Failed to setup tray: %v", err)
}
// Manager service handles all update checking
// If we're launched with /ui flag, we're connected to manager via IPC
if len(os.Args) >= 5 && os.Args[1] == "/ui" {
logger.Info("Connected to manager service - update checking handled by manager")
} else {
logger.Info("Running standalone - manager service should be running separately")
// Note: In production, the UI should always be launched by the manager service
// This standalone mode is mainly for development/testing
}
// Run the application
app.Run()
}