util.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. DWORD 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) && !defined(MSDOS)
  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. #ifdef _WIN32
  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. /* Window message handler for Windows applications to add support
  513. * for graceful process termination via taskkill (without /f) which
  514. * sends WM_CLOSE to all Windows of a process (even hidden ones).
  515. *
  516. * Therefore we create and run a hidden Window in a separate thread
  517. * to receive and handle the WM_CLOSE message as SIGTERM signal.
  518. */
  519. static LRESULT CALLBACK main_window_proc(HWND hwnd, UINT uMsg,
  520. WPARAM wParam, LPARAM lParam)
  521. {
  522. int signum = 0;
  523. if(hwnd == hidden_main_window) {
  524. switch(uMsg) {
  525. #ifdef SIGTERM
  526. case WM_CLOSE: signum = SIGTERM; break;
  527. #endif
  528. case WM_DESTROY: PostQuitMessage(0); break;
  529. }
  530. if(signum) {
  531. logmsg("main_window_proc: %d -> %d", uMsg, signum);
  532. raise(signum);
  533. }
  534. }
  535. return DefWindowProc(hwnd, uMsg, wParam, lParam);
  536. }
  537. /* Window message queue loop for hidden main window, details see above.
  538. */
  539. #ifdef _WIN32_WCE
  540. static DWORD WINAPI main_window_loop(LPVOID lpParameter)
  541. #else
  542. #include <process.h>
  543. static unsigned int WINAPI main_window_loop(void *lpParameter)
  544. #endif
  545. {
  546. WNDCLASS wc;
  547. BOOL ret;
  548. MSG msg;
  549. ZeroMemory(&wc, sizeof(wc));
  550. wc.lpfnWndProc = (WNDPROC)main_window_proc;
  551. wc.hInstance = (HINSTANCE)lpParameter;
  552. wc.lpszClassName = TEXT("MainWClass");
  553. if(!RegisterClass(&wc)) {
  554. perror("RegisterClass failed");
  555. return (DWORD)-1;
  556. }
  557. hidden_main_window = CreateWindowEx(0, TEXT("MainWClass"),
  558. TEXT("Recv WM_CLOSE msg"),
  559. WS_OVERLAPPEDWINDOW,
  560. CW_USEDEFAULT, CW_USEDEFAULT,
  561. CW_USEDEFAULT, CW_USEDEFAULT,
  562. (HWND)NULL, (HMENU)NULL,
  563. wc.hInstance, (LPVOID)NULL);
  564. if(!hidden_main_window) {
  565. perror("CreateWindowEx failed");
  566. return (DWORD)-1;
  567. }
  568. do {
  569. ret = GetMessage(&msg, NULL, 0, 0);
  570. if(ret == -1) {
  571. perror("GetMessage failed");
  572. return (DWORD)-1;
  573. }
  574. else if(ret) {
  575. if(msg.message == WM_APP) {
  576. DestroyWindow(hidden_main_window);
  577. }
  578. else if(msg.hwnd && !TranslateMessage(&msg)) {
  579. DispatchMessage(&msg);
  580. }
  581. }
  582. } while(ret);
  583. hidden_main_window = NULL;
  584. return (DWORD)msg.wParam;
  585. }
  586. #endif
  587. static SIGHANDLER_T set_signal(int signum, SIGHANDLER_T handler,
  588. bool restartable)
  589. {
  590. #if defined(HAVE_SIGACTION) && defined(SA_RESTART)
  591. struct sigaction sa, oldsa;
  592. memset(&sa, 0, sizeof(sa));
  593. sa.sa_handler = handler;
  594. sigemptyset(&sa.sa_mask);
  595. sigaddset(&sa.sa_mask, signum);
  596. sa.sa_flags = restartable? SA_RESTART: 0;
  597. if(sigaction(signum, &sa, &oldsa))
  598. return SIG_ERR;
  599. return oldsa.sa_handler;
  600. #else
  601. SIGHANDLER_T oldhdlr = signal(signum, handler);
  602. #ifdef HAVE_SIGINTERRUPT
  603. if(oldhdlr != SIG_ERR)
  604. siginterrupt(signum, (int) restartable);
  605. #else
  606. (void) restartable;
  607. #endif
  608. return oldhdlr;
  609. #endif
  610. }
  611. void install_signal_handlers(bool keep_sigalrm)
  612. {
  613. #ifdef _WIN32
  614. #ifdef _WIN32_WCE
  615. typedef HANDLE curl_win_thread_handle_t;
  616. #else
  617. typedef uintptr_t curl_win_thread_handle_t;
  618. #endif
  619. curl_win_thread_handle_t thread;
  620. /* setup windows exit event before any signal can trigger */
  621. exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
  622. if(!exit_event)
  623. logmsg("cannot create exit event");
  624. #endif
  625. #ifdef SIGHUP
  626. /* ignore SIGHUP signal */
  627. old_sighup_handler = set_signal(SIGHUP, SIG_IGN, FALSE);
  628. if(old_sighup_handler == SIG_ERR)
  629. logmsg("cannot install SIGHUP handler: %s", strerror(errno));
  630. #endif
  631. #ifdef SIGPIPE
  632. /* ignore SIGPIPE signal */
  633. old_sigpipe_handler = set_signal(SIGPIPE, SIG_IGN, FALSE);
  634. if(old_sigpipe_handler == SIG_ERR)
  635. logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
  636. #endif
  637. #ifdef SIGALRM
  638. if(!keep_sigalrm) {
  639. /* ignore SIGALRM signal */
  640. old_sigalrm_handler = set_signal(SIGALRM, SIG_IGN, FALSE);
  641. if(old_sigalrm_handler == SIG_ERR)
  642. logmsg("cannot install SIGALRM handler: %s", strerror(errno));
  643. }
  644. #else
  645. (void)keep_sigalrm;
  646. #endif
  647. #ifdef SIGINT
  648. /* handle SIGINT signal with our exit_signal_handler */
  649. old_sigint_handler = set_signal(SIGINT, exit_signal_handler, TRUE);
  650. if(old_sigint_handler == SIG_ERR)
  651. logmsg("cannot install SIGINT handler: %s", strerror(errno));
  652. #endif
  653. #ifdef SIGTERM
  654. /* handle SIGTERM signal with our exit_signal_handler */
  655. old_sigterm_handler = set_signal(SIGTERM, exit_signal_handler, TRUE);
  656. if(old_sigterm_handler == SIG_ERR)
  657. logmsg("cannot install SIGTERM handler: %s", strerror(errno));
  658. #endif
  659. #if defined(SIGBREAK) && defined(_WIN32)
  660. /* handle SIGBREAK signal with our exit_signal_handler */
  661. old_sigbreak_handler = set_signal(SIGBREAK, exit_signal_handler, TRUE);
  662. if(old_sigbreak_handler == SIG_ERR)
  663. logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
  664. #endif
  665. #ifdef _WIN32
  666. if(!SetConsoleCtrlHandler(ctrl_event_handler, TRUE))
  667. logmsg("cannot install CTRL event handler");
  668. #ifdef _WIN32_WCE
  669. thread = CreateThread(NULL, 0, &main_window_loop,
  670. (LPVOID)GetModuleHandle(NULL), 0, &thread_main_id);
  671. #else
  672. thread = _beginthreadex(NULL, 0, &main_window_loop,
  673. (void *)GetModuleHandle(NULL), 0, &thread_main_id);
  674. #endif
  675. thread_main_window = (HANDLE)thread;
  676. if(!thread_main_window || !thread_main_id)
  677. logmsg("cannot start main window loop");
  678. #endif
  679. }
  680. void restore_signal_handlers(bool keep_sigalrm)
  681. {
  682. #ifdef SIGHUP
  683. if(SIG_ERR != old_sighup_handler)
  684. (void) set_signal(SIGHUP, old_sighup_handler, FALSE);
  685. #endif
  686. #ifdef SIGPIPE
  687. if(SIG_ERR != old_sigpipe_handler)
  688. (void) set_signal(SIGPIPE, old_sigpipe_handler, FALSE);
  689. #endif
  690. #ifdef SIGALRM
  691. if(!keep_sigalrm) {
  692. if(SIG_ERR != old_sigalrm_handler)
  693. (void) set_signal(SIGALRM, old_sigalrm_handler, FALSE);
  694. }
  695. #else
  696. (void)keep_sigalrm;
  697. #endif
  698. #ifdef SIGINT
  699. if(SIG_ERR != old_sigint_handler)
  700. (void) set_signal(SIGINT, old_sigint_handler, FALSE);
  701. #endif
  702. #ifdef SIGTERM
  703. if(SIG_ERR != old_sigterm_handler)
  704. (void) set_signal(SIGTERM, old_sigterm_handler, FALSE);
  705. #endif
  706. #if defined(SIGBREAK) && defined(_WIN32)
  707. if(SIG_ERR != old_sigbreak_handler)
  708. (void) set_signal(SIGBREAK, old_sigbreak_handler, FALSE);
  709. #endif
  710. #ifdef _WIN32
  711. (void)SetConsoleCtrlHandler(ctrl_event_handler, FALSE);
  712. if(thread_main_window && thread_main_id) {
  713. if(PostThreadMessage(thread_main_id, WM_APP, 0, 0)) {
  714. if(WaitForSingleObjectEx(thread_main_window, INFINITE, TRUE)) {
  715. if(CloseHandle(thread_main_window)) {
  716. thread_main_window = NULL;
  717. thread_main_id = 0;
  718. }
  719. }
  720. }
  721. }
  722. if(exit_event) {
  723. if(CloseHandle(exit_event)) {
  724. exit_event = NULL;
  725. }
  726. }
  727. #endif
  728. }
  729. #ifdef USE_UNIX_SOCKETS
  730. int bind_unix_socket(curl_socket_t sock, const char *unix_socket,
  731. struct sockaddr_un *sau) {
  732. int error;
  733. int rc;
  734. memset(sau, 0, sizeof(struct sockaddr_un));
  735. sau->sun_family = AF_UNIX;
  736. strncpy(sau->sun_path, unix_socket, sizeof(sau->sun_path) - 1);
  737. rc = bind(sock, (struct sockaddr*)sau, sizeof(struct sockaddr_un));
  738. if(0 != rc && SOCKERRNO == EADDRINUSE) {
  739. struct_stat statbuf;
  740. /* socket already exists. Perhaps it is stale? */
  741. curl_socket_t unixfd = socket(AF_UNIX, SOCK_STREAM, 0);
  742. if(CURL_SOCKET_BAD == unixfd) {
  743. logmsg("Failed to create socket at %s: (%d) %s",
  744. unix_socket, SOCKERRNO, sstrerror(SOCKERRNO));
  745. return -1;
  746. }
  747. /* check whether the server is alive */
  748. rc = connect(unixfd, (struct sockaddr*)sau, sizeof(struct sockaddr_un));
  749. error = SOCKERRNO;
  750. sclose(unixfd);
  751. if(0 != rc && ECONNREFUSED != error) {
  752. logmsg("Failed to connect to %s: (%d) %s",
  753. unix_socket, error, sstrerror(error));
  754. return rc;
  755. }
  756. /* socket server is not alive, now check if it was actually a socket. */
  757. #ifdef _WIN32
  758. /* Windows does not have lstat function. */
  759. rc = curlx_win32_stat(unix_socket, &statbuf);
  760. #else
  761. rc = lstat(unix_socket, &statbuf);
  762. #endif
  763. if(0 != rc) {
  764. logmsg("Error binding socket, failed to stat %s: (%d) %s",
  765. unix_socket, errno, strerror(errno));
  766. return rc;
  767. }
  768. #ifdef S_IFSOCK
  769. if((statbuf.st_mode & S_IFSOCK) != S_IFSOCK) {
  770. logmsg("Error binding socket, failed to stat %s", unix_socket);
  771. return -1;
  772. }
  773. #endif
  774. /* dead socket, cleanup and retry bind */
  775. rc = unlink(unix_socket);
  776. if(0 != rc) {
  777. logmsg("Error binding socket, failed to unlink %s: (%d) %s",
  778. unix_socket, errno, strerror(errno));
  779. return rc;
  780. }
  781. /* stale socket is gone, retry bind */
  782. rc = bind(sock, (struct sockaddr*)sau, sizeof(struct sockaddr_un));
  783. }
  784. return rc;
  785. }
  786. #endif