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