util.c 24 KB

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