2
0

util.c 24 KB

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