util.c 24 KB

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