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