1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2021, 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.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) {
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 && ((error = errno) == EINTR));
321 if(!lockfile) {
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 /* vars used to keep around previous signal handlers */
539
540 typedef void (*SIGHANDLER_T)(int);
541
542 #ifdef SIGHUP
543 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
544 #endif
545
546 #ifdef SIGPIPE
547 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
548 #endif
549
550 #ifdef SIGALRM
551 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
552 #endif
553
554 #ifdef SIGINT
555 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
556 #endif
557
558 #ifdef SIGTERM
559 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
560 #endif
561
562 #if defined(SIGBREAK) && defined(WIN32)
563 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
564 #endif
565
566 #ifdef WIN32
567 static DWORD thread_main_id = 0;
568 static HANDLE thread_main_window = NULL;
569 static HWND hidden_main_window = NULL;
570 #endif
571
572 /* var which if set indicates that the program should finish execution */
573 volatile int got_exit_signal = 0;
574
575 /* if next is set indicates the first signal handled in exit_signal_handler */
576 volatile int exit_signal = 0;
577
578 #ifdef WIN32
579 /* event which if set indicates that the program should finish */
580 HANDLE exit_event = NULL;
581 #endif
582
583 /* signal handler that will be triggered to indicate that the program
584 * should finish its execution in a controlled manner as soon as possible.
585 * The first time this is called it will set got_exit_signal to one and
586 * store in exit_signal the signal that triggered its execution.
587 */
exit_signal_handler(int signum)588 static void exit_signal_handler(int signum)
589 {
590 int old_errno = errno;
591 logmsg("exit_signal_handler: %d", signum);
592 if(got_exit_signal == 0) {
593 got_exit_signal = 1;
594 exit_signal = signum;
595 #ifdef WIN32
596 if(exit_event)
597 (void)SetEvent(exit_event);
598 #endif
599 }
600 (void)signal(signum, exit_signal_handler);
601 errno = old_errno;
602 }
603
604 #ifdef WIN32
605 /* CTRL event handler for Windows Console applications to simulate
606 * SIGINT, SIGTERM and SIGBREAK on CTRL events and trigger signal handler.
607 *
608 * Background information from MSDN:
609 * SIGINT is not supported for any Win32 application. When a CTRL+C
610 * interrupt occurs, Win32 operating systems generate a new thread
611 * to specifically handle that interrupt. This can cause a single-thread
612 * application, such as one in UNIX, to become multithreaded and cause
613 * unexpected behavior.
614 * [...]
615 * The SIGILL and SIGTERM signals are not generated under Windows.
616 * They are included for ANSI compatibility. Therefore, you can set
617 * signal handlers for these signals by using signal, and you can also
618 * explicitly generate these signals by calling raise. Source:
619 * https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/signal
620 */
ctrl_event_handler(DWORD dwCtrlType)621 static BOOL WINAPI ctrl_event_handler(DWORD dwCtrlType)
622 {
623 int signum = 0;
624 logmsg("ctrl_event_handler: %d", dwCtrlType);
625 switch(dwCtrlType) {
626 #ifdef SIGINT
627 case CTRL_C_EVENT: signum = SIGINT; break;
628 #endif
629 #ifdef SIGTERM
630 case CTRL_CLOSE_EVENT: signum = SIGTERM; break;
631 #endif
632 #ifdef SIGBREAK
633 case CTRL_BREAK_EVENT: signum = SIGBREAK; break;
634 #endif
635 default: return FALSE;
636 }
637 if(signum) {
638 logmsg("ctrl_event_handler: %d -> %d", dwCtrlType, signum);
639 raise(signum);
640 }
641 return TRUE;
642 }
643 /* Window message handler for Windows applications to add support
644 * for graceful process termination via taskkill (without /f) which
645 * sends WM_CLOSE to all Windows of a process (even hidden ones).
646 *
647 * Therefore we create and run a hidden Window in a separate thread
648 * to receive and handle the WM_CLOSE message as SIGTERM signal.
649 */
main_window_proc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)650 static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg,
651 WPARAM wParam, LPARAM lParam)
652 {
653 int signum = 0;
654 if(hwnd == hidden_main_window) {
655 switch(uMsg) {
656 #ifdef SIGTERM
657 case WM_CLOSE: signum = SIGTERM; break;
658 #endif
659 case WM_DESTROY: PostQuitMessage(0); break;
660 }
661 if(signum) {
662 logmsg("main_window_proc: %d -> %d", uMsg, signum);
663 raise(signum);
664 }
665 }
666 return DefWindowProc(hwnd, uMsg, wParam, lParam);
667 }
668 /* Window message queue loop for hidden main window, details see above.
669 */
main_window_loop(LPVOID lpParameter)670 static DWORD WINAPI main_window_loop(LPVOID lpParameter)
671 {
672 WNDCLASS wc;
673 BOOL ret;
674 MSG msg;
675
676 ZeroMemory(&wc, sizeof(wc));
677 wc.lpfnWndProc = (WNDPROC)main_window_proc;
678 wc.hInstance = (HINSTANCE)lpParameter;
679 wc.lpszClassName = TEXT("MainWClass");
680 if(!RegisterClass(&wc)) {
681 perror("RegisterClass failed");
682 return (DWORD)-1;
683 }
684
685 hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"),
686 TEXT("Recv WM_CLOSE msg"),
687 WS_OVERLAPPEDWINDOW,
688 CW_USEDEFAULT, CW_USEDEFAULT,
689 CW_USEDEFAULT, CW_USEDEFAULT,
690 (HWND)NULL, (HMENU)NULL,
691 wc.hInstance, (LPVOID)NULL);
692 if(!hidden_main_window) {
693 perror("CreateWindowEx failed");
694 return (DWORD)-1;
695 }
696
697 do {
698 ret = GetMessage(&msg, NULL, 0, 0);
699 if(ret == -1) {
700 perror("GetMessage failed");
701 return (DWORD)-1;
702 }
703 else if(ret) {
704 if(msg.message == WM_APP) {
705 DestroyWindow(hidden_main_window);
706 }
707 else if(msg.hwnd && !TranslateMessage(&msg)) {
708 DispatchMessage(&msg);
709 }
710 }
711 } while(ret);
712
713 hidden_main_window = NULL;
714 return (DWORD)msg.wParam;
715 }
716 #endif
717
set_signal(int signum,SIGHANDLER_T handler,bool restartable)718 static SIGHANDLER_T set_signal(int signum, SIGHANDLER_T handler,
719 bool restartable)
720 {
721 #if defined(HAVE_SIGACTION) && defined(SA_RESTART)
722 struct sigaction sa, oldsa;
723
724 memset(&sa, 0, sizeof(sa));
725 sa.sa_handler = handler;
726 sigemptyset(&sa.sa_mask);
727 sigaddset(&sa.sa_mask, signum);
728 sa.sa_flags = restartable? SA_RESTART: 0;
729
730 if(sigaction(signum, &sa, &oldsa))
731 return SIG_ERR;
732
733 return oldsa.sa_handler;
734 #else
735 SIGHANDLER_T oldhdlr = signal(signum, handler);
736
737 #ifdef HAVE_SIGINTERRUPT
738 if(oldhdlr != SIG_ERR)
739 siginterrupt(signum, (int) restartable);
740 #else
741 (void) restartable;
742 #endif
743
744 return oldhdlr;
745 #endif
746 }
747
install_signal_handlers(bool keep_sigalrm)748 void install_signal_handlers(bool keep_sigalrm)
749 {
750 #ifdef WIN32
751 /* setup windows exit event before any signal can trigger */
752 exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
753 if(!exit_event)
754 logmsg("cannot create exit event");
755 #endif
756 #ifdef SIGHUP
757 /* ignore SIGHUP signal */
758 old_sighup_handler = set_signal(SIGHUP, SIG_IGN, FALSE);
759 if(old_sighup_handler == SIG_ERR)
760 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
761 #endif
762 #ifdef SIGPIPE
763 /* ignore SIGPIPE signal */
764 old_sigpipe_handler = set_signal(SIGPIPE, SIG_IGN, FALSE);
765 if(old_sigpipe_handler == SIG_ERR)
766 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
767 #endif
768 #ifdef SIGALRM
769 if(!keep_sigalrm) {
770 /* ignore SIGALRM signal */
771 old_sigalrm_handler = set_signal(SIGALRM, SIG_IGN, FALSE);
772 if(old_sigalrm_handler == SIG_ERR)
773 logmsg("cannot install SIGALRM handler: %s", strerror(errno));
774 }
775 #else
776 (void)keep_sigalrm;
777 #endif
778 #ifdef SIGINT
779 /* handle SIGINT signal with our exit_signal_handler */
780 old_sigint_handler = set_signal(SIGINT, exit_signal_handler, TRUE);
781 if(old_sigint_handler == SIG_ERR)
782 logmsg("cannot install SIGINT handler: %s", strerror(errno));
783 #endif
784 #ifdef SIGTERM
785 /* handle SIGTERM signal with our exit_signal_handler */
786 old_sigterm_handler = set_signal(SIGTERM, exit_signal_handler, TRUE);
787 if(old_sigterm_handler == SIG_ERR)
788 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
789 #endif
790 #if defined(SIGBREAK) && defined(WIN32)
791 /* handle SIGBREAK signal with our exit_signal_handler */
792 old_sigbreak_handler = set_signal(SIGBREAK, exit_signal_handler, TRUE);
793 if(old_sigbreak_handler == SIG_ERR)
794 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
795 #endif
796 #ifdef WIN32
797 if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE))
798 logmsg("cannot install CTRL event handler");
799 thread_main_window = CreateThread(NULL, 0,
800 &main_window_loop,
801 (LPVOID)GetModuleHandle(NULL),
802 0, &thread_main_id);
803 if(!thread_main_window || !thread_main_id)
804 logmsg("cannot start main window loop");
805 #endif
806 }
807
restore_signal_handlers(bool keep_sigalrm)808 void restore_signal_handlers(bool keep_sigalrm)
809 {
810 #ifdef SIGHUP
811 if(SIG_ERR != old_sighup_handler)
812 (void) set_signal(SIGHUP, old_sighup_handler, FALSE);
813 #endif
814 #ifdef SIGPIPE
815 if(SIG_ERR != old_sigpipe_handler)
816 (void) set_signal(SIGPIPE, old_sigpipe_handler, FALSE);
817 #endif
818 #ifdef SIGALRM
819 if(!keep_sigalrm) {
820 if(SIG_ERR != old_sigalrm_handler)
821 (void) set_signal(SIGALRM, old_sigalrm_handler, FALSE);
822 }
823 #else
824 (void)keep_sigalrm;
825 #endif
826 #ifdef SIGINT
827 if(SIG_ERR != old_sigint_handler)
828 (void) set_signal(SIGINT, old_sigint_handler, FALSE);
829 #endif
830 #ifdef SIGTERM
831 if(SIG_ERR != old_sigterm_handler)
832 (void) set_signal(SIGTERM, old_sigterm_handler, FALSE);
833 #endif
834 #if defined(SIGBREAK) && defined(WIN32)
835 if(SIG_ERR != old_sigbreak_handler)
836 (void) set_signal(SIGBREAK, old_sigbreak_handler, FALSE);
837 #endif
838 #ifdef WIN32
839 (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE);
840 if(thread_main_window && thread_main_id) {
841 if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) {
842 if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) {
843 if(CloseHandle(thread_main_window)) {
844 thread_main_window = NULL;
845 thread_main_id = 0;
846 }
847 }
848 }
849 }
850 if(exit_event) {
851 if(CloseHandle(exit_event)) {
852 exit_event = NULL;
853 }
854 }
855 #endif
856 }
857