util.c 24 KB

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