util.c 12 KB

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