util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2018, 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, NULL, err,
  137. LANG_NEUTRAL, buf, sizeof(buf), NULL))
  138. msnprintf(buf, sizeof(buf), "Unknown error %lu (%#lx)", err, err);
  139. if(msg)
  140. fprintf(stderr, "%s: ", msg);
  141. fprintf(stderr, "%s\n", buf);
  142. }
  143. #endif /* WIN32 */
  144. #ifdef USE_WINSOCK
  145. void win32_init(void)
  146. {
  147. WORD wVersionRequested;
  148. WSADATA wsaData;
  149. int err;
  150. wVersionRequested = MAKEWORD(USE_WINSOCK, USE_WINSOCK);
  151. err = WSAStartup(wVersionRequested, &wsaData);
  152. if(err != 0) {
  153. perror("Winsock init failed");
  154. logmsg("Error initialising winsock -- aborting");
  155. exit(1);
  156. }
  157. if(LOBYTE(wsaData.wVersion) != USE_WINSOCK ||
  158. HIBYTE(wsaData.wVersion) != USE_WINSOCK) {
  159. WSACleanup();
  160. perror("Winsock init failed");
  161. logmsg("No suitable winsock.dll found -- aborting");
  162. exit(1);
  163. }
  164. }
  165. void win32_cleanup(void)
  166. {
  167. WSACleanup();
  168. }
  169. #endif /* USE_WINSOCK */
  170. /* set by the main code to point to where the test dir is */
  171. const char *path = ".";
  172. char *test2file(long testno)
  173. {
  174. static char filename[256];
  175. msnprintf(filename, sizeof(filename), TEST_DATA_PATH, path, testno);
  176. return filename;
  177. }
  178. /*
  179. * Portable function used for waiting a specific amount of ms.
  180. * Waiting indefinitely with this function is not allowed, a
  181. * zero or negative timeout value will return immediately.
  182. *
  183. * Return values:
  184. * -1 = system call error, or invalid timeout value
  185. * 0 = specified timeout has elapsed
  186. */
  187. int wait_ms(int timeout_ms)
  188. {
  189. #if !defined(MSDOS) && !defined(USE_WINSOCK)
  190. #ifndef HAVE_POLL_FINE
  191. struct timeval pending_tv;
  192. #endif
  193. struct timeval initial_tv;
  194. int pending_ms;
  195. #endif
  196. int r = 0;
  197. if(!timeout_ms)
  198. return 0;
  199. if(timeout_ms < 0) {
  200. errno = EINVAL;
  201. return -1;
  202. }
  203. #if defined(MSDOS)
  204. delay(timeout_ms);
  205. #elif defined(USE_WINSOCK)
  206. Sleep(timeout_ms);
  207. #else
  208. pending_ms = timeout_ms;
  209. initial_tv = tvnow();
  210. do {
  211. int error;
  212. #if defined(HAVE_POLL_FINE)
  213. r = poll(NULL, 0, pending_ms);
  214. #else
  215. pending_tv.tv_sec = pending_ms / 1000;
  216. pending_tv.tv_usec = (pending_ms % 1000) * 1000;
  217. r = select(0, NULL, NULL, NULL, &pending_tv);
  218. #endif /* HAVE_POLL_FINE */
  219. if(r != -1)
  220. break;
  221. error = errno;
  222. if(error && (error != EINTR))
  223. break;
  224. pending_ms = timeout_ms - (int)timediff(tvnow(), initial_tv);
  225. if(pending_ms <= 0)
  226. break;
  227. } while(r == -1);
  228. #endif /* USE_WINSOCK */
  229. if(r)
  230. r = -1;
  231. return r;
  232. }
  233. int write_pidfile(const char *filename)
  234. {
  235. FILE *pidfile;
  236. long pid;
  237. pid = (long)getpid();
  238. pidfile = fopen(filename, "wb");
  239. if(!pidfile) {
  240. logmsg("Couldn't write pid file: %s %s", filename, strerror(errno));
  241. return 0; /* fail */
  242. }
  243. fprintf(pidfile, "%ld\n", pid);
  244. fclose(pidfile);
  245. logmsg("Wrote pid %ld to %s", pid, filename);
  246. return 1; /* success */
  247. }
  248. void set_advisor_read_lock(const char *filename)
  249. {
  250. FILE *lockfile;
  251. int error = 0;
  252. int res;
  253. do {
  254. lockfile = fopen(filename, "wb");
  255. } while((lockfile == NULL) && ((error = errno) == EINTR));
  256. if(lockfile == NULL) {
  257. logmsg("Error creating lock file %s error: %d %s",
  258. filename, error, strerror(error));
  259. return;
  260. }
  261. do {
  262. res = fclose(lockfile);
  263. } while(res && ((error = errno) == EINTR));
  264. if(res)
  265. logmsg("Error closing lock file %s error: %d %s",
  266. filename, error, strerror(error));
  267. }
  268. void clear_advisor_read_lock(const char *filename)
  269. {
  270. int error = 0;
  271. int res;
  272. /*
  273. ** Log all removal failures. Even those due to file not existing.
  274. ** This allows to detect if unexpectedly the file has already been
  275. ** removed by a process different than the one that should do this.
  276. */
  277. do {
  278. res = unlink(filename);
  279. } while(res && ((error = errno) == EINTR));
  280. if(res)
  281. logmsg("Error removing lock file %s error: %d %s",
  282. filename, error, strerror(error));
  283. }
  284. /* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
  285. its behavior is altered by the current locale. */
  286. static char raw_toupper(char in)
  287. {
  288. #if !defined(CURL_DOES_CONVERSIONS)
  289. if(in >= 'a' && in <= 'z')
  290. return (char)('A' + in - 'a');
  291. #else
  292. switch(in) {
  293. case 'a':
  294. return 'A';
  295. case 'b':
  296. return 'B';
  297. case 'c':
  298. return 'C';
  299. case 'd':
  300. return 'D';
  301. case 'e':
  302. return 'E';
  303. case 'f':
  304. return 'F';
  305. case 'g':
  306. return 'G';
  307. case 'h':
  308. return 'H';
  309. case 'i':
  310. return 'I';
  311. case 'j':
  312. return 'J';
  313. case 'k':
  314. return 'K';
  315. case 'l':
  316. return 'L';
  317. case 'm':
  318. return 'M';
  319. case 'n':
  320. return 'N';
  321. case 'o':
  322. return 'O';
  323. case 'p':
  324. return 'P';
  325. case 'q':
  326. return 'Q';
  327. case 'r':
  328. return 'R';
  329. case 's':
  330. return 'S';
  331. case 't':
  332. return 'T';
  333. case 'u':
  334. return 'U';
  335. case 'v':
  336. return 'V';
  337. case 'w':
  338. return 'W';
  339. case 'x':
  340. return 'X';
  341. case 'y':
  342. return 'Y';
  343. case 'z':
  344. return 'Z';
  345. }
  346. #endif
  347. return in;
  348. }
  349. int strncasecompare(const char *first, const char *second, size_t max)
  350. {
  351. while(*first && *second && max) {
  352. if(raw_toupper(*first) != raw_toupper(*second)) {
  353. break;
  354. }
  355. max--;
  356. first++;
  357. second++;
  358. }
  359. if(0 == max)
  360. return 1; /* they are equal this far */
  361. return raw_toupper(*first) == raw_toupper(*second);
  362. }
  363. #if defined(WIN32) && !defined(MSDOS)
  364. static struct timeval tvnow(void)
  365. {
  366. /*
  367. ** GetTickCount() is available on _all_ Windows versions from W95 up
  368. ** to nowadays. Returns milliseconds elapsed since last system boot,
  369. ** increases monotonically and wraps once 49.7 days have elapsed.
  370. **
  371. ** GetTickCount64() is available on Windows version from Windows Vista
  372. ** and Windows Server 2008 up to nowadays. The resolution of the
  373. ** function is limited to the resolution of the system timer, which
  374. ** is typically in the range of 10 milliseconds to 16 milliseconds.
  375. */
  376. struct timeval now;
  377. #if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) && \
  378. (!defined(__MINGW32__) || defined(__MINGW64_VERSION_MAJOR))
  379. ULONGLONG milliseconds = GetTickCount64();
  380. #else
  381. DWORD milliseconds = GetTickCount();
  382. #endif
  383. now.tv_sec = (long)(milliseconds / 1000);
  384. now.tv_usec = (long)((milliseconds % 1000) * 1000);
  385. return now;
  386. }
  387. #elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
  388. static struct timeval tvnow(void)
  389. {
  390. /*
  391. ** clock_gettime() is granted to be increased monotonically when the
  392. ** monotonic clock is queried. Time starting point is unspecified, it
  393. ** could be the system start-up time, the Epoch, or something else,
  394. ** in any case the time starting point does not change once that the
  395. ** system has started up.
  396. */
  397. struct timeval now;
  398. struct timespec tsnow;
  399. if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
  400. now.tv_sec = tsnow.tv_sec;
  401. now.tv_usec = tsnow.tv_nsec / 1000;
  402. }
  403. /*
  404. ** Even when the configure process has truly detected monotonic clock
  405. ** availability, it might happen that it is not actually available at
  406. ** run-time. When this occurs simply fallback to other time source.
  407. */
  408. #ifdef HAVE_GETTIMEOFDAY
  409. else
  410. (void)gettimeofday(&now, NULL);
  411. #else
  412. else {
  413. now.tv_sec = (long)time(NULL);
  414. now.tv_usec = 0;
  415. }
  416. #endif
  417. return now;
  418. }
  419. #elif defined(HAVE_GETTIMEOFDAY)
  420. static struct timeval tvnow(void)
  421. {
  422. /*
  423. ** gettimeofday() is not granted to be increased monotonically, due to
  424. ** clock drifting and external source time synchronization it can jump
  425. ** forward or backward in time.
  426. */
  427. struct timeval now;
  428. (void)gettimeofday(&now, NULL);
  429. return now;
  430. }
  431. #else
  432. static struct timeval tvnow(void)
  433. {
  434. /*
  435. ** time() returns the value of time in seconds since the Epoch.
  436. */
  437. struct timeval now;
  438. now.tv_sec = (long)time(NULL);
  439. now.tv_usec = 0;
  440. return now;
  441. }
  442. #endif
  443. long timediff(struct timeval newer, struct timeval older)
  444. {
  445. timediff_t diff = newer.tv_sec-older.tv_sec;
  446. if(diff >= (LONG_MAX/1000))
  447. return LONG_MAX;
  448. else if(diff <= (LONG_MIN/1000))
  449. return LONG_MIN;
  450. return (long)(newer.tv_sec-older.tv_sec)*1000+
  451. (long)(newer.tv_usec-older.tv_usec)/1000;
  452. }