util.c 22 KB

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