util.c 22 KB

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