1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.haxx.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 ***************************************************************************/
22 #include "server_setup.h"
23
24 #ifdef HAVE_SIGNAL_H
25 #include <signal.h>
26 #endif
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
29 #endif
30 #ifdef _XOPEN_SOURCE_EXTENDED
31 /* This define is "almost" required to build on HPUX 11 */
32 #include <arpa/inet.h>
33 #endif
34 #ifdef HAVE_NETDB_H
35 #include <netdb.h>
36 #endif
37 #ifdef HAVE_POLL_H
38 #include <poll.h>
39 #elif defined(HAVE_SYS_POLL_H)
40 #include <sys/poll.h>
41 #endif
42 #ifdef __MINGW32__
43 #include <w32api.h>
44 #endif
45
46 #define ENABLE_CURLX_PRINTF
47 /* make the curlx header define all printf() functions to use the curlx_*
48 versions instead */
49 #include "curlx.h" /* from the private lib dir */
50 #include "getpart.h"
51 #include "util.h"
52 #include "timeval.h"
53
54 #ifdef USE_WINSOCK
55 #undef EINTR
56 #define EINTR 4 /* errno.h value */
57 #undef EINVAL
58 #define EINVAL 22 /* errno.h value */
59 #endif
60
61 /* MinGW with w32api version < 3.6 declared in6addr_any as extern,
62 but lacked the definition */
63 #if defined(ENABLE_IPV6) && defined(__MINGW32__)
64 #if (__W32API_MAJOR_VERSION < 3) || \
65 ((__W32API_MAJOR_VERSION == 3) && (__W32API_MINOR_VERSION < 6))
66 const struct in6_addr in6addr_any = {{ IN6ADDR_ANY_INIT }};
67 #endif /* w32api < 3.6 */
68 #endif /* ENABLE_IPV6 && __MINGW32__*/
69
70 static struct timeval tvnow(void);
71
72 /* This function returns a pointer to STATIC memory. It converts the given
73 * binary lump to a hex formatted string usable for output in logs or
74 * whatever.
75 */
data_to_hex(char * data,size_t len)76 char *data_to_hex(char *data, size_t len)
77 {
78 static char buf[256*3];
79 size_t i;
80 char *optr = buf;
81 char *iptr = data;
82
83 if(len > 255)
84 len = 255;
85
86 for(i = 0; i < len; i++) {
87 if((data[i] >= 0x20) && (data[i] < 0x7f))
88 *optr++ = *iptr++;
89 else {
90 msnprintf(optr, 4, "%%%02x", *iptr++);
91 optr += 3;
92 }
93 }
94 *optr = 0; /* in case no sprintf was used */
95
96 return buf;
97 }
98
logmsg(const char * msg,...)99 void logmsg(const char *msg, ...)
100 {
101 va_list ap;
102 char buffer[2048 + 1];
103 FILE *logfp;
104 struct timeval tv;
105 time_t sec;
106 struct tm *now;
107 char timebuf[20];
108 static time_t epoch_offset;
109 static int known_offset;
110
111 if(!serverlogfile) {
112 fprintf(stderr, "Error: serverlogfile not set\n");
113 return;
114 }
115
116 tv = tvnow();
117 if(!known_offset) {
118 epoch_offset = time(NULL) - tv.tv_sec;
119 known_offset = 1;
120 }
121 sec = epoch_offset + tv.tv_sec;
122 /* !checksrc! disable BANNEDFUNC 1 */
123 now = localtime(&sec); /* not thread safe but we don't care */
124
125 msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld",
126 (int)now->tm_hour, (int)now->tm_min, (int)now->tm_sec,
127 (long)tv.tv_usec);
128
129 va_start(ap, msg);
130 mvsnprintf(buffer, sizeof(buffer), msg, ap);
131 va_end(ap);
132
133 logfp = fopen(serverlogfile, "ab");
134 if(logfp) {
135 fprintf(logfp, "%s %s\n", timebuf, buffer);
136 fclose(logfp);
137 }
138 else {
139 int error = errno;
140 fprintf(stderr, "fopen() failed with error: %d %s\n",
141 error, strerror(error));
142 fprintf(stderr, "Error opening file: %s\n", serverlogfile);
143 fprintf(stderr, "Msg not logged: %s %s\n", timebuf, buffer);
144 }
145 }
146
147 #ifdef WIN32
148 /* use instead of perror() on generic windows */
win32_perror(const char * msg)149 void win32_perror(const char *msg)
150 {
151 char buf[512];
152 DWORD err = SOCKERRNO;
153
154 if(!FormatMessageA((FORMAT_MESSAGE_FROM_SYSTEM |
155 FORMAT_MESSAGE_IGNORE_INSERTS), NULL, err,
156 LANG_NEUTRAL, buf, sizeof(buf), NULL))
157 msnprintf(buf, sizeof(buf), "Unknown error %lu (%#lx)", err, err);
158 if(msg)
159 fprintf(stderr, "%s: ", msg);
160 fprintf(stderr, "%s\n", buf);
161 }
162 #endif /* WIN32 */
163
164 #ifdef USE_WINSOCK
win32_init(void)165 void win32_init(void)
166 {
167 WORD wVersionRequested;
168 WSADATA wsaData;
169 int err;
170
171 wVersionRequested = MAKEWORD(2, 2);
172 err = WSAStartup(wVersionRequested, &wsaData);
173
174 if(err != 0) {
175 perror("Winsock init failed");
176 logmsg("Error initialising winsock -- aborting");
177 exit(1);
178 }
179
180 if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) ||
181 HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested) ) {
182 WSACleanup();
183 perror("Winsock init failed");
184 logmsg("No suitable winsock.dll found -- aborting");
185 exit(1);
186 }
187 }
188
win32_cleanup(void)189 void win32_cleanup(void)
190 {
191 WSACleanup();
192 }
193 #endif /* USE_WINSOCK */
194
195 /* set by the main code to point to where the test dir is */
196 const char *path = ".";
197
test2fopen(long testno)198 FILE *test2fopen(long testno)
199 {
200 FILE *stream;
201 char filename[256];
202 /* first try the alternative, preprocessed, file */
203 msnprintf(filename, sizeof(filename), ALTTEST_DATA_PATH, ".", testno);
204 stream = fopen(filename, "rb");
205 if(stream)
206 return stream;
207
208 /* then try the source version */
209 msnprintf(filename, sizeof(filename), TEST_DATA_PATH, path, testno);
210 stream = fopen(filename, "rb");
211
212 return stream;
213 }
214
215 /*
216 * Portable function used for waiting a specific amount of ms.
217 * Waiting indefinitely with this function is not allowed, a
218 * zero or negative timeout value will return immediately.
219 *
220 * Return values:
221 * -1 = system call error, or invalid timeout value
222 * 0 = specified timeout has elapsed
223 */
wait_ms(int timeout_ms)224 int wait_ms(int timeout_ms)
225 {
226 #if !defined(MSDOS) && !defined(USE_WINSOCK)
227 #ifndef HAVE_POLL_FINE
228 struct timeval pending_tv;
229 #endif
230 struct timeval initial_tv;
231 int pending_ms;
232 #endif
233 int r = 0;
234
235 if(!timeout_ms)
236 return 0;
237 if(timeout_ms < 0) {
238 errno = EINVAL;
239 return -1;
240 }
241 #if defined(MSDOS)
242 delay(timeout_ms);
243 #elif defined(USE_WINSOCK)
244 Sleep(timeout_ms);
245 #else
246 pending_ms = timeout_ms;
247 initial_tv = tvnow();
248 do {
249 int error;
250 #if defined(HAVE_POLL_FINE)
251 r = poll(NULL, 0, pending_ms);
252 #else
253 pending_tv.tv_sec = pending_ms / 1000;
254 pending_tv.tv_usec = (pending_ms % 1000) * 1000;
255 r = select(0, NULL, NULL, NULL, &pending_tv);
256 #endif /* HAVE_POLL_FINE */
257 if(r != -1)
258 break;
259 error = errno;
260 if(error && (error != EINTR))
261 break;
262 pending_ms = timeout_ms - (int)timediff(tvnow(), initial_tv);
263 if(pending_ms <= 0)
264 break;
265 } while(r == -1);
266 #endif /* USE_WINSOCK */
267 if(r)
268 r = -1;
269 return r;
270 }
271
write_pidfile(const char * filename)272 int write_pidfile(const char *filename)
273 {
274 FILE *pidfile;
275 curl_off_t pid;
276
277 pid = (curl_off_t)getpid();
278 pidfile = fopen(filename, "wb");
279 if(!pidfile) {
280 logmsg("Couldn't write pid file: %s %s", filename, strerror(errno));
281 return 0; /* fail */
282 }
283 #if defined(WIN32) || defined(_WIN32)
284 /* store pid + 65536 to avoid conflict with Cygwin/msys PIDs, see also:
285 * - https://cygwin.com/git/?p=newlib-cygwin.git;a=commit; ↵
286 * h=b5e1003722cb14235c4f166be72c09acdffc62ea
287 * - https://cygwin.com/git/?p=newlib-cygwin.git;a=commit; ↵
288 * h=448cf5aa4b429d5a9cebf92a0da4ab4b5b6d23fe
289 */
290 pid += 65536;
291 #endif
292 fprintf(pidfile, "%" CURL_FORMAT_CURL_OFF_T "\n", pid);
293 fclose(pidfile);
294 logmsg("Wrote pid %" CURL_FORMAT_CURL_OFF_T " to %s", pid, filename);
295 return 1; /* success */
296 }
297
298 /* store the used port number in a file */
write_portfile(const char * filename,int port)299 int write_portfile(const char *filename, int port)
300 {
301 FILE *portfile = fopen(filename, "wb");
302 if(!portfile) {
303 logmsg("Couldn't write port file: %s %s", filename, strerror(errno));
304 return 0; /* fail */
305 }
306 fprintf(portfile, "%d\n", port);
307 fclose(portfile);
308 logmsg("Wrote port %d to %s", port, filename);
309 return 1; /* success */
310 }
311
set_advisor_read_lock(const char * filename)312 void set_advisor_read_lock(const char *filename)
313 {
314 FILE *lockfile;
315 int error = 0;
316 int res;
317
318 do {
319 lockfile = fopen(filename, "wb");
320 } while((lockfile == NULL) && ((error = errno) == EINTR));
321 if(lockfile == NULL) {
322 logmsg("Error creating lock file %s error: %d %s",
323 filename, error, strerror(error));
324 return;
325 }
326
327 do {
328 res = fclose(lockfile);
329 } while(res && ((error = errno) == EINTR));
330 if(res)
331 logmsg("Error closing lock file %s error: %d %s",
332 filename, error, strerror(error));
333 }
334
clear_advisor_read_lock(const char * filename)335 void clear_advisor_read_lock(const char *filename)
336 {
337 int error = 0;
338 int res;
339
340 /*
341 ** Log all removal failures. Even those due to file not existing.
342 ** This allows to detect if unexpectedly the file has already been
343 ** removed by a process different than the one that should do this.
344 */
345
346 do {
347 res = unlink(filename);
348 } while(res && ((error = errno) == EINTR));
349 if(res)
350 logmsg("Error removing lock file %s error: %d %s",
351 filename, error, strerror(error));
352 }
353
354
355 /* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
356 its behavior is altered by the current locale. */
raw_toupper(char in)357 static char raw_toupper(char in)
358 {
359 #if !defined(CURL_DOES_CONVERSIONS)
360 if(in >= 'a' && in <= 'z')
361 return (char)('A' + in - 'a');
362 #else
363 switch(in) {
364 case 'a':
365 return 'A';
366 case 'b':
367 return 'B';
368 case 'c':
369 return 'C';
370 case 'd':
371 return 'D';
372 case 'e':
373 return 'E';
374 case 'f':
375 return 'F';
376 case 'g':
377 return 'G';
378 case 'h':
379 return 'H';
380 case 'i':
381 return 'I';
382 case 'j':
383 return 'J';
384 case 'k':
385 return 'K';
386 case 'l':
387 return 'L';
388 case 'm':
389 return 'M';
390 case 'n':
391 return 'N';
392 case 'o':
393 return 'O';
394 case 'p':
395 return 'P';
396 case 'q':
397 return 'Q';
398 case 'r':
399 return 'R';
400 case 's':
401 return 'S';
402 case 't':
403 return 'T';
404 case 'u':
405 return 'U';
406 case 'v':
407 return 'V';
408 case 'w':
409 return 'W';
410 case 'x':
411 return 'X';
412 case 'y':
413 return 'Y';
414 case 'z':
415 return 'Z';
416 }
417 #endif
418
419 return in;
420 }
421
strncasecompare(const char * first,const char * second,size_t max)422 int strncasecompare(const char *first, const char *second, size_t max)
423 {
424 while(*first && *second && max) {
425 if(raw_toupper(*first) != raw_toupper(*second)) {
426 break;
427 }
428 max--;
429 first++;
430 second++;
431 }
432 if(0 == max)
433 return 1; /* they are equal this far */
434
435 return raw_toupper(*first) == raw_toupper(*second);
436 }
437
438 #if defined(WIN32) && !defined(MSDOS)
439
tvnow(void)440 static struct timeval tvnow(void)
441 {
442 /*
443 ** GetTickCount() is available on _all_ Windows versions from W95 up
444 ** to nowadays. Returns milliseconds elapsed since last system boot,
445 ** increases monotonically and wraps once 49.7 days have elapsed.
446 **
447 ** GetTickCount64() is available on Windows version from Windows Vista
448 ** and Windows Server 2008 up to nowadays. The resolution of the
449 ** function is limited to the resolution of the system timer, which
450 ** is typically in the range of 10 milliseconds to 16 milliseconds.
451 */
452 struct timeval now;
453 #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && \
454 (!defined(__MINGW32__) || defined(__MINGW64_VERSION_MAJOR))
455 ULONGLONG milliseconds = GetTickCount64();
456 #else
457 DWORD milliseconds = GetTickCount();
458 #endif
459 now.tv_sec = (long)(milliseconds / 1000);
460 now.tv_usec = (long)((milliseconds % 1000) * 1000);
461 return now;
462 }
463
464 #elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
465
tvnow(void)466 static struct timeval tvnow(void)
467 {
468 /*
469 ** clock_gettime() is granted to be increased monotonically when the
470 ** monotonic clock is queried. Time starting point is unspecified, it
471 ** could be the system start-up time, the Epoch, or something else,
472 ** in any case the time starting point does not change once that the
473 ** system has started up.
474 */
475 struct timeval now;
476 struct timespec tsnow;
477 if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
478 now.tv_sec = tsnow.tv_sec;
479 now.tv_usec = (int)(tsnow.tv_nsec / 1000);
480 }
481 /*
482 ** Even when the configure process has truly detected monotonic clock
483 ** availability, it might happen that it is not actually available at
484 ** run-time. When this occurs simply fallback to other time source.
485 */
486 #ifdef HAVE_GETTIMEOFDAY
487 else
488 (void)gettimeofday(&now, NULL);
489 #else
490 else {
491 now.tv_sec = (long)time(NULL);
492 now.tv_usec = 0;
493 }
494 #endif
495 return now;
496 }
497
498 #elif defined(HAVE_GETTIMEOFDAY)
499
tvnow(void)500 static struct timeval tvnow(void)
501 {
502 /*
503 ** gettimeofday() is not granted to be increased monotonically, due to
504 ** clock drifting and external source time synchronization it can jump
505 ** forward or backward in time.
506 */
507 struct timeval now;
508 (void)gettimeofday(&now, NULL);
509 return now;
510 }
511
512 #else
513
tvnow(void)514 static struct timeval tvnow(void)
515 {
516 /*
517 ** time() returns the value of time in seconds since the Epoch.
518 */
519 struct timeval now;
520 now.tv_sec = (long)time(NULL);
521 now.tv_usec = 0;
522 return now;
523 }
524
525 #endif
526
timediff(struct timeval newer,struct timeval older)527 long timediff(struct timeval newer, struct timeval older)
528 {
529 timediff_t diff = newer.tv_sec-older.tv_sec;
530 if(diff >= (LONG_MAX/1000))
531 return LONG_MAX;
532 else if(diff <= (LONG_MIN/1000))
533 return LONG_MIN;
534 return (long)(newer.tv_sec-older.tv_sec)*1000+
535 (long)(newer.tv_usec-older.tv_usec)/1000;
536 }
537
538 /* do-nothing macro replacement for systems which lack siginterrupt() */
539
540 #ifndef HAVE_SIGINTERRUPT
541 #define siginterrupt(x,y) do {} while(0)
542 #endif
543
544 /* vars used to keep around previous signal handlers */
545
546 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
547
548 #ifdef SIGHUP
549 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
550 #endif
551
552 #ifdef SIGPIPE
553 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
554 #endif
555
556 #ifdef SIGALRM
557 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
558 #endif
559
560 #ifdef SIGINT
561 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
562 #endif
563
564 #ifdef SIGTERM
565 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
566 #endif
567
568 #if defined(SIGBREAK) && defined(WIN32)
569 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
570 #endif
571
572 #ifdef WIN32
573 static DWORD thread_main_id = 0;
574 static HANDLE thread_main_window = NULL;
575 static HWND hidden_main_window = NULL;
576 #endif
577
578 /* var which if set indicates that the program should finish execution */
579 volatile int got_exit_signal = 0;
580
581 /* if next is set indicates the first signal handled in exit_signal_handler */
582 volatile int exit_signal = 0;
583
584 #ifdef WIN32
585 /* event which if set indicates that the program should finish */
586 HANDLE exit_event = NULL;
587 #endif
588
589 /* signal handler that will be triggered to indicate that the program
590 * should finish its execution in a controlled manner as soon as possible.
591 * The first time this is called it will set got_exit_signal to one and
592 * store in exit_signal the signal that triggered its execution.
593 */
exit_signal_handler(int signum)594 static RETSIGTYPE exit_signal_handler(int signum)
595 {
596 int old_errno = errno;
597 logmsg("exit_signal_handler: %d", signum);
598 if(got_exit_signal == 0) {
599 got_exit_signal = 1;
600 exit_signal = signum;
601 #ifdef WIN32
602 if(exit_event)
603 (void)SetEvent(exit_event);
604 #endif
605 }
606 (void)signal(signum, exit_signal_handler);
607 errno = old_errno;
608 }
609
610 #ifdef WIN32
611 /* CTRL event handler for Windows Console applications to simulate
612 * SIGINT, SIGTERM and SIGBREAK on CTRL events and trigger signal handler.
613 *
614 * Background information from MSDN:
615 * SIGINT is not supported for any Win32 application. When a CTRL+C
616 * interrupt occurs, Win32 operating systems generate a new thread
617 * to specifically handle that interrupt. This can cause a single-thread
618 * application, such as one in UNIX, to become multithreaded and cause
619 * unexpected behavior.
620 * [...]
621 * The SIGILL and SIGTERM signals are not generated under Windows.
622 * They are included for ANSI compatibility. Therefore, you can set
623 * signal handlers for these signals by using signal, and you can also
624 * explicitly generate these signals by calling raise. Source:
625 * https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/signal
626 */
ctrl_event_handler(DWORD dwCtrlType)627 static BOOL WINAPI ctrl_event_handler(DWORD dwCtrlType)
628 {
629 int signum = 0;
630 logmsg("ctrl_event_handler: %d", dwCtrlType);
631 switch(dwCtrlType) {
632 #ifdef SIGINT
633 case CTRL_C_EVENT: signum = SIGINT; break;
634 #endif
635 #ifdef SIGTERM
636 case CTRL_CLOSE_EVENT: signum = SIGTERM; break;
637 #endif
638 #ifdef SIGBREAK
639 case CTRL_BREAK_EVENT: signum = SIGBREAK; break;
640 #endif
641 default: return FALSE;
642 }
643 if(signum) {
644 logmsg("ctrl_event_handler: %d -> %d", dwCtrlType, signum);
645 raise(signum);
646 }
647 return TRUE;
648 }
649 /* Window message handler for Windows applications to add support
650 * for graceful process termination via taskkill (without /f) which
651 * sends WM_CLOSE to all Windows of a process (even hidden ones).
652 *
653 * Therefore we create and run a hidden Window in a separate thread
654 * to receive and handle the WM_CLOSE message as SIGTERM signal.
655 */
main_window_proc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)656 static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg,
657 WPARAM wParam, LPARAM lParam)
658 {
659 int signum = 0;
660 if(hwnd == hidden_main_window) {
661 switch(uMsg) {
662 #ifdef SIGTERM
663 case WM_CLOSE: signum = SIGTERM; break;
664 #endif
665 case WM_DESTROY: PostQuitMessage(0); break;
666 }
667 if(signum) {
668 logmsg("main_window_proc: %d -> %d", uMsg, signum);
669 raise(signum);
670 }
671 }
672 return DefWindowProc(hwnd, uMsg, wParam, lParam);
673 }
674 /* Window message queue loop for hidden main window, details see above.
675 */
main_window_loop(LPVOID lpParameter)676 static DWORD WINAPI main_window_loop(LPVOID lpParameter)
677 {
678 WNDCLASS wc;
679 BOOL ret;
680 MSG msg;
681
682 ZeroMemory(&wc, sizeof(wc));
683 wc.lpfnWndProc = (WNDPROC)main_window_proc;
684 wc.hInstance = (HINSTANCE)lpParameter;
685 wc.lpszClassName = TEXT("MainWClass");
686 if(!RegisterClass(&wc)) {
687 perror("RegisterClass failed");
688 return (DWORD)-1;
689 }
690
691 hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"),
692 TEXT("Recv WM_CLOSE msg"),
693 WS_OVERLAPPEDWINDOW,
694 CW_USEDEFAULT, CW_USEDEFAULT,
695 CW_USEDEFAULT, CW_USEDEFAULT,
696 (HWND)NULL, (HMENU)NULL,
697 wc.hInstance, (LPVOID)NULL);
698 if(!hidden_main_window) {
699 perror("CreateWindowEx failed");
700 return (DWORD)-1;
701 }
702
703 do {
704 ret = GetMessage(&msg, NULL, 0, 0);
705 if(ret == -1) {
706 perror("GetMessage failed");
707 return (DWORD)-1;
708 }
709 else if(ret) {
710 if(msg.message == WM_APP) {
711 DestroyWindow(hidden_main_window);
712 }
713 else if(msg.hwnd && !TranslateMessage(&msg)) {
714 DispatchMessage(&msg);
715 }
716 }
717 } while(ret);
718
719 hidden_main_window = NULL;
720 return (DWORD)msg.wParam;
721 }
722 #endif
723
install_signal_handlers(bool keep_sigalrm)724 void install_signal_handlers(bool keep_sigalrm)
725 {
726 #ifdef WIN32
727 /* setup windows exit event before any signal can trigger */
728 exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
729 if(!exit_event)
730 logmsg("cannot create exit event");
731 #endif
732 #ifdef SIGHUP
733 /* ignore SIGHUP signal */
734 old_sighup_handler = signal(SIGHUP, SIG_IGN);
735 if(old_sighup_handler == SIG_ERR)
736 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
737 #endif
738 #ifdef SIGPIPE
739 /* ignore SIGPIPE signal */
740 old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
741 if(old_sigpipe_handler == SIG_ERR)
742 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
743 #endif
744 #ifdef SIGALRM
745 if(!keep_sigalrm) {
746 /* ignore SIGALRM signal */
747 old_sigalrm_handler = signal(SIGALRM, SIG_IGN);
748 if(old_sigalrm_handler == SIG_ERR)
749 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
750 }
751 #else
752 (void)keep_sigalrm;
753 #endif
754 #ifdef SIGINT
755 /* handle SIGINT signal with our exit_signal_handler */
756 old_sigint_handler = signal(SIGINT, exit_signal_handler);
757 if(old_sigint_handler == SIG_ERR)
758 logmsg("cannot install SIGINT handler: %s", strerror(errno));
759 else
760 siginterrupt(SIGINT, 1);
761 #endif
762 #ifdef SIGTERM
763 /* handle SIGTERM signal with our exit_signal_handler */
764 old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
765 if(old_sigterm_handler == SIG_ERR)
766 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
767 else
768 siginterrupt(SIGTERM, 1);
769 #endif
770 #if defined(SIGBREAK) && defined(WIN32)
771 /* handle SIGBREAK signal with our exit_signal_handler */
772 old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
773 if(old_sigbreak_handler == SIG_ERR)
774 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
775 else
776 siginterrupt(SIGBREAK, 1);
777 #endif
778 #ifdef WIN32
779 if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE))
780 logmsg("cannot install CTRL event handler");
781 thread_main_window = CreateThread(NULL, 0,
782 &main_window_loop,
783 (LPVOID)GetModuleHandle(NULL),
784 0, &thread_main_id);
785 if(!thread_main_window || !thread_main_id)
786 logmsg("cannot start main window loop");
787 #endif
788 }
789
restore_signal_handlers(bool keep_sigalrm)790 void restore_signal_handlers(bool keep_sigalrm)
791 {
792 #ifdef SIGHUP
793 if(SIG_ERR != old_sighup_handler)
794 (void)signal(SIGHUP, old_sighup_handler);
795 #endif
796 #ifdef SIGPIPE
797 if(SIG_ERR != old_sigpipe_handler)
798 (void)signal(SIGPIPE, old_sigpipe_handler);
799 #endif
800 #ifdef SIGALRM
801 if(!keep_sigalrm) {
802 if(SIG_ERR != old_sigalrm_handler)
803 (void)signal(SIGALRM, old_sigalrm_handler);
804 }
805 #else
806 (void)keep_sigalrm;
807 #endif
808 #ifdef SIGINT
809 if(SIG_ERR != old_sigint_handler)
810 (void)signal(SIGINT, old_sigint_handler);
811 #endif
812 #ifdef SIGTERM
813 if(SIG_ERR != old_sigterm_handler)
814 (void)signal(SIGTERM, old_sigterm_handler);
815 #endif
816 #if defined(SIGBREAK) && defined(WIN32)
817 if(SIG_ERR != old_sigbreak_handler)
818 (void)signal(SIGBREAK, old_sigbreak_handler);
819 #endif
820 #ifdef WIN32
821 (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE);
822 if(thread_main_window && thread_main_id) {
823 if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) {
824 if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) {
825 if(CloseHandle(thread_main_window)) {
826 thread_main_window = NULL;
827 thread_main_id = 0;
828 }
829 }
830 }
831 }
832 if(exit_event) {
833 if(CloseHandle(exit_event)) {
834 exit_event = NULL;
835 }
836 }
837 #endif
838 }
839