util.c 24 KB

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