• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #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))
68 const struct in6_addr in6addr_any = {{ IN6ADDR_ANY_INIT }};
69 #endif /* w32api < 3.6 */
70 #endif /* ENABLE_IPV6 && __MINGW32__ */
71 
72 static 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  */
data_to_hex(char * data,size_t len)78 char *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 
logmsg(const char * msg,...)101 void 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 */
win32_perror(const char * msg)151 void 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 
win32_init(void)165 void 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 
win32_cleanup(void)191 void 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 */
203 const char *path = ".";
204 
test2fopen(long testno)205 FILE *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  */
wait_ms(int timeout_ms)231 int 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 
our_getpid(void)279 curl_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 
write_pidfile(const char * filename)296 int 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 */
write_portfile(const char * filename,int port)314 int 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 
set_advisor_read_lock(const char * filename)327 void 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 
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) && !defined(MSDOS)
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     (!defined(__MINGW32__) || defined(__MINGW64_VERSION_MAJOR))
387   ULONGLONG milliseconds = GetTickCount64();
388 #else
389   DWORD milliseconds = GetTickCount();
390 #endif
391   now.tv_sec = (long)(milliseconds / 1000);
392   now.tv_usec = (long)((milliseconds % 1000) * 1000);
393   return now;
394 }
395 
396 #elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
397 
tvnow(void)398 static struct timeval tvnow(void)
399 {
400   /*
401   ** clock_gettime() is granted to be increased monotonically when the
402   ** monotonic clock is queried. Time starting point is unspecified, it
403   ** could be the system start-up time, the Epoch, or something else,
404   ** in any case the time starting point does not change once that the
405   ** system has started up.
406   */
407   struct timeval now;
408   struct timespec tsnow;
409   if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
410     now.tv_sec = tsnow.tv_sec;
411     now.tv_usec = (int)(tsnow.tv_nsec / 1000);
412   }
413   /*
414   ** Even when the configure process has truly detected monotonic clock
415   ** availability, it might happen that it is not actually available at
416   ** run-time. When this occurs simply fallback to other time source.
417   */
418 #ifdef HAVE_GETTIMEOFDAY
419   else
420     (void)gettimeofday(&now, NULL);
421 #else
422   else {
423     now.tv_sec = time(NULL);
424     now.tv_usec = 0;
425   }
426 #endif
427   return now;
428 }
429 
430 #elif defined(HAVE_GETTIMEOFDAY)
431 
tvnow(void)432 static struct timeval tvnow(void)
433 {
434   /*
435   ** gettimeofday() is not granted to be increased monotonically, due to
436   ** clock drifting and external source time synchronization it can jump
437   ** forward or backward in time.
438   */
439   struct timeval now;
440   (void)gettimeofday(&now, NULL);
441   return now;
442 }
443 
444 #else
445 
tvnow(void)446 static struct timeval tvnow(void)
447 {
448   /*
449   ** time() returns the value of time in seconds since the Epoch.
450   */
451   struct timeval now;
452   now.tv_sec = time(NULL);
453   now.tv_usec = 0;
454   return now;
455 }
456 
457 #endif
458 
timediff(struct timeval newer,struct timeval older)459 long timediff(struct timeval newer, struct timeval older)
460 {
461   timediff_t diff = newer.tv_sec-older.tv_sec;
462   if(diff >= (LONG_MAX/1000))
463     return LONG_MAX;
464   else if(diff <= (LONG_MIN/1000))
465     return LONG_MIN;
466   return (long)(newer.tv_sec-older.tv_sec)*1000+
467     (long)(newer.tv_usec-older.tv_usec)/1000;
468 }
469 
470 /* vars used to keep around previous signal handlers */
471 
472 typedef void (*SIGHANDLER_T)(int);
473 
474 #ifdef SIGHUP
475 static SIGHANDLER_T old_sighup_handler  = SIG_ERR;
476 #endif
477 
478 #ifdef SIGPIPE
479 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
480 #endif
481 
482 #ifdef SIGALRM
483 static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
484 #endif
485 
486 #ifdef SIGINT
487 static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
488 #endif
489 
490 #ifdef SIGTERM
491 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
492 #endif
493 
494 #if defined(SIGBREAK) && defined(WIN32)
495 static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
496 #endif
497 
498 #ifdef WIN32
499 #ifdef _WIN32_WCE
500 static DWORD thread_main_id = 0;
501 #else
502 static unsigned int thread_main_id = 0;
503 #endif
504 static HANDLE thread_main_window = NULL;
505 static HWND hidden_main_window = NULL;
506 #endif
507 
508 /* var which if set indicates that the program should finish execution */
509 volatile int got_exit_signal = 0;
510 
511 /* if next is set indicates the first signal handled in exit_signal_handler */
512 volatile int exit_signal = 0;
513 
514 #ifdef WIN32
515 /* event which if set indicates that the program should finish */
516 HANDLE exit_event = NULL;
517 #endif
518 
519 /* signal handler that will be triggered to indicate that the program
520  * should finish its execution in a controlled manner as soon as possible.
521  * The first time this is called it will set got_exit_signal to one and
522  * store in exit_signal the signal that triggered its execution.
523  */
exit_signal_handler(int signum)524 static void exit_signal_handler(int signum)
525 {
526   int old_errno = errno;
527   logmsg("exit_signal_handler: %d", signum);
528   if(got_exit_signal == 0) {
529     got_exit_signal = 1;
530     exit_signal = signum;
531 #ifdef WIN32
532     if(exit_event)
533       (void)SetEvent(exit_event);
534 #endif
535   }
536   (void)signal(signum, exit_signal_handler);
537   errno = old_errno;
538 }
539 
540 #ifdef WIN32
541 /* CTRL event handler for Windows Console applications to simulate
542  * SIGINT, SIGTERM and SIGBREAK on CTRL events and trigger signal handler.
543  *
544  * Background information from MSDN:
545  * SIGINT is not supported for any Win32 application. When a CTRL+C
546  * interrupt occurs, Win32 operating systems generate a new thread
547  * to specifically handle that interrupt. This can cause a single-thread
548  * application, such as one in UNIX, to become multithreaded and cause
549  * unexpected behavior.
550  * [...]
551  * The SIGILL and SIGTERM signals are not generated under Windows.
552  * They are included for ANSI compatibility. Therefore, you can set
553  * signal handlers for these signals by using signal, and you can also
554  * explicitly generate these signals by calling raise. Source:
555  * https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/signal
556  */
ctrl_event_handler(DWORD dwCtrlType)557 static BOOL WINAPI ctrl_event_handler(DWORD dwCtrlType)
558 {
559   int signum = 0;
560   logmsg("ctrl_event_handler: %d", dwCtrlType);
561   switch(dwCtrlType) {
562 #ifdef SIGINT
563     case CTRL_C_EVENT: signum = SIGINT; break;
564 #endif
565 #ifdef SIGTERM
566     case CTRL_CLOSE_EVENT: signum = SIGTERM; break;
567 #endif
568 #ifdef SIGBREAK
569     case CTRL_BREAK_EVENT: signum = SIGBREAK; break;
570 #endif
571     default: return FALSE;
572   }
573   if(signum) {
574     logmsg("ctrl_event_handler: %d -> %d", dwCtrlType, signum);
575     raise(signum);
576   }
577   return TRUE;
578 }
579 /* Window message handler for Windows applications to add support
580  * for graceful process termination via taskkill (without /f) which
581  * sends WM_CLOSE to all Windows of a process (even hidden ones).
582  *
583  * Therefore we create and run a hidden Window in a separate thread
584  * to receive and handle the WM_CLOSE message as SIGTERM signal.
585  */
main_window_proc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)586 static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg,
587                                          WPARAM wParam, LPARAM lParam)
588 {
589   int signum = 0;
590   if(hwnd == hidden_main_window) {
591     switch(uMsg) {
592 #ifdef SIGTERM
593       case WM_CLOSE: signum = SIGTERM; break;
594 #endif
595       case WM_DESTROY: PostQuitMessage(0); break;
596     }
597     if(signum) {
598       logmsg("main_window_proc: %d -> %d", uMsg, signum);
599       raise(signum);
600     }
601   }
602   return DefWindowProc(hwnd, uMsg, wParam, lParam);
603 }
604 /* Window message queue loop for hidden main window, details see above.
605  */
606 #ifdef _WIN32_WCE
main_window_loop(LPVOID lpParameter)607 static DWORD WINAPI main_window_loop(LPVOID lpParameter)
608 #else
609 #include <process.h>
610 static unsigned int WINAPI main_window_loop(void *lpParameter)
611 #endif
612 {
613   WNDCLASS wc;
614   BOOL ret;
615   MSG msg;
616 
617   ZeroMemory(&wc, sizeof(wc));
618   wc.lpfnWndProc = (WNDPROC)main_window_proc;
619   wc.hInstance = (HINSTANCE)lpParameter;
620   wc.lpszClassName = TEXT("MainWClass");
621   if(!RegisterClass(&wc)) {
622     perror("RegisterClass failed");
623     return (DWORD)-1;
624   }
625 
626   hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"),
627                                       TEXT("Recv WM_CLOSE msg"),
628                                       WS_OVERLAPPEDWINDOW,
629                                       CW_USEDEFAULT, CW_USEDEFAULT,
630                                       CW_USEDEFAULT, CW_USEDEFAULT,
631                                       (HWND)NULL, (HMENU)NULL,
632                                       wc.hInstance, (LPVOID)NULL);
633   if(!hidden_main_window) {
634     perror("CreateWindowEx failed");
635     return (DWORD)-1;
636   }
637 
638   do {
639     ret = GetMessage(&msg, NULL, 0, 0);
640     if(ret == -1) {
641       perror("GetMessage failed");
642       return (DWORD)-1;
643     }
644     else if(ret) {
645       if(msg.message == WM_APP) {
646         DestroyWindow(hidden_main_window);
647       }
648       else if(msg.hwnd && !TranslateMessage(&msg)) {
649         DispatchMessage(&msg);
650       }
651     }
652   } while(ret);
653 
654   hidden_main_window = NULL;
655   return (DWORD)msg.wParam;
656 }
657 #endif
658 
set_signal(int signum,SIGHANDLER_T handler,bool restartable)659 static SIGHANDLER_T set_signal(int signum, SIGHANDLER_T handler,
660                                bool restartable)
661 {
662 #if defined(HAVE_SIGACTION) && defined(SA_RESTART)
663   struct sigaction sa, oldsa;
664 
665   memset(&sa, 0, sizeof(sa));
666   sa.sa_handler = handler;
667   sigemptyset(&sa.sa_mask);
668   sigaddset(&sa.sa_mask, signum);
669   sa.sa_flags = restartable? SA_RESTART: 0;
670 
671   if(sigaction(signum, &sa, &oldsa))
672     return SIG_ERR;
673 
674   return oldsa.sa_handler;
675 #else
676   SIGHANDLER_T oldhdlr = signal(signum, handler);
677 
678 #ifdef HAVE_SIGINTERRUPT
679   if(oldhdlr != SIG_ERR)
680     siginterrupt(signum, (int) restartable);
681 #else
682   (void) restartable;
683 #endif
684 
685   return oldhdlr;
686 #endif
687 }
688 
install_signal_handlers(bool keep_sigalrm)689 void install_signal_handlers(bool keep_sigalrm)
690 {
691 #ifdef WIN32
692 #ifdef _WIN32_WCE
693   typedef HANDLE curl_win_thread_handle_t;
694 #elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
695   typedef unsigned long curl_win_thread_handle_t;
696 #else
697   typedef uintptr_t curl_win_thread_handle_t;
698 #endif
699   curl_win_thread_handle_t thread;
700   /* setup windows exit event before any signal can trigger */
701   exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
702   if(!exit_event)
703     logmsg("cannot create exit event");
704 #endif
705 #ifdef SIGHUP
706   /* ignore SIGHUP signal */
707   old_sighup_handler = set_signal(SIGHUP, SIG_IGN, FALSE);
708   if(old_sighup_handler == SIG_ERR)
709     logmsg("cannot install SIGHUP handler: %s", strerror(errno));
710 #endif
711 #ifdef SIGPIPE
712   /* ignore SIGPIPE signal */
713   old_sigpipe_handler = set_signal(SIGPIPE, SIG_IGN, FALSE);
714   if(old_sigpipe_handler == SIG_ERR)
715     logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
716 #endif
717 #ifdef SIGALRM
718   if(!keep_sigalrm) {
719     /* ignore SIGALRM signal */
720     old_sigalrm_handler = set_signal(SIGALRM, SIG_IGN, FALSE);
721     if(old_sigalrm_handler == SIG_ERR)
722       logmsg("cannot install SIGALRM handler: %s", strerror(errno));
723   }
724 #else
725   (void)keep_sigalrm;
726 #endif
727 #ifdef SIGINT
728   /* handle SIGINT signal with our exit_signal_handler */
729   old_sigint_handler = set_signal(SIGINT, exit_signal_handler, TRUE);
730   if(old_sigint_handler == SIG_ERR)
731     logmsg("cannot install SIGINT handler: %s", strerror(errno));
732 #endif
733 #ifdef SIGTERM
734   /* handle SIGTERM signal with our exit_signal_handler */
735   old_sigterm_handler = set_signal(SIGTERM, exit_signal_handler, TRUE);
736   if(old_sigterm_handler == SIG_ERR)
737     logmsg("cannot install SIGTERM handler: %s", strerror(errno));
738 #endif
739 #if defined(SIGBREAK) && defined(WIN32)
740   /* handle SIGBREAK signal with our exit_signal_handler */
741   old_sigbreak_handler = set_signal(SIGBREAK, exit_signal_handler, TRUE);
742   if(old_sigbreak_handler == SIG_ERR)
743     logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
744 #endif
745 #ifdef WIN32
746   if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE))
747     logmsg("cannot install CTRL event handler");
748 #ifdef _WIN32_WCE
749   thread = CreateThread(NULL, 0, &main_window_loop,
750                         (LPVOID)GetModuleHandle(NULL), 0, &thread_main_id);
751 #else
752   thread = _beginthreadex(NULL, 0, &main_window_loop,
753                           (void *)GetModuleHandle(NULL), 0, &thread_main_id);
754 #endif
755   thread_main_window = (HANDLE)thread;
756   if(!thread_main_window || !thread_main_id)
757     logmsg("cannot start main window loop");
758 #endif
759 }
760 
restore_signal_handlers(bool keep_sigalrm)761 void restore_signal_handlers(bool keep_sigalrm)
762 {
763 #ifdef SIGHUP
764   if(SIG_ERR != old_sighup_handler)
765     (void) set_signal(SIGHUP, old_sighup_handler, FALSE);
766 #endif
767 #ifdef SIGPIPE
768   if(SIG_ERR != old_sigpipe_handler)
769     (void) set_signal(SIGPIPE, old_sigpipe_handler, FALSE);
770 #endif
771 #ifdef SIGALRM
772   if(!keep_sigalrm) {
773     if(SIG_ERR != old_sigalrm_handler)
774       (void) set_signal(SIGALRM, old_sigalrm_handler, FALSE);
775   }
776 #else
777   (void)keep_sigalrm;
778 #endif
779 #ifdef SIGINT
780   if(SIG_ERR != old_sigint_handler)
781     (void) set_signal(SIGINT, old_sigint_handler, FALSE);
782 #endif
783 #ifdef SIGTERM
784   if(SIG_ERR != old_sigterm_handler)
785     (void) set_signal(SIGTERM, old_sigterm_handler, FALSE);
786 #endif
787 #if defined(SIGBREAK) && defined(WIN32)
788   if(SIG_ERR != old_sigbreak_handler)
789     (void) set_signal(SIGBREAK, old_sigbreak_handler, FALSE);
790 #endif
791 #ifdef WIN32
792   (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE);
793   if(thread_main_window && thread_main_id) {
794     if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) {
795       if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) {
796         if(CloseHandle(thread_main_window)) {
797           thread_main_window = NULL;
798           thread_main_id = 0;
799         }
800       }
801     }
802   }
803   if(exit_event) {
804     if(CloseHandle(exit_event)) {
805       exit_event = NULL;
806     }
807   }
808 #endif
809 }
810 
811 #ifdef USE_UNIX_SOCKETS
812 
bind_unix_socket(curl_socket_t sock,const char * unix_socket,struct sockaddr_un * sau)813 int bind_unix_socket(curl_socket_t sock, const char *unix_socket,
814         struct sockaddr_un *sau) {
815     int error;
816     int rc;
817 
818     memset(sau, 0, sizeof(struct sockaddr_un));
819     sau->sun_family = AF_UNIX;
820     strncpy(sau->sun_path, unix_socket, sizeof(sau->sun_path) - 1);
821     rc = bind(sock, (struct sockaddr*)sau, sizeof(struct sockaddr_un));
822     if(0 != rc && errno == EADDRINUSE) {
823       struct_stat statbuf;
824       /* socket already exists. Perhaps it is stale? */
825       curl_socket_t unixfd = socket(AF_UNIX, SOCK_STREAM, 0);
826       if(CURL_SOCKET_BAD == unixfd) {
827         error = SOCKERRNO;
828         logmsg("Error binding socket, failed to create socket at %s: (%d) %s",
829                unix_socket, error, strerror(error));
830         return rc;
831       }
832       /* check whether the server is alive */
833       rc = connect(unixfd, (struct sockaddr*)sau, sizeof(struct sockaddr_un));
834       error = errno;
835       sclose(unixfd);
836       if(ECONNREFUSED != error) {
837         logmsg("Error binding socket, failed to connect to %s: (%d) %s",
838                unix_socket, error, strerror(error));
839         return rc;
840       }
841       /* socket server is not alive, now check if it was actually a socket. */
842 #ifdef WIN32
843       /* Windows does not have lstat function. */
844       rc = curlx_win32_stat(unix_socket, &statbuf);
845 #else
846       rc = lstat(unix_socket, &statbuf);
847 #endif
848       if(0 != rc) {
849         logmsg("Error binding socket, failed to stat %s: (%d) %s",
850                unix_socket, errno, strerror(errno));
851         return rc;
852       }
853 #ifdef S_IFSOCK
854       if((statbuf.st_mode & S_IFSOCK) != S_IFSOCK) {
855         logmsg("Error binding socket, failed to stat %s: (%d) %s",
856                unix_socket, error, strerror(error));
857         return rc;
858       }
859 #endif
860       /* dead socket, cleanup and retry bind */
861       rc = unlink(unix_socket);
862       if(0 != rc) {
863         logmsg("Error binding socket, failed to unlink %s: (%d) %s",
864                unix_socket, errno, strerror(errno));
865         return rc;
866       }
867       /* stale socket is gone, retry bind */
868       rc = bind(sock, (struct sockaddr*)sau, sizeof(struct sockaddr_un));
869     }
870     return rc;
871 }
872 #endif
873