util.c 24 KB

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