util.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2021, 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) {
  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 && ((error = errno) == EINTR));
  288. if(!lockfile) {
  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. /* vars used to keep around previous signal handlers */
  486. typedef void (*SIGHANDLER_T)(int);
  487. #ifdef SIGHUP
  488. static SIGHANDLER_T old_sighup_handler = SIG_ERR;
  489. #endif
  490. #ifdef SIGPIPE
  491. static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
  492. #endif
  493. #ifdef SIGALRM
  494. static SIGHANDLER_T old_sigalrm_handler = SIG_ERR;
  495. #endif
  496. #ifdef SIGINT
  497. static SIGHANDLER_T old_sigint_handler = SIG_ERR;
  498. #endif
  499. #ifdef SIGTERM
  500. static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
  501. #endif
  502. #if defined(SIGBREAK) && defined(WIN32)
  503. static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
  504. #endif
  505. #ifdef WIN32
  506. static DWORD thread_main_id = 0;
  507. static HANDLE thread_main_window = NULL;
  508. static HWND hidden_main_window = NULL;
  509. #endif
  510. /* var which if set indicates that the program should finish execution */
  511. volatile int got_exit_signal = 0;
  512. /* if next is set indicates the first signal handled in exit_signal_handler */
  513. volatile int exit_signal = 0;
  514. #ifdef WIN32
  515. /* event which if set indicates that the program should finish */
  516. HANDLE exit_event = NULL;
  517. #endif
  518. /* signal handler that will be triggered to indicate that the program
  519. * should finish its execution in a controlled manner as soon as possible.
  520. * The first time this is called it will set got_exit_signal to one and
  521. * store in exit_signal the signal that triggered its execution.
  522. */
  523. static void exit_signal_handler(int signum)
  524. {
  525. int old_errno = errno;
  526. logmsg("exit_signal_handler: %d", signum);
  527. if(got_exit_signal == 0) {
  528. got_exit_signal = 1;
  529. exit_signal = signum;
  530. #ifdef WIN32
  531. if(exit_event)
  532. (void)SetEvent(exit_event);
  533. #endif
  534. }
  535. (void)signal(signum, exit_signal_handler);
  536. errno = old_errno;
  537. }
  538. #ifdef WIN32
  539. /* CTRL event handler for Windows Console applications to simulate
  540. * SIGINT, SIGTERM and SIGBREAK on CTRL events and trigger signal handler.
  541. *
  542. * Background information from MSDN:
  543. * SIGINT is not supported for any Win32 application. When a CTRL+C
  544. * interrupt occurs, Win32 operating systems generate a new thread
  545. * to specifically handle that interrupt. This can cause a single-thread
  546. * application, such as one in UNIX, to become multithreaded and cause
  547. * unexpected behavior.
  548. * [...]
  549. * The SIGILL and SIGTERM signals are not generated under Windows.
  550. * They are included for ANSI compatibility. Therefore, you can set
  551. * signal handlers for these signals by using signal, and you can also
  552. * explicitly generate these signals by calling raise. Source:
  553. * https://docs.microsoft.com/de-de/cpp/c-runtime-library/reference/signal
  554. */
  555. static BOOL WINAPI ctrl_event_handler(DWORD dwCtrlType)
  556. {
  557. int signum = 0;
  558. logmsg("ctrl_event_handler: %d", dwCtrlType);
  559. switch(dwCtrlType) {
  560. #ifdef SIGINT
  561. case CTRL_C_EVENT: signum = SIGINT; break;
  562. #endif
  563. #ifdef SIGTERM
  564. case CTRL_CLOSE_EVENT: signum = SIGTERM; break;
  565. #endif
  566. #ifdef SIGBREAK
  567. case CTRL_BREAK_EVENT: signum = SIGBREAK; break;
  568. #endif
  569. default: return FALSE;
  570. }
  571. if(signum) {
  572. logmsg("ctrl_event_handler: %d -> %d", dwCtrlType, signum);
  573. raise(signum);
  574. }
  575. return TRUE;
  576. }
  577. /* Window message handler for Windows applications to add support
  578. * for graceful process termination via taskkill (without /f) which
  579. * sends WM_CLOSE to all Windows of a process (even hidden ones).
  580. *
  581. * Therefore we create and run a hidden Window in a separate thread
  582. * to receive and handle the WM_CLOSE message as SIGTERM signal.
  583. */
  584. static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg,
  585. WPARAM wParam, LPARAM lParam)
  586. {
  587. int signum = 0;
  588. if(hwnd == hidden_main_window) {
  589. switch(uMsg) {
  590. #ifdef SIGTERM
  591. case WM_CLOSE: signum = SIGTERM; break;
  592. #endif
  593. case WM_DESTROY: PostQuitMessage(0); break;
  594. }
  595. if(signum) {
  596. logmsg("main_window_proc: %d -> %d", uMsg, signum);
  597. raise(signum);
  598. }
  599. }
  600. return DefWindowProc(hwnd, uMsg, wParam, lParam);
  601. }
  602. /* Window message queue loop for hidden main window, details see above.
  603. */
  604. static DWORD WINAPI main_window_loop(LPVOID lpParameter)
  605. {
  606. WNDCLASS wc;
  607. BOOL ret;
  608. MSG msg;
  609. ZeroMemory(&wc, sizeof(wc));
  610. wc.lpfnWndProc = (WNDPROC)main_window_proc;
  611. wc.hInstance = (HINSTANCE)lpParameter;
  612. wc.lpszClassName = TEXT("MainWClass");
  613. if(!RegisterClass(&wc)) {
  614. perror("RegisterClass failed");
  615. return (DWORD)-1;
  616. }
  617. hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"),
  618. TEXT("Recv WM_CLOSE msg"),
  619. WS_OVERLAPPEDWINDOW,
  620. CW_USEDEFAULT, CW_USEDEFAULT,
  621. CW_USEDEFAULT, CW_USEDEFAULT,
  622. (HWND)NULL, (HMENU)NULL,
  623. wc.hInstance, (LPVOID)NULL);
  624. if(!hidden_main_window) {
  625. perror("CreateWindowEx failed");
  626. return (DWORD)-1;
  627. }
  628. do {
  629. ret = GetMessage(&msg, NULL, 0, 0);
  630. if(ret == -1) {
  631. perror("GetMessage failed");
  632. return (DWORD)-1;
  633. }
  634. else if(ret) {
  635. if(msg.message == WM_APP) {
  636. DestroyWindow(hidden_main_window);
  637. }
  638. else if(msg.hwnd && !TranslateMessage(&msg)) {
  639. DispatchMessage(&msg);
  640. }
  641. }
  642. } while(ret);
  643. hidden_main_window = NULL;
  644. return (DWORD)msg.wParam;
  645. }
  646. #endif
  647. static SIGHANDLER_T set_signal(int signum, SIGHANDLER_T handler,
  648. bool restartable)
  649. {
  650. #if defined(HAVE_SIGACTION) && defined(SA_RESTART)
  651. struct sigaction sa, oldsa;
  652. memset(&sa, 0, sizeof(sa));
  653. sa.sa_handler = handler;
  654. sigemptyset(&sa.sa_mask);
  655. sigaddset(&sa.sa_mask, signum);
  656. sa.sa_flags = restartable? SA_RESTART: 0;
  657. if(sigaction(signum, &sa, &oldsa))
  658. return SIG_ERR;
  659. return oldsa.sa_handler;
  660. #else
  661. SIGHANDLER_T oldhdlr = signal(signum, handler);
  662. #ifdef HAVE_SIGINTERRUPT
  663. if(oldhdlr != SIG_ERR)
  664. siginterrupt(signum, (int) restartable);
  665. #else
  666. (void) restartable;
  667. #endif
  668. return oldhdlr;
  669. #endif
  670. }
  671. void install_signal_handlers(bool keep_sigalrm)
  672. {
  673. #ifdef WIN32
  674. /* setup windows exit event before any signal can trigger */
  675. exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
  676. if(!exit_event)
  677. logmsg("cannot create exit event");
  678. #endif
  679. #ifdef SIGHUP
  680. /* ignore SIGHUP signal */
  681. old_sighup_handler = set_signal(SIGHUP, SIG_IGN, FALSE);
  682. if(old_sighup_handler == SIG_ERR)
  683. logmsg("cannot install SIGHUP handler: %s", strerror(errno));
  684. #endif
  685. #ifdef SIGPIPE
  686. /* ignore SIGPIPE signal */
  687. old_sigpipe_handler = set_signal(SIGPIPE, SIG_IGN, FALSE);
  688. if(old_sigpipe_handler == SIG_ERR)
  689. logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
  690. #endif
  691. #ifdef SIGALRM
  692. if(!keep_sigalrm) {
  693. /* ignore SIGALRM signal */
  694. old_sigalrm_handler = set_signal(SIGALRM, SIG_IGN, FALSE);
  695. if(old_sigalrm_handler == SIG_ERR)
  696. logmsg("cannot install SIGALRM handler: %s", strerror(errno));
  697. }
  698. #else
  699. (void)keep_sigalrm;
  700. #endif
  701. #ifdef SIGINT
  702. /* handle SIGINT signal with our exit_signal_handler */
  703. old_sigint_handler = set_signal(SIGINT, exit_signal_handler, TRUE);
  704. if(old_sigint_handler == SIG_ERR)
  705. logmsg("cannot install SIGINT handler: %s", strerror(errno));
  706. #endif
  707. #ifdef SIGTERM
  708. /* handle SIGTERM signal with our exit_signal_handler */
  709. old_sigterm_handler = set_signal(SIGTERM, exit_signal_handler, TRUE);
  710. if(old_sigterm_handler == SIG_ERR)
  711. logmsg("cannot install SIGTERM handler: %s", strerror(errno));
  712. #endif
  713. #if defined(SIGBREAK) && defined(WIN32)
  714. /* handle SIGBREAK signal with our exit_signal_handler */
  715. old_sigbreak_handler = set_signal(SIGBREAK, exit_signal_handler, TRUE);
  716. if(old_sigbreak_handler == SIG_ERR)
  717. logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
  718. #endif
  719. #ifdef WIN32
  720. if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE))
  721. logmsg("cannot install CTRL event handler");
  722. thread_main_window = CreateThread(NULL, 0,
  723. &main_window_loop,
  724. (LPVOID)GetModuleHandle(NULL),
  725. 0, &thread_main_id);
  726. if(!thread_main_window || !thread_main_id)
  727. logmsg("cannot start main window loop");
  728. #endif
  729. }
  730. void restore_signal_handlers(bool keep_sigalrm)
  731. {
  732. #ifdef SIGHUP
  733. if(SIG_ERR != old_sighup_handler)
  734. (void) set_signal(SIGHUP, old_sighup_handler, FALSE);
  735. #endif
  736. #ifdef SIGPIPE
  737. if(SIG_ERR != old_sigpipe_handler)
  738. (void) set_signal(SIGPIPE, old_sigpipe_handler, FALSE);
  739. #endif
  740. #ifdef SIGALRM
  741. if(!keep_sigalrm) {
  742. if(SIG_ERR != old_sigalrm_handler)
  743. (void) set_signal(SIGALRM, old_sigalrm_handler, FALSE);
  744. }
  745. #else
  746. (void)keep_sigalrm;
  747. #endif
  748. #ifdef SIGINT
  749. if(SIG_ERR != old_sigint_handler)
  750. (void) set_signal(SIGINT, old_sigint_handler, FALSE);
  751. #endif
  752. #ifdef SIGTERM
  753. if(SIG_ERR != old_sigterm_handler)
  754. (void) set_signal(SIGTERM, old_sigterm_handler, FALSE);
  755. #endif
  756. #if defined(SIGBREAK) && defined(WIN32)
  757. if(SIG_ERR != old_sigbreak_handler)
  758. (void) set_signal(SIGBREAK, old_sigbreak_handler, FALSE);
  759. #endif
  760. #ifdef WIN32
  761. (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE);
  762. if(thread_main_window && thread_main_id) {
  763. if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) {
  764. if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) {
  765. if(CloseHandle(thread_main_window)) {
  766. thread_main_window = NULL;
  767. thread_main_id = 0;
  768. }
  769. }
  770. }
  771. }
  772. if(exit_event) {
  773. if(CloseHandle(exit_event)) {
  774. exit_event = NULL;
  775. }
  776. }
  777. #endif
  778. }