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