Debian Codegraph @

src/ui_win_gui.c

raw
1 /*
2 * stunnel TLS offloading and load-balancing proxy
3 * Copyright (C) 1998-2026 Michal Trojnara <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, see <http://www.gnu.org/licenses>.
17 *
18 * Linking stunnel statically or dynamically with other modules is making
19 * a combined work based on stunnel. Thus, the terms and conditions of
20 * the GNU General Public License cover the whole combination.
21 *
22 * In addition, as a special exception, the copyright holder of stunnel
23 * gives you permission to combine stunnel with free software programs or
24 * libraries that are released under the GNU LGPL and with code included
25 * in the standard release of OpenSSL under the OpenSSL License (or
26 * modified versions of such code, with unchanged license). You may copy
27 * and distribute such a system following the terms of the GNU GPL for
28 * stunnel and the licenses of the other code concerned.
29 *
30 * Note that people who make modified versions of stunnel are not obligated
31 * to grant this special exception for their modified versions; it is their
32 * choice whether to do so. The GNU General Public License gives permission
33 * to release a modified version without this exception; this exception
34 * also makes it possible to release a modified version which carries
35 * forward this exception.
36 */
37
38 #include "prototypes.h"
39 #include <commdlg.h>
40 #include <commctrl.h>
41 #ifndef _WIN32_WCE
42 #include <psapi.h>
43 #endif
44 #include <sddl.h>
45 #include "resources.h"
46
47 #define LOG_LINES 1000
48
49 #ifdef _WIN32_WCE
50 #define STUNNEL_PLATFORM "WinCE"
51 #else
52 #ifdef _WIN64
53 #define STUNNEL_PLATFORM "Win64"
54 #else /* MSDN claims that _WIN32 is always defined */
55 #define STUNNEL_PLATFORM "Win32"
56 #endif
57 #define SERVICE_NAME TEXT("stunnel")
58 #define SERVICE_DISPLAY_NAME TEXT("Stunnel TLS wrapper")
59 #endif
60
61 /* mingw-Patches-1825044 is missing in Debian Squeeze */
62 WINBASEAPI BOOL WINAPI CheckTokenMembership(HANDLE, PSID, PBOOL);
63
64 /* initialization */
65 NOEXPORT unsigned __stdcall daemon_thread(void *);
66
67 /* GUI core */
68 NOEXPORT void gui_cmdline(void);
69 NOEXPORT void gui_init(void);
70 NOEXPORT int gui_loop(void);
71
72 /* GUI callbacks */
73 NOEXPORT void CALLBACK timer_proc(HWND, UINT, UINT_PTR, DWORD);
74 NOEXPORT LRESULT CALLBACK window_proc(HWND, UINT, WPARAM, LPARAM);
75 NOEXPORT LRESULT CALLBACK edit_proc(HWND, UINT, WPARAM, LPARAM);
76 NOEXPORT LRESULT CALLBACK about_proc(HWND, UINT, WPARAM, LPARAM);
77 NOEXPORT LRESULT CALLBACK pass_proc(HWND, UINT, WPARAM, LPARAM);
78
79 /* icon tray */
80 NOEXPORT void tray_update(const int);
81 NOEXPORT void tray_delete(void);
82
83 /* configuration file (re)loading */
84 NOEXPORT void config_valid(void);
85 NOEXPORT void config_invalid(void);
86 NOEXPORT void config_edit(HWND);
87
88 /* peer certs */
89 NOEXPORT void peer_menu_update(void);
90 NOEXPORT void peer_menu_update_unlocked(void);
91 NOEXPORT void peer_cert_save(WPARAM wParam);
92
93 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L
94 /* UI callbacks */
95 NOEXPORT int pin_cb(UI *, UI_STRING *);
96 #endif /* !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L */
97
98 /* log handling */
99 NOEXPORT void log_save(void);
100 NOEXPORT void log_push(LPCTSTR);
101 NOEXPORT void log_update(void);
102 NOEXPORT LPTSTR log_txt(void);
103
104 /* control pipe support */
105 NOEXPORT void control_pipe_names(void);
106 NOEXPORT int control_pipe_client(void);
107 NOEXPORT int control_pipe_server(LPTSTR);
108 NOEXPORT unsigned __stdcall control_pipe_server_thread(void *);
109 NOEXPORT unsigned __stdcall control_pipe_instance_thread(void *);
110 NOEXPORT int control_pipe_send(HANDLE, const char *, ...);
111 NOEXPORT char *control_pipe_recv(HANDLE);
112 NOEXPORT char *control_pipe_call(LPTSTR, const char *, ...);
113
114 /* NT Service support */
115 #ifndef _WIN32_WCE
116 NOEXPORT int service_initialize(void);
117 NOEXPORT int service_install(void);
118 NOEXPORT int service_uninstall(void);
119 NOEXPORT int service_start(void);
120 NOEXPORT int service_stop(void);
121 NOEXPORT void WINAPI service_main(DWORD, LPTSTR *);
122 NOEXPORT void WINAPI control_handler(DWORD);
123 #endif /* !defined(_WIN32_WCE) */
124
125 /* helper functions */
126 NOEXPORT LPTSTR params_get(void);
127 NOEXPORT int text_file_create(LPTSTR, char *);
128 NOEXPORT void gui_signal_post(uint8_t);
129 NOEXPORT void error_box(LPCTSTR);
130
131 /* global variables */
132 static struct LIST {
133 struct LIST *next;
134 size_t len;
135 TCHAR txt[1]; /* single character for trailing '\0' */
136 } *head=NULL, *tail=NULL;
137
138 static HINSTANCE ghInst;
139 static HWND edit_handle=NULL, pause_handle=NULL;
140 static HMENU tray_menu_handle=NULL;
141 #ifndef _WIN32_WCE
142 static HMENU main_menu_handle=NULL;
143 #endif
144 static HWND hwnd=NULL; /* main window handle */
145 #ifdef _WIN32_WCE
146 static HWND command_bar_handle; /* command bar handle */
147 #endif
148 static WNDPROC default_edit_proc;
149 /* win32_name is needed for any error_box(), message_box(),
150 * and the initial main window title */
151 static TCHAR *win32_name=TEXT("stunnel ") TEXT(STUNNEL_VERSION)
152 TEXT(" on ") TEXT(STUNNEL_PLATFORM) TEXT(" (not configured)");
153
154 #ifndef _WIN32_WCE
155 static SERVICE_STATUS serviceStatus;
156 static SERVICE_STATUS_HANDLE serviceStatusHandle=0;
157 #endif
158
159 static BOOL visible=FALSE;
160 static HANDLE main_initialized=NULL; /* global initialization performed */
161 static HANDLE main_terminated=NULL; /* daemon_loop() terminated */
162 static HANDLE config_ready=NULL; /* reload without a valid configuration */
163 static BOOL new_logs=FALSE;
164 static int removed_logs=0;
165
166 static struct {
167 char *config_file;
168 char *config_command;
169 unsigned service:1, install:1, uninstall:1, start:1, stop:1,
170 quiet:1, exit:1, reload:1, reopen:1;
171 } cmdline;
172
173 static char ui_pass[PEM_BUFSIZE];
174
175 LPTSTR pipe_name_ui, pipe_name_service;
176 BOOL nt_service_client=FALSE;
177
178 /**************************************** initialization */
179
180 int WINAPI WinMain(HINSTANCE this_instance, HINSTANCE prev_instance,
181 #ifdef _WIN32_WCE
182 LPWSTR lpCmdLine,
183 #else
184 LPSTR lpCmdLine,
185 #endif
186 int nCmdShow) {
187 HANDLE daemon;
188
189 (void)prev_instance; /* squash the unused parameter warning */
190 (void)lpCmdLine; /* squash the unused parameter warning */
191 (void)nCmdShow; /* squash the unused parameter warning */
192
193 ghInst=this_instance;
194 if(stunnel_init()) {
195 message_box(TEXT("Initialization failed"), MB_ICONERROR);
196 return 1;
197 }
198 gui_cmdline(); /* setup global cmdline structure */
199 control_pipe_names();
200
201 #ifndef _WIN32_WCE
202 if(cmdline.service) { /* "-service" must be processed before "-install" */
203 cmdline.quiet=1;
204 /* create a service pipe thread for accepting signals */
205 if(control_pipe_server(pipe_name_service))
206 return 1; /* a control pipe service already exists or failed */
207 return service_initialize();
208 }
209 if(cmdline.install)
210 return service_install();
211 if(cmdline.uninstall)
212 return service_uninstall();
213 if(cmdline.start)
214 return service_start();
215 if(cmdline.stop)
216 return service_stop();
217 #endif
218
219 /* auto-reset, non-signaled events */
220 main_initialized=CreateEvent(NULL, FALSE, FALSE, NULL);
221 main_terminated=CreateEvent(NULL, FALSE, FALSE, NULL);
222 config_ready=CreateEvent(NULL, FALSE, FALSE, NULL);
223
224 if(control_pipe_client())
225 return 0;
226 /* create a service pipe thread for accepting signals */
227 if(control_pipe_server(pipe_name_service))
228 return 1; /* a control pipe service already exists or failed */
229 gui_init();
230 /* hwnd needs to be initialized before _beginthreadex() */
231 daemon=(HANDLE)_beginthreadex(NULL, DEFAULT_STACK_SIZE,
232 daemon_thread, NULL, 0, NULL);
233 if(!daemon)
234 fatal("Failed to create the daemon thread");
235 CloseHandle(daemon);
236 WaitForSingleObject(main_initialized, INFINITE);
237 return gui_loop();
238 }
239
240 NOEXPORT unsigned __stdcall daemon_thread(void *arg) {
241 (void)arg; /* squash the unused parameter warning */
242
243 tls_alloc(NULL, NULL, "main"); /* new thread-local storage */
244 main_init();
245 SetEvent(main_initialized); /* unlock the GUI thread */
246 /* get a valid configuration */
247 if(cmdline.config_command) {
248 main_configure(cmdline.config_command, NULL);
249 ShowWindow(hwnd, SW_SHOWNORMAL); /* show window */
250 SetForegroundWindow(hwnd); /* bring on top */
251 }
252 while(main_configure(cmdline.config_file, NULL)) {
253 PostMessage(hwnd, WM_INVALID_CONFIG, 0, 0); /* display error */
254 WaitForSingleObject(config_ready, INFINITE);
255 }
256 PostMessage(hwnd, WM_VALID_CONFIG, 0, 0);
257
258 /* start the main loop */
259 daemon_loop();
260 main_cleanup();
261 SetEvent(main_terminated); /* ready for WM_QUIT */
262 PostMessage(hwnd, WM_TERMINATE, 0, 0); /* terminate GUI */
263 tls_cleanup();
264 _endthreadex(0); /* SIGNAL_TERMINATE received */
265 return 0;
266 }
267
268 /**************************************** GUI core */
269
270 NOEXPORT void gui_cmdline() {
271 char *line, *c, *config_file=NULL;
272
273 memset(&cmdline, 0, sizeof cmdline);
274 line=tstr2str(params_get());
275 c=line;
276 while(*c) {
277 char *opt;
278
279 if(*c=='\"') { /* the option is within double quotes */
280 *c++='\0';
281 opt=c;
282 while(*c && *c!='\"') /* find the closing double quote */
283 c++;
284 if(*c=='\"') /* replace with '\0' if found */
285 *c++='\0';
286 } else if(*c=='-' || *c=='/') { /* advanced parameters: the option is the next word */
287 opt=c;
288 while(*c && !isspace(*c)) /* skip non-whitespaces */
289 c++;
290 } else { /* the rest of the line is our configuration file path */
291 config_file=c;
292 break;
293 }
294 while(*c && isspace(*c)) /* replace whitespaces with '\0' */
295 *c++='\0';
296
297 if(*opt=='/' || *opt=='-') {
298 if(!strcasecmp(opt+1, "install")) {
299 cmdline.install=1;
300 continue;
301 }
302 if(!strcasecmp(opt+1, "uninstall")) {
303 cmdline.uninstall=1;
304 continue;
305 }
306 if(!strcasecmp(opt+1, "reload")) {
307 cmdline.reload=1;
308 continue;
309 }
310 if(!strcasecmp(opt+1, "reopen")) {
311 cmdline.reopen=1;
312 continue;
313 }
314 if(!strcasecmp(opt+1, "start")) {
315 cmdline.start=1;
316 continue;
317 }
318 if(!strcasecmp(opt+1, "stop")) {
319 cmdline.stop=1;
320 continue;
321 }
322 if(!strcasecmp(opt+1, "service")) {
323 cmdline.service=1;
324 continue;
325 }
326 if(!strcasecmp(opt+1, "quiet")) {
327 cmdline.quiet=1;
328 continue;
329 }
330 if(!strcasecmp(opt+1, "exit")) {
331 cmdline.exit=1;
332 continue;
333 }
334 if(!strcasecmp(opt+1, "help")) {
335 cmdline.config_command="-help";
336 continue;
337 }
338 if(!strcasecmp(opt+1, "version")) {
339 cmdline.config_command="-version";
340 continue;
341 }
342 if(!strcasecmp(opt+1, "sockets")) {
343 cmdline.config_command="-sockets";
344 continue;
345 }
346 if(!strcasecmp(opt+1, "options")) {
347 cmdline.config_command="-options";
348 continue;
349 }
350 }
351 /* any other non-empty option must be our configuration file name */
352 if(*opt && !config_file)
353 config_file=opt;
354 }
355 if(!config_file || !*config_file)
356 config_file="stunnel.conf";
357 config_file=_fullpath(NULL, config_file, 0);
358 if(config_file) { /* _fullpath managed to create an absolute path */
359 cmdline.config_file=str_dup(config_file);
360 free(config_file);
361 } else {
362 cmdline.config_file=str_dup("stunnel.conf");
363 }
364 str_free(line);
365 }
366
367 NOEXPORT void gui_init() {
368 #ifdef _WIN32_WCE
369 WNDCLASS wc;
370 #else
371 WNDCLASSEX wc;
372 #endif
373 LPTSTR classname=TEXT("stunnel_main_window_class");
374
375 /* register the class */
376 #ifndef _WIN32_WCE
377 wc.cbSize=sizeof wc;
378 #endif
379 wc.style=CS_VREDRAW|CS_HREDRAW;
380 wc.lpfnWndProc=window_proc;
381 wc.cbClsExtra=wc.cbWndExtra=0;
382 wc.hInstance=ghInst;
383 wc.hIcon=LoadIcon(ghInst, MAKEINTRESOURCE(IDI_STUNNEL_MAIN));
384 wc.hCursor=LoadCursor(NULL, IDC_ARROW);
385 wc.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);
386 wc.lpszMenuName=NULL;
387 wc.lpszClassName=classname;
388 #ifdef _WIN32_WCE
389 RegisterClass(&wc);
390 #else
391 /* load 16x16 icon */
392 wc.hIconSm=LoadImage(ghInst, MAKEINTRESOURCE(IDI_STUNNEL_MAIN), IMAGE_ICON,
393 GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
394 RegisterClassEx(&wc);
395 #endif
396
397 /* create main window */
398 #ifdef _WIN32_WCE
399 hwnd=CreateWindow(classname, win32_name, 0,
400 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
401 NULL, NULL, ghInst, NULL);
402 #else
403 main_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_MAINMENU));
404 hwnd=CreateWindow(classname, win32_name, WS_TILEDWINDOW,
405 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
406 NULL, main_menu_handle, ghInst, NULL);
407 #endif
408
409 /* create initial icon tray */
410 tray_update(0);
411 }
412
413 NOEXPORT int gui_loop() {
414 MSG msg;
415
416 /* setup periodic event to trigger log_update() and tray_update() */
417 SetTimer(NULL, 0, 1000, timer_proc); /* run callback once per second */
418
419 for(;;)
420 switch(GetMessage(&msg, NULL, 0, 0)) {
421 case -1:
422 ioerror("GetMessage");
423 return 0;
424 case 0:
425 /* the following error may only be logged if main_cleanup()
426 * did not disable logging with log_flush(LOG_MODE_BUFFER) */
427 ui_new_log("GUI message loop terminated with WM_QUIT");
428 return (int)msg.wParam;
429 default:
430 TranslateMessage(&msg);
431 DispatchMessage(&msg);
432 }
433 }
434
435 /**************************************** GUI callbacks */
436
437 NOEXPORT void CALLBACK timer_proc(HWND hWnd, UINT msg, UINT_PTR id, DWORD t) {
438 (void)hWnd; /* squash the unused parameter warning */
439 (void)msg; /* squash the unused parameter warning */
440 (void)id; /* squash the unused parameter warning */
441 (void)t; /* squash the unused parameter warning */
442 log_update();
443 tray_update(num_clients);
444 }
445
446 NOEXPORT LRESULT CALLBACK window_proc(HWND main_window_handle,
447 UINT message, WPARAM wParam, LPARAM lParam) {
448 POINT pt;
449 RECT rect;
450 HFONT monospaced_font, proportional_font;
451
452 #if 0
453 switch(message) {
454 case WM_CTLCOLORSTATIC:
455 case WM_TIMER:
456 break;
457 default:
458 s_log(LOG_DEBUG, "Window message: 0x%x(0x%hx,0x%lx)",
459 message, wParam, lParam);
460 }
461 #endif
462 switch(message) {
463 case WM_CREATE:
464 #ifdef _WIN32_WCE
465 /* create command bar */
466 command_bar_handle=CommandBar_Create(ghInst, main_window_handle, 1);
467 if(!command_bar_handle)
468 error_box(TEXT("CommandBar_Create"));
469 if(!CommandBar_InsertMenubar(command_bar_handle, ghInst, IDM_MAINMENU, 0))
470 error_box(TEXT("CommandBar_InsertMenubar"));
471 if(!CommandBar_AddAdornments(command_bar_handle, 0, 0))
472 error_box(TEXT("CommandBar_AddAdornments"));
473 #endif
474
475 /* create child edit window */
476 edit_handle=CreateWindowEx(WS_EX_STATICEDGE, WC_EDIT, NULL,
477 WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|ES_MULTILINE|ES_READONLY,
478 0, 0, 0, 0, main_window_handle, (HMENU)IDE_EDIT, ghInst, NULL);
479 pause_handle=CreateWindowEx(0, WC_BUTTON, TEXT("Pause auto-scroll"),
480 WS_CHILD|WS_VISIBLE|BS_CHECKBOX|BS_AUTOCHECKBOX|BS_TEXT,
481 0, 0, 0, 0, main_window_handle, (HMENU)IDE_PAUSE, ghInst, NULL);
482 default_edit_proc=(WNDPROC)SetWindowLongPtr(edit_handle, GWLP_WNDPROC,
483 (LONG_PTR)edit_proc);
484 #ifndef _WIN32_WCE
485 monospaced_font=CreateFont(-12, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE,
486 DEFAULT_CHARSET, OUT_RASTER_PRECIS, CLIP_DEFAULT_PRECIS,
487 PROOF_QUALITY, DEFAULT_PITCH, TEXT("Courier")),
488 SendMessage(edit_handle, WM_SETFONT, (WPARAM)monospaced_font,
489 MAKELPARAM(FALSE, 0)); /* no need to redraw right now */
490 proportional_font=CreateFont(-12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
491 DEFAULT_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,
492 DEFAULT_QUALITY, DEFAULT_PITCH, TEXT("Segoe UI")),
493 SendMessage(pause_handle, WM_SETFONT, (WPARAM)proportional_font,
494 MAKELPARAM(FALSE, 0)); /* no need to redraw right now */
495 #endif
496 /* NOTE: there's no return statement here -> proceeding with resize */
497
498 case WM_SIZE:
499 GetClientRect(main_window_handle, &rect);
500 #ifdef _WIN32_WCE
501 MoveWindow(edit_handle, 0, CommandBar_Height(command_bar_handle),
502 rect.right, rect.bottom-CommandBar_Height(command_bar_handle),
503 TRUE);
504 SendMessage(command_bar_handle, TB_AUTOSIZE, 0L, 0L);
505 CommandBar_AlignAdornments(command_bar_handle);
506 #else
507 MoveWindow(edit_handle, 0, 0, rect.right, rect.bottom-17, TRUE);
508 MoveWindow(pause_handle, 0, rect.bottom-17, rect.right, 17, TRUE);
509 #endif
510 UpdateWindow(edit_handle);
511 /* CommandBar_Show(command_bar_handle, TRUE); */
512 return 0;
513
514 case WM_SETFOCUS:
515 SetFocus(edit_handle);
516 return 0;
517
518 case WM_PAINT:
519 {
520 PAINTSTRUCT ps;
521 BeginPaint(hwnd, &ps);
522 EndPaint(hwnd, &ps);
523 }
524 break;
525
526 case WM_GETMINMAXINFO:
527 {
528 LPMINMAXINFO minmaxinfo=(LPMINMAXINFO)lParam;
529 minmaxinfo->ptMinTrackSize.x=320;
530 minmaxinfo->ptMinTrackSize.y=200;
531 }
532 break;
533
534 case WM_CLOSE:
535 ShowWindow(main_window_handle, SW_HIDE);
536 return 0;
537
538 #ifdef WM_SHOWWINDOW
539 case WM_SHOWWINDOW:
540 visible=(BOOL)wParam;
541 #else /* this works for Pierre Delaage, but not for me... */
542 case WM_WINDOWPOSCHANGED:
543 visible=IsWindowVisible(main_window_handle);
544 #endif
545 if(tray_menu_handle)
546 CheckMenuItem(tray_menu_handle, IDM_SHOW_LOG,
547 visible ? MF_CHECKED : MF_UNCHECKED);
548 log_update();
549 #ifdef WM_SHOWWINDOW
550 return 0;
551 #else
552 break; /* proceed to DefWindowProc() */
553 #endif
554
555 case WM_DESTROY:
556 tray_delete(); /* remove the taskbark icon if exists */
557 #ifdef _WIN32_WCE
558 CommandBar_Destroy(command_bar_handle);
559 #else
560 if(main_menu_handle) {
561 if(!DestroyMenu(main_menu_handle))
562 ioerror("DestroyMenu");
563 main_menu_handle=NULL;
564 }
565 #endif
566 PostQuitMessage(0);
567 return 0;
568
569 case WM_TERMINATE:
570 DestroyWindow(main_window_handle);
571 return 0;
572
573 case WM_COMMAND:
574 switch(wParam) {
575 case IDM_ABOUT:
576 DialogBox(ghInst, TEXT("AboutBox"), main_window_handle,
577 (DLGPROC)about_proc);
578 break;
579 case IDM_SHOW_LOG:
580 if(visible) {
581 ShowWindow(main_window_handle, SW_HIDE); /* hide window */
582 } else {
583 ShowWindow(main_window_handle, SW_SHOWNORMAL); /* show window */
584 SetForegroundWindow(main_window_handle); /* bring on top */
585 }
586 break;
587 case IDM_CLOSE:
588 ShowWindow(main_window_handle, SW_HIDE); /* hide window */
589 break;
590 case IDM_EXIT:
591 gui_signal_post(SIGNAL_TERMINATE);
592 break;
593 case IDM_SAVE_LOG:
594 log_save();
595 break;
596 case IDM_EDIT_CONFIG:
597 #ifndef _WIN32_WCE
598 config_edit(main_window_handle);
599 #endif
600 break;
601 case IDM_RELOAD_CONFIG:
602 gui_signal_post(SIGNAL_RELOAD_CONFIG);
603 break;
604 case IDM_REOPEN_LOG:
605 gui_signal_post(SIGNAL_REOPEN_LOG);
606 break;
607 case IDM_CONNECTIONS:
608 gui_signal_post(SIGNAL_CONNECTIONS);
609 break;
610 case IDM_MANPAGE:
611 #ifndef _WIN32_WCE
612 ShellExecute(main_window_handle, TEXT("open"),
613 TEXT("..\\doc\\stunnel.html"), NULL, NULL, SW_SHOWNORMAL);
614 #endif
615 break;
616 case IDM_HOMEPAGE:
617 #ifndef _WIN32_WCE
618 ShellExecute(main_window_handle, TEXT("open"),
619 TEXT("http://www.stunnel.org/"), NULL, NULL, SW_SHOWNORMAL);
620 #endif
621 break;
622 default:
623 if(wParam>=IDM_PEER_MENU && wParam<IDM_PEER_MENU+number_of_sections)
624 peer_cert_save(wParam);
625 }
626 return 0;
627
628 case WM_SYSTRAY: /* a taskbar event */
629 switch(lParam) {
630 #ifdef _WIN32_WCE
631 case WM_LBUTTONDOWN: /* no right mouse button on Windows CE */
632 GetWindowRect(GetDesktopWindow(), &rect); /* no cursor position */
633 pt.x=rect.right;
634 pt.y=rect.bottom-25;
635 #else
636 case WM_RBUTTONDOWN:
637 GetCursorPos(&pt);
638 #endif
639 SetForegroundWindow(main_window_handle);
640 if(tray_menu_handle)
641 TrackPopupMenuEx(GetSubMenu(tray_menu_handle, 0),
642 TPM_BOTTOMALIGN, pt.x, pt.y, main_window_handle, NULL);
643 PostMessage(main_window_handle, WM_NULL, 0, 0);
644 break;
645
646 #ifndef _WIN32_WCE
647 case WM_LBUTTONDOWN: /* switch log window visibility */
648 if(visible) {
649 ShowWindow(main_window_handle, SW_HIDE); /* hide window */
650 } else {
651 ShowWindow(main_window_handle, SW_SHOWNORMAL); /* show window */
652 SetForegroundWindow(main_window_handle); /* bring on top */
653 }
654 break;
655 #endif
656 }
657 return 0;
658
659 case WM_VALID_CONFIG:
660 config_valid();
661 return 0;
662
663 case WM_INVALID_CONFIG:
664 config_invalid();
665 return 0;
666
667 case WM_NEW_CHAIN:
668 #ifndef _WIN32_WCE
669 if(main_menu_handle)
670 EnableMenuItem(main_menu_handle,
671 (UINT)(IDM_PEER_MENU+wParam), MF_ENABLED);
672 #endif
673 if(tray_menu_handle)
674 EnableMenuItem(tray_menu_handle,
675 (UINT)(IDM_PEER_MENU+wParam), MF_ENABLED);
676 return 0;
677
678 case WM_CAPWIN_DESTROY:
679 DestroyWindow(main_window_handle);
680 return TRUE;
681 }
682
683 return DefWindowProc(main_window_handle, message, wParam, lParam);
684 }
685
686 NOEXPORT LRESULT CALLBACK edit_proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
687 if(uMsg==WM_CHAR && wParam==VK_SPACE) {
688 Button_SetCheck(pause_handle, !Button_GetCheck(pause_handle));
689 return 0;
690 }
691 return CallWindowProc(default_edit_proc, hWnd, uMsg, wParam, lParam);
692 }
693
694 NOEXPORT LRESULT CALLBACK about_proc(HWND dialog_handle, UINT message,
695 WPARAM wParam, LPARAM lParam) {
696 (void)lParam; /* squash the unused parameter warning */
697
698 switch(message) {
699 case WM_INITDIALOG:
700 return TRUE;
701 case WM_COMMAND:
702 switch(wParam) {
703 case IDOK:
704 case IDCANCEL:
705 EndDialog(dialog_handle, TRUE);
706 return TRUE;
707 }
708 }
709 return FALSE;
710 }
711
712 NOEXPORT LRESULT CALLBACK pass_proc(HWND dialog_handle, UINT message,
713 WPARAM wParam, LPARAM lParam) {
714 LPTSTR titlebar;
715 union {
716 TCHAR txt[PEM_BUFSIZE];
717 WORD len;
718 } pass_dialog;
719 WORD pass_len;
720 char* pass_txt;
721 LPTSTR key_file_name;
722
723 switch(message) {
724 case WM_INITDIALOG:
725 /* set the default push button to "Cancel" */
726 SendMessage(dialog_handle, DM_SETDEFID, (WPARAM)IDCANCEL, (LPARAM)0);
727
728 if(current_section) { /* should always be set */
729 SetDlgItemText(dialog_handle, IDE_PASSPHRASE_LABEL,
730 is_prefix(current_section->key, "pkcs11:") ?
731 TEXT("Smart card PIN:") : TEXT("Key passphrase:"));
732 key_file_name=str2tstr(current_section->key);
733 titlebar=str_tprintf(TEXT("Private key: %s"), key_file_name);
734 str_free(key_file_name);
735 SetWindowText(dialog_handle, titlebar);
736 str_free(titlebar);
737 }
738 return TRUE;
739
740 case WM_COMMAND:
741 /* set the default push button to "OK" when the user enters text */
742 if(HIWORD(wParam)==EN_CHANGE && LOWORD(wParam)==IDE_PASSEDIT)
743 SendMessage(dialog_handle, DM_SETDEFID, (WPARAM)IDOK, (LPARAM)0);
744 switch(wParam) {
745 case IDOK:
746 /* get number of characters */
747 pass_len=(WORD)SendDlgItemMessage(dialog_handle,
748 IDE_PASSEDIT, EM_LINELENGTH, (WPARAM)0, (LPARAM)0);
749 if(!pass_len || pass_len>=PEM_BUFSIZE) {
750 EndDialog(dialog_handle, FALSE);
751 return FALSE;
752 }
753
754 /* put the number of characters into first word of buffer */
755 pass_dialog.len=pass_len;
756
757 /* get the characters */
758 SendDlgItemMessage(dialog_handle, IDE_PASSEDIT, EM_GETLINE,
759 (WPARAM)0 /* line 0 */, (LPARAM)pass_dialog.txt);
760 pass_dialog.txt[pass_len]='\0'; /* null-terminate the string */
761
762 /* convert input passphrase to UTF-8 string (as ui_pass) */
763 pass_txt=tstr2str(pass_dialog.txt);
764 strcpy(ui_pass, pass_txt);
765 str_free(pass_txt);
766
767 EndDialog(dialog_handle, TRUE);
768 return TRUE;
769
770 case IDCANCEL:
771 EndDialog(dialog_handle, FALSE);
772 return TRUE;
773 }
774 return 0;
775 }
776 return FALSE;
777
778 UNREFERENCED_PARAMETER(lParam);
779 }
780
781 /**************************************** icon tray */
782
783 NOEXPORT void tray_update(const int num) {
784 NOTIFYICONDATA nid;
785 static ICON_TYPE previous_icon=ICON_NONE;
786 ICON_TYPE current_icon;
787 LPTSTR tip;
788
789 if(!nt_service_client) {
790 if(!global_options.option.taskbar) { /* currently disabled */
791 tray_delete(); /* remove the taskbark icon if exists */
792 return;
793 }
794 }
795 if(!tray_menu_handle) /* initialize taskbar */
796 tray_menu_handle=LoadMenu(ghInst, MAKEINTRESOURCE(IDM_TRAYMENU));
797 if(!tray_menu_handle) {
798 ioerror("LoadMenu");
799 return;
800 }
801
802 ZeroMemory(&nid, sizeof nid);
803 nid.cbSize=sizeof nid;
804 nid.uID=1; /* application-defined icon ID */
805 nid.uFlags=NIF_MESSAGE|NIF_TIP;
806 nid.uCallbackMessage=WM_SYSTRAY; /* notification message */
807 nid.hWnd=hwnd; /* window to receive notifications */
808 if(num<0) {
809 tip=str_tprintf(TEXT("stunnel is down"));
810 current_icon=ICON_ERROR;
811 } else if(num>0) {
812 tip=str_tprintf(TEXT("stunnel connections: %d"), num);
813 current_icon=ICON_ACTIVE;
814 } else {
815 tip=str_tprintf(TEXT("stunnel is idle"));
816 current_icon=ICON_IDLE;
817 }
818 _tcsncpy(nid.szTip, tip, 63);
819 nid.szTip[63]=TEXT('\0');
820 str_free(tip);
821 if(!nt_service_client) {
822 nid.hIcon=global_options.icon[current_icon];
823 } else { /* NT service client: configuration file ignored */
824 static ICON_IMAGE icon[ICON_NONE]={NULL, NULL, NULL};
825 if(!icon[current_icon])
826 icon[current_icon]=load_icon_default(current_icon);
827 nid.hIcon=icon[current_icon];
828 }
829 if(current_icon!=previous_icon) {
830 nid.uFlags|=NIF_ICON;
831 previous_icon=current_icon;
832 }
833 if(Shell_NotifyIcon(NIM_MODIFY, &nid)) /* modify tooltip */
834 return; /* OK: taskbar icon exists */
835 /* tooltip update failed - try to create the icon */
836 nid.uFlags|=NIF_ICON;
837 Shell_NotifyIcon(NIM_ADD, &nid);
838 }
839
840 NOEXPORT void tray_delete(void) {
841 NOTIFYICONDATA nid;
842
843 if(tray_menu_handle) {
844 ZeroMemory(&nid, sizeof nid);
845 nid.cbSize=sizeof nid;
846 nid.uID=1; /* application-defined icon ID */
847 nid.hWnd=hwnd; /* window to receive notifications */
848 nid.uFlags=NIF_TIP; /* not really sure what to put here, but it works */
849 Shell_NotifyIcon(NIM_DELETE, &nid); /* this removes the icon */
850 if(!DestroyMenu(tray_menu_handle)) /* release menu resources */
851 ioerror("DestroyMenu");
852 tray_menu_handle=NULL;
853 }
854 }
855
856 /**************************************** configuration file (re)loading */
857
858 NOEXPORT void config_invalid() {
859 /* update the main window title */
860 win32_name=TEXT("stunnel ") TEXT(STUNNEL_VERSION) TEXT(" on ")
861 TEXT(STUNNEL_PLATFORM) TEXT(" (invalid configuration file)");
862 SetWindowText(hwnd, win32_name);
863
864 /* log window is hidden by default */
865 ShowWindow(hwnd, SW_SHOWNORMAL); /* show window */
866 SetForegroundWindow(hwnd); /* bring on top */
867
868 tray_update(-1); /* error icon */
869 peer_menu_update(); /* purge the list of sections */
870
871 log_push(TEXT(""));
872 ui_new_log("Server is down");
873 message_box(TEXT("Stunnel server is down due to an error.\n")
874 TEXT("You need to exit and correct the problem.\n")
875 TEXT("Click OK to see the error log window."),
876 MB_ICONERROR);
877 }
878
879 NOEXPORT void config_valid() {
880 /* update the main window title */
881 win32_name=TEXT("stunnel ") TEXT(STUNNEL_VERSION) TEXT(" on ")
882 TEXT(STUNNEL_PLATFORM);
883 SetWindowText(hwnd, win32_name);
884
885 tray_update(num_clients); /* idle or busy icon (on reload) */
886 peer_menu_update(); /* one menu item per section */
887
888 /* enable IDM_REOPEN_LOG menu if a log file is used, disable otherwise */
889 if(!nt_service_client) {
890 #ifndef _WIN32_WCE
891 EnableMenuItem(main_menu_handle, IDM_REOPEN_LOG,
892 (UINT)(global_options.output_file ? MF_ENABLED : MF_GRAYED));
893 #endif
894 if(tray_menu_handle)
895 EnableMenuItem(tray_menu_handle, IDM_REOPEN_LOG,
896 (UINT)(global_options.output_file ? MF_ENABLED : MF_GRAYED));
897 }
898 }
899
900 /* TODO: port it to WCE */
901 NOEXPORT void config_edit(HWND main_window_handle) {
902 char *quoted;
903 LPTSTR conf_path;
904 DISK_FILE *df;
905
906 if(!cmdline.config_file)
907 return;
908 quoted=str_printf("\"%s\"", cmdline.config_file);
909 conf_path=str2tstr(quoted);
910 str_free(quoted);
911
912 df=file_open(cmdline.config_file, FILE_MODE_APPEND);
913 if(df) { /* the configuration file is writable */
914 file_close(df);
915 ShellExecute(main_window_handle, TEXT("open"),
916 TEXT("notepad.exe"), conf_path,
917 NULL, SW_SHOWNORMAL);
918 } else { /* UAC workaround */
919 ShellExecute(main_window_handle, TEXT("runas"),
920 TEXT("notepad.exe"), conf_path,
921 NULL, SW_SHOWNORMAL);
922 }
923 str_free(conf_path);
924 }
925
926 /**************************************** peer certs */
927
928 NOEXPORT void peer_menu_update(void) {
929 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_SECTIONS]);
930 peer_menu_update_unlocked();
931 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SECTIONS]);
932 }
933
934 NOEXPORT void peer_menu_update_unlocked(void) {
935 SERVICE_OPTIONS *section;
936 #ifndef _WIN32_WCE
937 HMENU main_peer_list=NULL;
938 #endif
939 HMENU tray_peer_list=NULL;
940 unsigned section_number;
941 LPTSTR servname;
942
943 /* purge menu peer lists */
944 #ifndef _WIN32_WCE
945 if(main_menu_handle)
946 main_peer_list=GetSubMenu(main_menu_handle, 2); /* 3rd sub-menu */
947 if(main_peer_list)
948 while(GetMenuItemCount(main_peer_list)) /* purge old menu */
949 DeleteMenu(main_peer_list, 0, MF_BYPOSITION);
950 #endif
951 if(tray_menu_handle)
952 tray_peer_list=GetSubMenu(GetSubMenu(tray_menu_handle, 0), 8); /* 9th sub-menu */
953 if(tray_peer_list)
954 while(GetMenuItemCount(tray_peer_list)) /* purge old menu */
955 DeleteMenu(tray_peer_list, 0, MF_BYPOSITION);
956
957 /* initialize data structures */
958 section_number=0;
959 for(section=service_options.next; section; section=section->next) {
960 servname=str2tstr(section->servname);
961
962 /* setup LPTSTR section->file */
963 section->file=str_tprintf(TEXT("peer-%s.pem"), servname);
964
965 /* setup section->help */
966 section->help=str_tprintf(
967 TEXT("Peer certificate chain has been saved.\n")
968 TEXT("Add the following lines to section [%s]:\n")
969 TEXT("\tCAfile = peer-%s.pem\n")
970 TEXT("\tverifyPeer = yes\n")
971 TEXT("to enable cryptographic authentication.\n")
972 TEXT("Then reload stunnel configuration file."),
973 servname, servname);
974
975 str_free(servname);
976
977 /* setup section->chain */
978 section->chain=NULL;
979
980 /* insert new menu item */
981 #ifndef _WIN32_WCE
982 if(main_peer_list)
983 if(!InsertMenu(main_peer_list, section_number,
984 MF_BYPOSITION|MF_STRING|MF_GRAYED,
985 IDM_PEER_MENU+section_number, section->file))
986 ioerror("InsertMenu");
987 #endif
988 if(tray_peer_list)
989 if(!InsertMenu(tray_peer_list, section_number,
990 MF_BYPOSITION|MF_STRING|MF_GRAYED,
991 IDM_PEER_MENU+section_number, section->file))
992 ioerror("InsertMenu");
993
994 ++section_number;
995 }
996 if(section_number) { /* enable Save Peer Certificate */
997 #ifndef _WIN32_WCE
998 /* 0 - File, 1 - Configuration, 2 - Save Peer Certificate */
999 EnableMenuItem(main_menu_handle, 2, MF_BYPOSITION|MF_ENABLED);
1000 #endif
1001 if(tray_menu_handle) /* 9th position on the tray menu */
1002 EnableMenuItem(GetSubMenu(tray_menu_handle, 0), 8, MF_BYPOSITION|MF_ENABLED);
1003 }
1004 if(hwnd)
1005 DrawMenuBar(hwnd);
1006 }
1007
1008 NOEXPORT void peer_cert_save(WPARAM wParam) {
1009 SERVICE_OPTIONS *section;
1010 unsigned section_number;
1011
1012 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_SECTIONS]);
1013 for(section=service_options.next, section_number=0;
1014 section && wParam!=IDM_PEER_MENU+section_number;
1015 section=section->next, ++section_number)
1016 ;
1017 if(section && !text_file_create(section->file, section->chain)) {
1018 #ifndef _WIN32_WCE
1019 if(main_menu_handle)
1020 CheckMenuItem(main_menu_handle, (UINT)wParam, MF_CHECKED);
1021 #endif
1022 if(tray_menu_handle)
1023 CheckMenuItem(tray_menu_handle, (UINT)wParam, MF_CHECKED);
1024 message_box(section->help, MB_ICONINFORMATION);
1025 }
1026 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_SECTIONS]);
1027 }
1028
1029 /**************************************** options callbacks */
1030
1031 void ui_config_reloaded(void) {
1032 if(!hwnd) /* NT service */
1033 return; /* not supported */
1034 PostMessage(hwnd, WM_VALID_CONFIG, 0, 0);
1035 }
1036
1037 ICON_IMAGE load_icon_default(ICON_TYPE type) {
1038 WORD idi;
1039 ICON_IMAGE img;
1040
1041 if(!hwnd) /* NT service */
1042 return NULL; /* not supported */
1043 switch(type) {
1044 case ICON_ACTIVE:
1045 idi=IDI_STUNNEL_ACTIVE;
1046 break;
1047 case ICON_ERROR:
1048 idi=IDI_STUNNEL_ERROR;
1049 break;
1050 case ICON_IDLE:
1051 idi=IDI_STUNNEL_IDLE;
1052 break;
1053 default:
1054 return NULL;
1055 }
1056 img=LoadImage(ghInst, MAKEINTRESOURCE(idi), IMAGE_ICON,
1057 GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
1058 return DuplicateIcon(NULL, img);
1059 }
1060
1061 ICON_IMAGE load_icon_file(const char *name) {
1062 LPTSTR tname;
1063 ICON_IMAGE icon;
1064
1065 if(!hwnd) /* NT service */
1066 return NULL; /* not supported */
1067 tname=str2tstr((LPSTR)name);
1068 #ifndef _WIN32_WCE
1069 icon=LoadImage(NULL, tname, IMAGE_ICON, GetSystemMetrics(SM_CXSMICON),
1070 GetSystemMetrics(SM_CYSMICON), LR_LOADFROMFILE);
1071 #else
1072 /* TODO: Implement a WCE version of LoadImage() */
1073 /* icon=wceLoadIconFromFile(tname); */
1074 ui_new_log("Loading image from file not implemented on WCE");
1075 icon=NULL;
1076 #endif
1077 str_free(tname);
1078 return icon;
1079 }
1080
1081 /**************************************** client callbacks */
1082
1083 void ui_new_chain(const unsigned section_number) {
1084 if(!hwnd) /* NT service */
1085 return; /* not supported */
1086 PostMessage(hwnd, WM_NEW_CHAIN, section_number, 0);
1087 }
1088
1089 void ui_clients(const long num) {
1090 if(cmdline.service) { /* forward the number of connections to the connected client */
1091 char *result;
1092
1093 result=control_pipe_call(pipe_name_ui, "connections %d", num);
1094 str_free(result);
1095 }
1096 }
1097
1098 /**************************************** s_log callbacks */
1099
1100 void message_box(LPCTSTR text, const UINT type) {
1101 if(cmdline.quiet)
1102 return;
1103 MessageBox(hwnd, text, win32_name, type);
1104 }
1105
1106 void ui_new_log(const char *line) {
1107 if(cmdline.service) { /* forward the log to the connected client */
1108 char *result;
1109
1110 result=control_pipe_call(pipe_name_ui, "log %s", line);
1111 str_free(result);
1112 } else if(hwnd) { /* GUI mode */
1113 LPTSTR txt;
1114
1115 txt=str2tstr(line);
1116 log_push(txt);
1117 str_free(txt);
1118 }
1119 }
1120
1121 /**************************************** ctx callbacks */
1122
1123 int ui_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
1124 int len;
1125
1126 (void)rwflag; /* squash the unused parameter warning */
1127 (void)userdata; /* squash the unused parameter warning */
1128 if(!hwnd) /* NT service */
1129 return 0; /* not supported */
1130 if(!DialogBox(ghInst, TEXT("PassBox"), hwnd, (DLGPROC)pass_proc))
1131 return 0; /* dialog cancelled or failed */
1132 len=(int)strlen(ui_pass);
1133 if(len<0 || size<0) /* the API uses signed integers */
1134 return 0;
1135 if(len>size) /* truncate the returned data if needed */
1136 len=size;
1137 memcpy(buf, ui_pass, (size_t)len);
1138 memset(ui_pass, 0, sizeof ui_pass);
1139 return len;
1140 }
1141
1142 #if !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L
1143
1144 NOEXPORT int pin_cb(UI *ui, UI_STRING *uis) {
1145 if(!DialogBox(ghInst, TEXT("PassBox"), hwnd, (DLGPROC)pass_proc))
1146 return 0; /* dialog cancelled or failed */
1147 UI_set_result(ui, uis, ui_pass);
1148 memset(ui_pass, 0, sizeof ui_pass);
1149 return 1;
1150 }
1151
1152 int (*ui_get_opener(void)) (UI *) {
1153 return NULL;
1154 }
1155
1156 int (*ui_get_writer(void)) (UI *, UI_STRING *) {
1157 return NULL;
1158 }
1159
1160 int (*ui_get_reader(void)) (UI *, UI_STRING *) {
1161 return hwnd ? pin_cb : NULL; /* only allow for UI in GUI mode */
1162 }
1163
1164 int (*ui_get_closer(void)) (UI *) {
1165 return NULL;
1166 }
1167
1168 #endif /* !defined(OPENSSL_NO_ENGINE) || OPENSSL_VERSION_NUMBER>=0x10101000L */
1169
1170 /**************************************** log handling */
1171
1172 NOEXPORT void log_save() {
1173 TCHAR file_name[MAX_PATH];
1174 OPENFILENAME ofn;
1175 LPTSTR txt;
1176 LPSTR str;
1177
1178 ZeroMemory(&ofn, sizeof ofn);
1179 file_name[0]='\0';
1180
1181 ofn.lStructSize=sizeof ofn;
1182 ofn.hwndOwner=hwnd;
1183 ofn.lpstrFilter=TEXT("Log Files (*.log)\0*.log\0All Files (*.*)\0*.*\0\0");
1184 ofn.lpstrFile=file_name;
1185 ofn.nMaxFile=MAX_PATH;
1186 ofn.lpstrDefExt=TEXT("LOG");
1187 ofn.lpstrInitialDir=TEXT(".");
1188
1189 ofn.lpstrTitle=TEXT("Save Log");
1190 ofn.Flags=OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY|
1191 OFN_OVERWRITEPROMPT;
1192 if(!GetSaveFileName(&ofn))
1193 return;
1194
1195 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_WIN_LOG]);
1196 txt=log_txt(); /* need to convert the result to UTF-8 */
1197 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_WIN_LOG]);
1198 str=tstr2str(txt);
1199 str_free(txt);
1200 text_file_create(file_name, str);
1201 str_free(str);
1202 }
1203
1204 NOEXPORT void log_push(LPCTSTR txt) {
1205 struct LIST *curr;
1206 size_t txt_len;
1207 static size_t log_len=0;
1208
1209 txt_len=_tcslen(txt);
1210 curr=str_alloc_detached(sizeof(struct LIST)+txt_len*sizeof(TCHAR));
1211 curr->len=txt_len;
1212 _tcscpy(curr->txt, txt);
1213 curr->next=NULL;
1214
1215 /* this critical section is performance critical */
1216 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_WIN_LOG]);
1217 if(tail)
1218 tail->next=curr;
1219 tail=curr;
1220 if(!head)
1221 head=tail;
1222 log_len++;
1223 new_logs=TRUE;
1224 if(log_len>LOG_LINES) {
1225 curr=head;
1226 head=head->next;
1227 log_len--;
1228 removed_logs++;
1229 } else {
1230 curr=NULL;
1231 }
1232 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_WIN_LOG]);
1233
1234 str_free(curr);
1235 }
1236
1237 NOEXPORT void log_update(void) {
1238 LPTSTR txt;
1239 int offset;
1240
1241 if(!visible || Button_GetCheck(pause_handle))
1242 return;
1243
1244 /* retrieve the new edit control text */
1245 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_WIN_LOG]);
1246 if(new_logs) {
1247 txt=log_txt();
1248 new_logs=FALSE;
1249 offset=removed_logs;
1250 removed_logs=0;
1251 } else {
1252 txt=NULL;
1253 offset=0; /* only needed to avoid a warning in MSVC */
1254 }
1255 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_WIN_LOG]);
1256
1257 if(txt) {
1258 int cur_pos, max_pos;
1259 WPARAM vscroll_param;
1260
1261 /* update the text and scroll it without flickering */
1262 SendMessage(edit_handle, WM_SETREDRAW, (WPARAM)FALSE, (LPARAM)0);
1263 cur_pos=GetScrollPos(edit_handle, SB_VERT);
1264 SendMessage(edit_handle, WM_VSCROLL, (WPARAM)SB_BOTTOM, (LPARAM)0);
1265 max_pos=GetScrollPos(edit_handle, SB_VERT);
1266 SetWindowText(edit_handle, txt);
1267 str_free(txt);
1268 /* stick to the bottom, otherwise scroll up if lines were removed */
1269 vscroll_param=cur_pos==max_pos ? (WPARAM)SB_BOTTOM :
1270 MAKEWPARAM(SB_THUMBPOSITION, cur_pos<offset ? 0 : cur_pos-offset);
1271 SendMessage(edit_handle, WM_VSCROLL, vscroll_param, (LPARAM)0);
1272 SendMessage(edit_handle, WM_SETREDRAW, (WPARAM)TRUE, (LPARAM)0);
1273
1274 /* redraw the affected areas of the edit control */
1275 if(cur_pos==max_pos || cur_pos<offset) /* visible text has changed */
1276 UpdateWindow(edit_handle);
1277 else /* only update the vertical scrollbar */
1278 SetScrollPos(edit_handle, SB_VERT, cur_pos-offset, TRUE);
1279 }
1280 }
1281
1282 NOEXPORT LPTSTR log_txt(void) {
1283 LPTSTR buff;
1284 size_t ptr=0, len=0;
1285 struct LIST *curr;
1286
1287 for(curr=head; curr; curr=curr->next)
1288 len+=curr->len+2; /* +2 for trailing '\r\n' */
1289 buff=str_alloc((len+1)*sizeof(TCHAR)); /* +1 for trailing '\0' */
1290 for(curr=head; curr; curr=curr->next) {
1291 memcpy(buff+ptr, curr->txt, curr->len*sizeof(TCHAR));
1292 ptr+=curr->len;
1293 if(curr->next) {
1294 buff[ptr++]=TEXT('\r');
1295 buff[ptr++]=TEXT('\n');
1296 }
1297 }
1298 buff[ptr]=TEXT('\0');
1299 return buff;
1300 }
1301
1302 /**************************************** control pipe */
1303
1304 /* build a pipe file name from the configuration file name */
1305 NOEXPORT void control_pipe_names() {
1306 char *pipe_name_txt, *text;
1307
1308 if(cmdline.config_file) {
1309 unsigned char hash_bin[SHA256_DIGEST_LENGTH];
1310 char hash_txt[2*SHA256_DIGEST_LENGTH+1];
1311
1312 /* SHA256 is only used here to prevent collisions, and not for security */
1313 SHA256((unsigned char *)cmdline.config_file, strlen(cmdline.config_file), hash_bin);
1314 bin2hexstring(hash_bin, sizeof hash_bin, hash_txt, sizeof hash_txt);
1315 pipe_name_txt=str_printf("\\\\.\\pipe\\%s", hash_txt);
1316 } else {
1317 pipe_name_txt=str_dup("\\\\.\\pipe\\stunnel-fallback");
1318 }
1319 text=str_printf("%s-ui", pipe_name_txt);
1320 pipe_name_ui=str2tstr(text);
1321 str_free(text);
1322 text=str_printf("%s-service", pipe_name_txt);
1323 pipe_name_service=str2tstr(text);
1324 str_free(text);
1325 str_free(pipe_name_txt);
1326 }
1327
1328 /* attempt to send a command to an already running stunnel */
1329 NOEXPORT int control_pipe_client() {
1330 char *result=NULL;
1331
1332 if(cmdline.exit || cmdline.reload || cmdline.reopen) {
1333 if(cmdline.exit)
1334 result=control_pipe_call(pipe_name_service, "signal %u", SIGNAL_TERMINATE);
1335 else if(cmdline.reload)
1336 result=control_pipe_call(pipe_name_service, "signal %u", SIGNAL_RELOAD_CONFIG);
1337 else if(cmdline.reopen)
1338 result=control_pipe_call(pipe_name_service, "signal %u", SIGNAL_REOPEN_LOG);
1339 if(!result) {
1340 message_box(TEXT("The target stunnel was not found"), MB_ICONERROR);
1341 return 1; /* terminate this instance */
1342 }
1343 if(strcasecmp(result, "succeeded")) {
1344 message_box(TEXT("Request failed"), MB_ICONERROR);
1345 str_free(result);
1346 return 1; /* terminate this instance */
1347 }
1348 message_box(TEXT("Request succeeded"), MB_ICONINFORMATION);
1349 str_free(result);
1350 return 1; /* terminate this instance */
1351 }
1352 result=control_pipe_call(pipe_name_service, "connect");
1353 if(!result)
1354 return 0; /* proceed with GUI initialization */
1355 if(!is_prefix(result, "service ")) {
1356 str_free(result);
1357 return 1; /* terminate this instance */
1358 }
1359 num_clients=atol(result+8);
1360 str_free(result);
1361
1362 nt_service_client=TRUE;
1363 sthreads_init(); /* required for locking to work */
1364 if(control_pipe_server(pipe_name_ui))
1365 return 1; /* a control pipe ui already exists or failed */
1366 gui_init();
1367 win32_name=TEXT("stunnel ") TEXT(STUNNEL_VERSION) TEXT(" on ")
1368 TEXT(STUNNEL_PLATFORM) TEXT(" (NT service client)");
1369 SetWindowText(hwnd, win32_name);
1370 #ifndef _WIN32_WCE
1371 EnableMenuItem(main_menu_handle, IDM_REOPEN_LOG, MF_ENABLED);
1372 #endif
1373 if(tray_menu_handle)
1374 EnableMenuItem(tray_menu_handle, IDM_REOPEN_LOG, MF_ENABLED);
1375 ShowWindow(hwnd, SW_SHOWNORMAL); /* show window */
1376 SetForegroundWindow(hwnd); /* bring on top */
1377 /* create a UI pipe thread for accepting logs */
1378 gui_loop();
1379 return 0; /* terminate this instance */
1380 }
1381
1382 /* create a new control pipe server */
1383 NOEXPORT int control_pipe_server(LPTSTR pipe_name) {
1384 char *result;
1385 HANDLE thread;
1386
1387 result=control_pipe_call(pipe_name, "connect");
1388 if(result) { /* a control pipe server already exists */
1389 str_free(result);
1390 return 1;
1391 }
1392 thread=(HANDLE)_beginthreadex(NULL, DEFAULT_STACK_SIZE,
1393 control_pipe_server_thread, pipe_name, 0, NULL);
1394 if(!thread) {
1395 message_box(TEXT("Failed to create a control pipe server"), MB_ICONERROR);
1396 return 1;
1397 }
1398 CloseHandle(thread);
1399 return 0;
1400 }
1401
1402 #define MSG_SIZE 256
1403
1404 NOEXPORT unsigned __stdcall control_pipe_server_thread(void *arg) {
1405 LPTSTR pipe_name=arg;
1406 SECURITY_ATTRIBUTES sa;
1407
1408 tls_alloc(NULL, NULL, "control server");
1409
1410 /* initialize security attributes */
1411 sa.nLength=sizeof(SECURITY_ATTRIBUTES);
1412 sa.bInheritHandle=FALSE;
1413 sa.lpSecurityDescriptor=NULL;
1414 if(ConvertStringSecurityDescriptorToSecurityDescriptor(
1415 TEXT("D:") /* discretionary ACL */
1416 TEXT("(D;OICI;GA;;;BG)") /* deny access to Built-in Guests */
1417 TEXT("(D;OICI;GA;;;AN)") /* deny access to Anonymous Logon */
1418 TEXT("(A;OICI;GRGW;;;AU)"), /* allow read/write to Authenticated Users */
1419 SDDL_REVISION_1, &sa.lpSecurityDescriptor, NULL)) {
1420 /* spawn new threads for incoming client connections */
1421 for(;;) {
1422 BOOL connected;
1423 HANDLE pipe=CreateNamedPipe(pipe_name, PIPE_ACCESS_DUPLEX,
1424 PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT,
1425 PIPE_UNLIMITED_INSTANCES, MSG_SIZE, MSG_SIZE, 3000, &sa);
1426 if(pipe==INVALID_HANDLE_VALUE) {
1427 message_box(TEXT("Failed to create a control pipe"), MB_ICONERROR);
1428 break;
1429 }
1430 connected=ConnectNamedPipe(pipe, NULL);
1431 if(!connected)
1432 connected=(GetLastError()==ERROR_PIPE_CONNECTED);
1433 if(connected) {
1434 HANDLE thread=(HANDLE)_beginthreadex(NULL, DEFAULT_STACK_SIZE,
1435 control_pipe_instance_thread, pipe, 0, NULL);
1436 if(thread)
1437 CloseHandle(thread);
1438 } else {
1439 CloseHandle(pipe);
1440 }
1441 }
1442 } else {
1443 message_box(TEXT("Failed to create a security descriptor"), MB_ICONERROR);
1444 }
1445
1446 if(nt_service_client && hwnd)
1447 PostMessage(hwnd, WM_TERMINATE, 0, 0); /* terminate GUI */
1448 tls_cleanup();
1449 _endthreadex(0);
1450 return 0;
1451 }
1452
1453 NOEXPORT unsigned __stdcall control_pipe_instance_thread(void *arg) {
1454 HANDLE pipe=arg;
1455 char *message;
1456
1457 tls_alloc(NULL, NULL, "control instance");
1458
1459 /* process incoming data */
1460 message=control_pipe_recv(pipe);
1461 if(message) {
1462 if(hwnd) { /* UI is available */
1463 if(is_prefix(message, "log ")) {
1464 control_pipe_send(pipe, "succeeded");
1465 ui_new_log(message+4);
1466 } else if(is_prefix(message, "connections ")) {
1467 control_pipe_send(pipe, "succeeded");
1468 num_clients=atol(message+12);
1469 } else if(is_prefix(message, "signal ")) {
1470 control_pipe_send(pipe, "succeeded");
1471 gui_signal_post((uint8_t)atoi(message+7));
1472 } else if(!strcasecmp(message, "connect")) {
1473 control_pipe_send(pipe, "succeeded");
1474 ShowWindow(hwnd, SW_SHOWNORMAL); /* show window */
1475 SetForegroundWindow(hwnd); /* bring on top */
1476 } else if(!strcasecmp(message, "terminate")) {
1477 control_pipe_send(pipe, "succeeded");
1478 PostMessage(hwnd, WM_TERMINATE, 0, 0); /* terminate GUI */
1479 } else { /* ignore unknown messages */
1480 control_pipe_send(pipe, "ignored");
1481 }
1482 } else if(cmdline.service) { /* NT service */
1483 if(is_prefix(message, "signal ")) {
1484 control_pipe_send(pipe, "succeeded");
1485 signal_post((uint8_t)atoi(message+7));
1486 } else if(!strcasecmp(message, "connect")) {
1487 control_pipe_send(pipe, "service %d", num_clients);
1488 } else { /* ignore unknown messages */
1489 control_pipe_send(pipe, "ignored");
1490 }
1491 } else {
1492 control_pipe_send(pipe, "failed");
1493 }
1494 str_free(message);
1495 }
1496 CloseHandle(pipe);
1497 tls_cleanup();
1498 _endthreadex(0);
1499 return 0;
1500 }
1501
1502 NOEXPORT int control_pipe_send(HANDLE pipe, const char *format, ...) {
1503 va_list ap;
1504 char *send_buf;
1505 BOOL success;
1506 DWORD send_len, sent_len;
1507
1508 va_start(ap, format);
1509 send_buf=str_vprintf(format, ap);
1510 va_end(ap);
1511 send_len=(DWORD)strlen(send_buf);
1512 success=WriteFile(pipe, send_buf, send_len, &sent_len, NULL);
1513 str_free(send_buf);
1514 return !success || sent_len!=send_len;
1515 }
1516
1517 NOEXPORT char *control_pipe_recv(HANDLE pipe) {
1518 char recv_buf[MSG_SIZE+1];
1519 BOOL success;
1520 DWORD recv_len;
1521
1522 success=ReadFile(pipe, recv_buf, MSG_SIZE, &recv_len, NULL);
1523 if(!success || !recv_len)
1524 return NULL;
1525 recv_buf[recv_len]='\0'; /* null-terminate the received message */
1526 return str_dup(recv_buf);
1527 }
1528
1529 NOEXPORT char *control_pipe_call(LPTSTR name, const char *format, ...) {
1530 va_list ap;
1531 char recv_buf[MSG_SIZE+1], *send_buf;
1532 BOOL success;
1533 DWORD send_len, recv_len;
1534
1535 va_start(ap, format);
1536 send_buf=str_vprintf(format, ap);
1537 va_end(ap);
1538 send_len=(DWORD)strlen(send_buf);
1539 success=CallNamedPipe(name,
1540 send_buf, send_len,
1541 recv_buf, MSG_SIZE,
1542 &recv_len, 3000);
1543 str_free(send_buf);
1544 if(!success || !recv_len)
1545 return NULL;
1546 recv_buf[recv_len]='\0'; /* null-terminate the message */
1547 return str_dup(recv_buf);
1548 }
1549
1550 /**************************************** windows service */
1551
1552 #ifndef _WIN32_WCE
1553
1554 NOEXPORT int service_initialize(void) {
1555 SERVICE_TABLE_ENTRY serviceTable[]={{0, 0}, {0, 0}};
1556
1557 serviceTable[0].lpServiceName=SERVICE_NAME;
1558 serviceTable[0].lpServiceProc=service_main;
1559 if(!StartServiceCtrlDispatcher(serviceTable)) {
1560 error_box(TEXT("StartServiceCtrlDispatcher"));
1561 return 1;
1562 }
1563 return 0; /* NT service started */
1564 }
1565
1566 #define DESCR_LEN 256
1567
1568 NOEXPORT int service_install() {
1569 SC_HANDLE scm, service;
1570 TCHAR stunnel_exe_path[MAX_PATH];
1571 LPTSTR service_path;
1572 TCHAR descr_str[DESCR_LEN];
1573 SERVICE_DESCRIPTION descr;
1574
1575 scm=OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
1576 if(!scm) {
1577 error_box(TEXT("OpenSCManager"));
1578 return 1;
1579 }
1580 GetModuleFileName(0, stunnel_exe_path, MAX_PATH);
1581 service_path=str_tprintf(TEXT("\"%s\" -service %s"),
1582 stunnel_exe_path, params_get());
1583 service=CreateService(scm, SERVICE_NAME, SERVICE_DISPLAY_NAME,
1584 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
1585 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, service_path,
1586 NULL, NULL, TEXT("TCPIP\0"), NULL, NULL);
1587 if(!service) {
1588 error_box(TEXT("CreateService"));
1589 str_free(service_path);
1590 CloseServiceHandle(scm);
1591 return 1;
1592 }
1593 str_free(service_path);
1594 if(LoadString(ghInst, IDS_SERVICE_DESC, descr_str, DESCR_LEN)) {
1595 descr.lpDescription=descr_str;
1596 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &descr);
1597 }
1598 message_box(TEXT("Service installed"), MB_ICONINFORMATION);
1599 CloseServiceHandle(service);
1600 CloseServiceHandle(scm);
1601 return 0;
1602 }
1603
1604 NOEXPORT int service_uninstall(void) {
1605 SC_HANDLE scm, service;
1606 SERVICE_STATUS service_status;
1607
1608 scm=OpenSCManager(0, 0, SC_MANAGER_CONNECT);
1609 if(!scm) {
1610 error_box(TEXT("OpenSCManager"));
1611 return 1;
1612 }
1613 service=OpenService(scm, SERVICE_NAME, SERVICE_QUERY_STATUS|DELETE);
1614 if(!service) {
1615 error_box(TEXT("OpenService"));
1616 CloseServiceHandle(scm);
1617 return 1;
1618 }
1619 if(!QueryServiceStatus(service, &service_status)) {
1620 error_box(TEXT("QueryServiceStatus"));
1621 CloseServiceHandle(service);
1622 CloseServiceHandle(scm);
1623 return 1;
1624 }
1625 if(service_status.dwCurrentState!=SERVICE_STOPPED) {
1626 message_box(TEXT("The service is still running"), MB_ICONERROR);
1627 CloseServiceHandle(service);
1628 CloseServiceHandle(scm);
1629 return 1;
1630 }
1631 if(!DeleteService(service)) {
1632 error_box(TEXT("DeleteService"));
1633 CloseServiceHandle(service);
1634 CloseServiceHandle(scm);
1635 return 1;
1636 }
1637 message_box(TEXT("Service uninstalled"), MB_ICONINFORMATION);
1638 CloseServiceHandle(service);
1639 CloseServiceHandle(scm);
1640 return 0;
1641 }
1642
1643 NOEXPORT int service_start(void) {
1644 SC_HANDLE scm, service;
1645 SERVICE_STATUS service_status;
1646
1647 scm=OpenSCManager(0, 0, SC_MANAGER_CONNECT);
1648 if(!scm) {
1649 error_box(TEXT("OpenSCManager"));
1650 return 1;
1651 }
1652 service=OpenService(scm, SERVICE_NAME, SERVICE_QUERY_STATUS|SERVICE_START);
1653 if(!service) {
1654 error_box(TEXT("OpenService"));
1655 CloseServiceHandle(scm);
1656 return 1;
1657 }
1658 if(!StartService(service, 0, NULL)) {
1659 error_box(TEXT("StartService"));
1660 CloseServiceHandle(service);
1661 CloseServiceHandle(scm);
1662 return 1;
1663 }
1664 do {
1665 Sleep(1000);
1666 if(!QueryServiceStatus(service, &service_status)) {
1667 error_box(TEXT("QueryServiceStatus"));
1668 CloseServiceHandle(service);
1669 CloseServiceHandle(scm);
1670 return 1;
1671 }
1672 } while(service_status.dwCurrentState==SERVICE_START_PENDING);
1673 if(service_status.dwCurrentState!=SERVICE_RUNNING) {
1674 message_box(TEXT("Failed to start service"), MB_ICONERROR);
1675 CloseServiceHandle(service);
1676 CloseServiceHandle(scm);
1677 return 1;
1678 }
1679 message_box(TEXT("Service started"), MB_ICONINFORMATION);
1680 CloseServiceHandle(service);
1681 CloseServiceHandle(scm);
1682 return 0;
1683 }
1684
1685 NOEXPORT int service_stop(void) {
1686 SC_HANDLE scm, service;
1687 SERVICE_STATUS service_status;
1688
1689 scm=OpenSCManager(0, 0, SC_MANAGER_CONNECT);
1690 if(!scm) {
1691 error_box(TEXT("OpenSCManager"));
1692 return 1;
1693 }
1694 service=OpenService(scm, SERVICE_NAME, SERVICE_QUERY_STATUS|SERVICE_STOP);
1695 if(!service) {
1696 error_box(TEXT("OpenService"));
1697 CloseServiceHandle(scm);
1698 return 1;
1699 }
1700 if(!QueryServiceStatus(service, &service_status)) {
1701 error_box(TEXT("QueryServiceStatus"));
1702 CloseServiceHandle(service);
1703 CloseServiceHandle(scm);
1704 return 1;
1705 }
1706 if(service_status.dwCurrentState==SERVICE_STOPPED) {
1707 message_box(TEXT("The service is already stopped"), MB_ICONERROR);
1708 CloseServiceHandle(service);
1709 CloseServiceHandle(scm);
1710 return 1;
1711 }
1712 if(!ControlService(service, SERVICE_CONTROL_STOP, &service_status)) {
1713 error_box(TEXT("ControlService"));
1714 CloseServiceHandle(service);
1715 CloseServiceHandle(scm);
1716 return 1;
1717 }
1718 do {
1719 Sleep(1000);
1720 if(!QueryServiceStatus(service, &service_status)) {
1721 error_box(TEXT("QueryServiceStatus"));
1722 CloseServiceHandle(service);
1723 CloseServiceHandle(scm);
1724 return 1;
1725 }
1726 } while(service_status.dwCurrentState!=SERVICE_STOPPED);
1727 message_box(TEXT("Service stopped"), MB_ICONINFORMATION);
1728 CloseServiceHandle(service);
1729 CloseServiceHandle(scm);
1730 return 0;
1731 }
1732
1733 NOEXPORT void WINAPI service_main(DWORD argc, LPTSTR* argv) {
1734 (void)argc; /* squash the unused parameter warning */
1735 (void)argv; /* squash the unused parameter warning */
1736
1737 tls_alloc(NULL, NULL, "service"); /* new thread-local storage */
1738
1739 /* initialise service status */
1740 serviceStatus.dwServiceType=SERVICE_WIN32;
1741 serviceStatus.dwCurrentState=SERVICE_STOPPED;
1742 serviceStatus.dwControlsAccepted=0;
1743 serviceStatus.dwWin32ExitCode=NO_ERROR;
1744 serviceStatus.dwServiceSpecificExitCode=NO_ERROR;
1745 serviceStatus.dwCheckPoint=0;
1746 serviceStatus.dwWaitHint=0;
1747
1748 serviceStatusHandle=
1749 RegisterServiceCtrlHandler(SERVICE_NAME, control_handler);
1750
1751 if(serviceStatusHandle) {
1752 char *result;
1753
1754 /* service is starting */
1755 serviceStatus.dwCurrentState=SERVICE_START_PENDING;
1756 SetServiceStatus(serviceStatusHandle, &serviceStatus);
1757
1758 /* running */
1759 serviceStatus.dwControlsAccepted|=
1760 (SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN);
1761 serviceStatus.dwCurrentState=SERVICE_RUNNING;
1762 SetServiceStatus(serviceStatusHandle, &serviceStatus);
1763
1764 /* start the main loop */
1765 main_init();
1766 if(!main_configure(cmdline.config_file, NULL))
1767 daemon_loop();
1768 result=control_pipe_call(pipe_name_ui, "terminate");
1769 str_free(result);
1770 main_cleanup();
1771
1772 /* service was stopped */
1773 serviceStatus.dwCurrentState=SERVICE_STOP_PENDING;
1774 SetServiceStatus(serviceStatusHandle, &serviceStatus);
1775
1776 /* service is now stopped */
1777 serviceStatus.dwControlsAccepted&=
1778 (DWORD)~(SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN);
1779 serviceStatus.dwCurrentState=SERVICE_STOPPED;
1780 SetServiceStatus(serviceStatusHandle, &serviceStatus);
1781 }
1782 }
1783
1784 NOEXPORT void WINAPI control_handler(DWORD controlCode) {
1785 switch(controlCode) {
1786 case SERVICE_CONTROL_INTERROGATE:
1787 break;
1788 case SERVICE_CONTROL_SHUTDOWN:
1789 case SERVICE_CONTROL_STOP:
1790 serviceStatus.dwCurrentState=SERVICE_STOP_PENDING;
1791 SetServiceStatus(serviceStatusHandle, &serviceStatus);
1792 signal_post(SIGNAL_TERMINATE);
1793 return;
1794 case SERVICE_CONTROL_PAUSE:
1795 break;
1796 case SERVICE_CONTROL_CONTINUE:
1797 break;
1798 default:
1799 if(controlCode >= 128 && controlCode <= 255)
1800 break; /* user defined control code */
1801 else
1802 break; /* unrecognised control code */
1803 }
1804 SetServiceStatus(serviceStatusHandle, &serviceStatus);
1805 }
1806
1807 #endif /* !defined(_WIN32_WCE) */
1808
1809 /**************************************** helper functions */
1810
1811 NOEXPORT LPTSTR params_get() {
1812 LPTSTR c;
1813 TCHAR s;
1814
1815 c=GetCommandLine();
1816
1817 /* skip executable path */
1818 if(*c==TEXT('\"')) {
1819 s=TEXT('\"');
1820 ++c;
1821 } else {
1822 s=TEXT(' ');
1823 }
1824 for(; *c; ++c)
1825 if(*c==s) {
1826 ++c;
1827 break;
1828 }
1829
1830 /* skip spaces */
1831 while(*c==TEXT(' '))
1832 ++c;
1833
1834 return c; /* return parameters */
1835 }
1836
1837 NOEXPORT int text_file_create(LPTSTR file_name, char *str) {
1838 HANDLE file_handle;
1839 DWORD ignore;
1840
1841 file_handle=CreateFile(file_name, GENERIC_WRITE, 0, NULL,
1842 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1843 if(file_handle==INVALID_HANDLE_VALUE) {
1844 error_box(TEXT("CreateFile"));
1845 return 1;
1846 }
1847 if(!WriteFile(file_handle, str, (DWORD)strlen(str), &ignore, NULL)) {
1848 CloseHandle(file_handle);
1849 error_box(TEXT("WriteFile"));
1850 return 1;
1851 }
1852 CloseHandle(file_handle);
1853 return 0;
1854 }
1855
1856 /* a wrapper is needed for GUI (not for NT service), as signal_pipe only
1857 * becomes active after the first valid configuration file is loaded */
1858 NOEXPORT void gui_signal_post(uint8_t sig) {
1859 if(nt_service_client) {
1860 char *result;
1861
1862 /* forward the signal to the connected server */
1863 result=control_pipe_call(pipe_name_service, "signal %u", sig);
1864 str_free(result);
1865 } else if(num_clients>=0) { /* signal_pipe is active */
1866 signal_post(sig);
1867 if(hwnd && sig==SIGNAL_TERMINATE) { /* forcefully close the GUI */
1868 /* 3 seconds for the main and client threads to save the final logs */
1869 if(WaitForSingleObject(main_terminated, 3000) != WAIT_OBJECT_0)
1870 PostMessage(hwnd, WM_TERMINATE, 0, 0); /* terminate GUI */
1871 }
1872 } else { /* no valid configuration file is loaded */
1873 switch(sig) {
1874 case SIGNAL_TERMINATE:
1875 PostMessage(hwnd, WM_TERMINATE, 0, 0); /* terminate GUI */
1876 break;
1877 case SIGNAL_RELOAD_CONFIG:
1878 SetEvent(config_ready); /* unlock daemon_thread() */
1879 break;
1880 default: /* ignore */
1881 break;
1882 }
1883 }
1884 }
1885
1886 NOEXPORT void error_box(LPCTSTR text) {
1887 LPTSTR errmsg, fullmsg;
1888 DWORD dw;
1889
1890 dw=GetLastError();
1891 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1892 NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1893 (LPTSTR)&errmsg, 0, NULL);
1894 fullmsg=str_tprintf(TEXT("%s: error %ld: %s"), text, dw, errmsg);
1895 LocalFree(errmsg);
1896 message_box(fullmsg, MB_ICONERROR);
1897 str_free(fullmsg);
1898 }
1899
1900 /* end of ui_win_gui.c */