util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, 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.haxx.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. ***************************************************************************/
  22. #include "server_setup.h"
  23. #ifdef HAVE_SIGNAL_H
  24. #include <signal.h>
  25. #endif
  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. #ifdef __MINGW32__
  42. #include <w32api.h>
  43. #endif
  44. #define ENABLE_CURLX_PRINTF
  45. /* make the curlx header define all printf() functions to use the curlx_*
  46. versions instead */
  47. #include "curlx.h" /* from the private lib dir */
  48. #include "getpart.h"
  49. #include "util.h"
  50. #include "timeval.h"
  51. #ifdef USE_WINSOCK
  52. #undef EINTR
  53. #define EINTR 4 /* errno.h value */
  54. #undef EINVAL
  55. #define EINVAL 22 /* errno.h value */
  56. #endif
  57. /* MinGW with w32api version < 3.6 declared in6addr_any as extern,
  58. but lacked the definition */
  59. #if defined(ENABLE_IPV6) && defined(__MINGW32__)
  60. #if (__W32API_MAJOR_VERSION < 3) || \
  61. ((__W32API_MAJOR_VERSION == 3) && (__W32API_MINOR_VERSION < 6))
  62. const struct in6_addr in6addr_any = {{ IN6ADDR_ANY_INIT }};
  63. #endif /* w32api < 3.6 */
  64. #endif /* ENABLE_IPV6 && __MINGW32__*/
  65. static struct timeval tvnow(void);
  66. /* This function returns a pointer to STATIC memory. It converts the given
  67. * binary lump to a hex formatted string usable for output in logs or
  68. * whatever.
  69. */
  70. char *data_to_hex(char *data, size_t len)
  71. {
  72. static char buf[256*3];
  73. size_t i;
  74. char *optr = buf;
  75. char *iptr = data;
  76. if(len > 255)
  77. len = 255;
  78. for(i = 0; i < len; i++) {
  79. if((data[i] >= 0x20) && (data[i] < 0x7f))
  80. *optr++ = *iptr++;
  81. else {
  82. msnprintf(optr, 4, "%%%02x", *iptr++);
  83. optr += 3;
  84. }
  85. }
  86. *optr = 0; /* in case no sprintf was used */
  87. return buf;
  88. }
  89. void logmsg(const char *msg, ...)
  90. {
  91. va_list ap;
  92. char buffer[2048 + 1];
  93. FILE *logfp;
  94. struct timeval tv;
  95. time_t sec;
  96. struct tm *now;
  97. char timebuf[20];
  98. static time_t epoch_offset;
  99. static int known_offset;
  100. if(!serverlogfile) {
  101. fprintf(stderr, "Error: serverlogfile not set\n");
  102. return;
  103. }
  104. tv = tvnow();
  105. if(!known_offset) {
  106. epoch_offset = time(NULL) - tv.tv_sec;
  107. known_offset = 1;
  108. }
  109. sec = epoch_offset + tv.tv_sec;
  110. now = localtime(&sec); /* not thread safe but we don't care */
  111. msnprintf(timebuf, sizeof(timebuf), "%02d:%02d:%02d.%06ld",
  112. (int)now->tm_hour, (int)now->tm_min, (int)now->tm_sec,
  113. (long)tv.tv_usec);
  114. va_start(ap, msg);
  115. mvsnprintf(buffer, sizeof(buffer), msg, ap);
  116. va_end(ap);
  117. logfp = fopen(serverlogfile, "ab");
  118. if(logfp) {
  119. fprintf(logfp, "%s %s\n", timebuf, buffer);
  120. fclose(logfp);
  121. }
  122. else {
  123. int error = errno;
  124. fprintf(stderr, "fopen() failed with error: %d %s\n",
  125. error, strerror(error));
  126. fprintf(stderr, "Error opening file: %s\n", serverlogfile);
  127. fprintf(stderr, "Msg not logged: %s %s\n", timebuf, buffer);
  128. }
  129. }
  130. #ifdef WIN32
  131. /* use instead of perror() on generic windows */
  132. void win32_perror(const char *msg)
  133. {
  134. char buf[512];
  135. DWORD err = SOCKERRNO;
  136. if(!FormatMessageA((FORMAT_MESSAGE_FROM_SYSTEM |
  137. FORMAT_MESSAGE_IGNORE_INSERTS), NULL, err,
  138. LANG_NEUTRAL, buf, sizeof(buf), NULL))
  139. msnprintf(buf, sizeof(buf), "Unknown error %lu (%#lx)", err, err);
  140. if(msg)
  141. fprintf(stderr, "%s: ", msg);
  142. fprintf(stderr, "%s\n", buf);
  143. }
  144. #endif /* WIN32 */
  145. #ifdef USE_WINSOCK
  146. void win32_init(void)
  147. {
  148. WORD wVersionRequested;
  149. WSADATA wsaData;
  150. int err;
  151. wVersionRequested = MAKEWORD(USE_WINSOCK, USE_WINSOCK);
  152. err = WSAStartup(wVersionRequested, &wsaData);
  153. if(err != 0) {
  154. perror("Winsock init failed");
  155. logmsg("Error initialising winsock -- aborting");
  156. exit(1);
  157. }
  158. if(LOBYTE(wsaData.wVersion) != USE_WINSOCK ||
  159. HIBYTE(wsaData.wVersion) != USE_WINSOCK) {
  160. WSACleanup();
  161. perror("Winsock init failed");
  162. logmsg("No suitable winsock.dll found -- aborting");
  163. exit(1);
  164. }
  165. }
  166. void win32_cleanup(void)
  167. {
  168. WSACleanup();
  169. }
  170. #endif /* USE_WINSOCK */
  171. /* set by the main code to point to where the test dir is */
  172. const char *path = ".";
  173. char *test2file(long testno)
  174. {
  175. static char filename[256];
  176. msnprintf(filename, sizeof(filename), TEST_DATA_PATH, path, testno);
  177. return filename;
  178. }
  179. /*
  180. * Portable function used for waiting a specific amount of ms.
  181. * Waiting indefinitely with this function is not allowed, a
  182. * zero or negative timeout value will return immediately.
  183. *
  184. * Return values:
  185. * -1 = system call error, or invalid timeout value
  186. * 0 = specified timeout has elapsed
  187. */
  188. int wait_ms(int timeout_ms)
  189. {
  190. #if !defined(MSDOS) && !defined(USE_WINSOCK)
  191. #ifndef HAVE_POLL_FINE
  192. struct timeval pending_tv;
  193. #endif
  194. struct timeval initial_tv;
  195. int pending_ms;
  196. #endif
  197. int r = 0;
  198. if(!timeout_ms)
  199. return 0;
  200. if(timeout_ms < 0) {
  201. errno = EINVAL;
  202. return -1;
  203. }
  204. #if defined(MSDOS)
  205. delay(timeout_ms);
  206. #elif defined(USE_WINSOCK)
  207. Sleep(timeout_ms);
  208. #else
  209. pending_ms = timeout_ms;
  210. initial_tv = tvnow();
  211. do {
  212. int error;
  213. #if defined(HAVE_POLL_FINE)
  214. r = poll(NULL, 0, pending_ms);
  215. #else
  216. pending_tv.tv_sec = pending_ms / 1000;
  217. pending_tv.tv_usec = (pending_ms % 1000) * 1000;
  218. r = select(0, NULL, NULL, NULL, &pending_tv);
  219. #endif /* HAVE_POLL_FINE */
  220. if(r != -1)
  221. break;
  222. error = errno;
  223. if(error && (error != EINTR))
  224. break;
  225. pending_ms = timeout_ms - (int)timediff(tvnow(), initial_tv);
  226. if(pending_ms <= 0)
  227. break;
  228. } while(r == -1);
  229. #endif /* USE_WINSOCK */
  230. if(r)
  231. r = -1;
  232. return r;
  233. }
  234. int write_pidfile(const char *filename)
  235. {
  236. FILE *pidfile;
  237. long pid;
  238. pid = (long)getpid();
  239. pidfile = fopen(filename, "wb");
  240. if(!pidfile) {
  241. logmsg("Couldn't write pid file: %s %s", filename, strerror(errno));
  242. return 0; /* fail */
  243. }
  244. fprintf(pidfile, "%ld\n", pid);
  245. fclose(pidfile);
  246. logmsg("Wrote pid %ld to %s", pid, filename);
  247. return 1; /* success */
  248. }
  249. void set_advisor_read_lock(const char *filename)
  250. {
  251. FILE *lockfile;
  252. int error = 0;
  253. int res;
  254. do {
  255. lockfile = fopen(filename, "wb");
  256. } while((lockfile == NULL) && ((error = errno) == EINTR));
  257. if(lockfile == NULL) {
  258. logmsg("Error creating lock file %s error: %d %s",
  259. filename, error, strerror(error));
  260. return;
  261. }
  262. do {
  263. res = fclose(lockfile);
  264. } while(res && ((error = errno) == EINTR));
  265. if(res)
  266. logmsg("Error closing lock file %s error: %d %s",
  267. filename, error, strerror(error));
  268. }
  269. void clear_advisor_read_lock(const char *filename)
  270. {
  271. int error = 0;
  272. int res;
  273. /*
  274. ** Log all removal failures. Even those due to file not existing.
  275. ** This allows to detect if unexpectedly the file has already been
  276. ** removed by a process different than the one that should do this.
  277. */
  278. do {
  279. res = unlink(filename);
  280. } while(res && ((error = errno) == EINTR));
  281. if(res)
  282. logmsg("Error removing lock file %s error: %d %s",
  283. filename, error, strerror(error));
  284. }
  285. /* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
  286. its behavior is altered by the current locale. */
  287. static char raw_toupper(char in)
  288. {
  289. #if !defined(CURL_DOES_CONVERSIONS)
  290. if(in >= 'a' && in <= 'z')
  291. return (char)('A' + in - 'a');
  292. #else
  293. switch(in) {
  294. case 'a':
  295. return 'A';
  296. case 'b':
  297. return 'B';
  298. case 'c':
  299. return 'C';
  300. case 'd':
  301. return 'D';
  302. case 'e':
  303. return 'E';
  304. case 'f':
  305. return 'F';
  306. case 'g':
  307. return 'G';
  308. case 'h':
  309. return 'H';
  310. case 'i':
  311. return 'I';
  312. case 'j':
  313. return 'J';
  314. case 'k':
  315. return 'K';
  316. case 'l':
  317. return 'L';
  318. case 'm':
  319. return 'M';
  320. case 'n':
  321. return 'N';
  322. case 'o':
  323. return 'O';
  324. case 'p':
  325. return 'P';
  326. case 'q':
  327. return 'Q';
  328. case 'r':
  329. return 'R';
  330. case 's':
  331. return 'S';
  332. case 't':
  333. return 'T';
  334. case 'u':
  335. return 'U';
  336. case 'v':
  337. return 'V';
  338. case 'w':
  339. return 'W';
  340. case 'x':
  341. return 'X';
  342. case 'y':
  343. return 'Y';
  344. case 'z':
  345. return 'Z';
  346. }
  347. #endif
  348. return in;
  349. }
  350. int strncasecompare(const char *first, const char *second, size_t max)
  351. {
  352. while(*first && *second && max) {
  353. if(raw_toupper(*first) != raw_toupper(*second)) {
  354. break;
  355. }
  356. max--;
  357. first++;
  358. second++;
  359. }
  360. if(0 == max)
  361. return 1; /* they are equal this far */
  362. return raw_toupper(*first) == raw_toupper(*second);
  363. }
  364. #if defined(WIN32) && !defined(MSDOS)
  365. static struct timeval tvnow(void)
  366. {
  367. /*
  368. ** GetTickCount() is available on _all_ Windows versions from W95 up
  369. ** to nowadays. Returns milliseconds elapsed since last system boot,
  370. ** increases monotonically and wraps once 49.7 days have elapsed.
  371. **
  372. ** GetTickCount64() is available on Windows version from Windows Vista
  373. ** and Windows Server 2008 up to nowadays. The resolution of the
  374. ** function is limited to the resolution of the system timer, which
  375. ** is typically in the range of 10 milliseconds to 16 milliseconds.
  376. */
  377. struct timeval now;
  378. #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && \
  379. (!defined(__MINGW32__) || defined(__MINGW64_VERSION_MAJOR))
  380. ULONGLONG milliseconds = GetTickCount64();
  381. #else
  382. DWORD milliseconds = GetTickCount();
  383. #endif
  384. now.tv_sec = (long)(milliseconds / 1000);
  385. now.tv_usec = (long)((milliseconds % 1000) * 1000);
  386. return now;
  387. }
  388. #elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
  389. static struct timeval tvnow(void)
  390. {
  391. /*
  392. ** clock_gettime() is granted to be increased monotonically when the
  393. ** monotonic clock is queried. Time starting point is unspecified, it
  394. ** could be the system start-up time, the Epoch, or something else,
  395. ** in any case the time starting point does not change once that the
  396. ** system has started up.
  397. */
  398. struct timeval now;
  399. struct timespec tsnow;
  400. if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
  401. now.tv_sec = tsnow.tv_sec;
  402. now.tv_usec = tsnow.tv_nsec / 1000;
  403. }
  404. /*
  405. ** Even when the configure process has truly detected monotonic clock
  406. ** availability, it might happen that it is not actually available at
  407. ** run-time. When this occurs simply fallback to other time source.
  408. */
  409. #ifdef HAVE_GETTIMEOFDAY
  410. else
  411. (void)gettimeofday(&now, NULL);
  412. #else
  413. else {
  414. now.tv_sec = (long)time(NULL);
  415. now.tv_usec = 0;
  416. }
  417. #endif
  418. return now;
  419. }
  420. #elif defined(HAVE_GETTIMEOFDAY)
  421. static struct timeval tvnow(void)
  422. {
  423. /*
  424. ** gettimeofday() is not granted to be increased monotonically, due to
  425. ** clock drifting and external source time synchronization it can jump
  426. ** forward or backward in time.
  427. */
  428. struct timeval now;
  429. (void)gettimeofday(&now, NULL);
  430. return now;
  431. }
  432. #else
  433. static struct timeval tvnow(void)
  434. {
  435. /*
  436. ** time() returns the value of time in seconds since the Epoch.
  437. */
  438. struct timeval now;
  439. now.tv_sec = (long)time(NULL);
  440. now.tv_usec = 0;
  441. return now;
  442. }
  443. #endif
  444. long timediff(struct timeval newer, struct timeval older)
  445. {
  446. timediff_t diff = newer.tv_sec-older.tv_sec;
  447. if(diff >= (LONG_MAX/1000))
  448. return LONG_MAX;
  449. else if(diff <= (LONG_MIN/1000))
  450. return LONG_MIN;
  451. return (long)(newer.tv_sec-older.tv_sec)*1000+
  452. (long)(newer.tv_usec-older.tv_usec)/1000;
  453. }