util.c 24 KB

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