1 /*
2  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "event2/event-config.h"
28 #include "evconfig-private.h"
29 
30 #ifdef _WIN32
31 #include <winsock2.h>
32 #define WIN32_LEAN_AND_MEAN
33 #include <windows.h>
34 #undef WIN32_LEAN_AND_MEAN
35 #endif
36 
37 #include <sys/types.h>
38 #ifdef EVENT__HAVE_STDLIB_H
39 #include <stdlib.h>
40 #endif
41 #include <errno.h>
42 #include <limits.h>
43 #ifndef EVENT__HAVE_GETTIMEOFDAY
44 #include <sys/timeb.h>
45 #endif
46 #if !defined(EVENT__HAVE_NANOSLEEP) && !defined(EVENT_HAVE_USLEEP) && \
47 	!defined(_WIN32)
48 #include <sys/select.h>
49 #endif
50 #include <time.h>
51 #include <sys/stat.h>
52 #include <string.h>
53 
54 /** evutil_usleep_() */
55 #if defined(_WIN32)
56 #elif defined(EVENT__HAVE_NANOSLEEP)
57 #elif defined(EVENT__HAVE_USLEEP)
58 #include <unistd.h>
59 #endif
60 
61 #include "event2/util.h"
62 #include "util-internal.h"
63 #include "log-internal.h"
64 #include "mm-internal.h"
65 
66 #ifndef EVENT__HAVE_GETTIMEOFDAY
67 /* No gettimeofday; this must be windows. */
68 int
evutil_gettimeofday(struct timeval * tv,struct timezone * tz)69 evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
70 {
71 #ifdef _MSC_VER
72 #define U64_LITERAL(n) n##ui64
73 #else
74 #define U64_LITERAL(n) n##llu
75 #endif
76 
77 	/* Conversion logic taken from Tor, which in turn took it
78 	 * from Perl.  GetSystemTimeAsFileTime returns its value as
79 	 * an unaligned (!) 64-bit value containing the number of
80 	 * 100-nanosecond intervals since 1 January 1601 UTC. */
81 #define EPOCH_BIAS U64_LITERAL(116444736000000000)
82 #define UNITS_PER_SEC U64_LITERAL(10000000)
83 #define USEC_PER_SEC U64_LITERAL(1000000)
84 #define UNITS_PER_USEC U64_LITERAL(10)
85 	union {
86 		FILETIME ft_ft;
87 		ev_uint64_t ft_64;
88 	} ft;
89 
90 	if (tv == NULL)
91 		return -1;
92 
93 	GetSystemTimeAsFileTime(&ft.ft_ft);
94 
95 	if (EVUTIL_UNLIKELY(ft.ft_64 < EPOCH_BIAS)) {
96 		/* Time before the unix epoch. */
97 		return -1;
98 	}
99 	ft.ft_64 -= EPOCH_BIAS;
100 	tv->tv_sec = (long) (ft.ft_64 / UNITS_PER_SEC);
101 	tv->tv_usec = (long) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
102 	return 0;
103 }
104 #endif
105 
106 #define MAX_SECONDS_IN_MSEC_LONG \
107 	(((LONG_MAX) - 999) / 1000)
108 
109 long
evutil_tv_to_msec_(const struct timeval * tv)110 evutil_tv_to_msec_(const struct timeval *tv)
111 {
112 	if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
113 		return -1;
114 
115 	return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
116 }
117 
118 /*
119   Replacement for usleep on platforms that don't have one.  Not guaranteed to
120   be any more finegrained than 1 msec.
121  */
122 void
evutil_usleep_(const struct timeval * tv)123 evutil_usleep_(const struct timeval *tv)
124 {
125 	if (!tv)
126 		return;
127 #if defined(_WIN32)
128 	{
129 		long msec = evutil_tv_to_msec_(tv);
130 		Sleep((DWORD)msec);
131 	}
132 #elif defined(EVENT__HAVE_NANOSLEEP)
133 	{
134 		struct timespec ts;
135 		ts.tv_sec = tv->tv_sec;
136 		ts.tv_nsec = tv->tv_usec*1000;
137 		nanosleep(&ts, NULL);
138 	}
139 #elif defined(EVENT__HAVE_USLEEP)
140 	/* Some systems don't like to usleep more than 999999 usec */
141 	sleep(tv->tv_sec);
142 	usleep(tv->tv_usec);
143 #else
144 	select(0, NULL, NULL, NULL, tv);
145 #endif
146 }
147 
148 int
evutil_date_rfc1123(char * date,const size_t datelen,struct tm * cur_p)149 evutil_date_rfc1123(char *date, const size_t datelen, struct tm *cur_p) {
150 	static const char *DAYS[] =
151 		{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
152 	static const char *MONTHS[] =
153 		{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
154 
155 	time_t t = time(NULL);
156 
157 	/* If `cur_p` is null, set system's current time. */
158 	if (cur_p == NULL) {
159 #ifdef _WIN32
160 		cur_p = gmtime(&t);
161 #else
162 		{
163 			struct tm cur;
164 			gmtime_r(&t, &cur);
165 			cur_p = &cur;
166 		}
167 #endif
168 	}
169 
170 	return evutil_snprintf(
171 		date, datelen, "%s, %02d %s %4d %02d:%02d:%02d GMT",
172 		DAYS[cur_p->tm_wday], cur_p->tm_mday, MONTHS[cur_p->tm_mon],
173 		1900+cur_p->tm_year, cur_p->tm_hour, cur_p->tm_min, cur_p->tm_sec);
174 }
175 
176 /*
177    This function assumes it's called repeatedly with a
178    not-actually-so-monotonic time source whose outputs are in 'tv'. It
179    implements a trivial ratcheting mechanism so that the values never go
180    backwards.
181  */
182 static void
adjust_monotonic_time(struct evutil_monotonic_timer * base,struct timeval * tv)183 adjust_monotonic_time(struct evutil_monotonic_timer *base,
184     struct timeval *tv)
185 {
186 	evutil_timeradd(tv, &base->adjust_monotonic_clock, tv);
187 
188 	if (evutil_timercmp(tv, &base->last_time, <)) {
189 		/* Guess it wasn't monotonic after all. */
190 		struct timeval adjust;
191 		evutil_timersub(&base->last_time, tv, &adjust);
192 		evutil_timeradd(&adjust, &base->adjust_monotonic_clock,
193 		    &base->adjust_monotonic_clock);
194 		*tv = base->last_time;
195 	}
196 	base->last_time = *tv;
197 }
198 
199 /*
200    Allocate a new struct evutil_monotonic_timer
201  */
202 struct evutil_monotonic_timer *
evutil_monotonic_timer_new(void)203 evutil_monotonic_timer_new(void)
204 {
205   struct evutil_monotonic_timer *p = NULL;
206 
207   p = mm_malloc(sizeof(*p));
208   if (!p) goto done;
209 
210   memset(p, 0, sizeof(*p));
211 
212  done:
213   return p;
214 }
215 
216 /*
217    Free a struct evutil_monotonic_timer
218  */
219 void
evutil_monotonic_timer_free(struct evutil_monotonic_timer * timer)220 evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer)
221 {
222   if (timer) {
223     mm_free(timer);
224   }
225 }
226 
227 /*
228    Set up a struct evutil_monotonic_timer for initial use
229  */
230 int
evutil_configure_monotonic_time(struct evutil_monotonic_timer * timer,int flags)231 evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
232                                 int flags)
233 {
234   return evutil_configure_monotonic_time_(timer, flags);
235 }
236 
237 /*
238    Query the current monotonic time
239  */
240 int
evutil_gettime_monotonic(struct evutil_monotonic_timer * timer,struct timeval * tp)241 evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
242                          struct timeval *tp)
243 {
244   return evutil_gettime_monotonic_(timer, tp);
245 }
246 
247 
248 #if defined(HAVE_POSIX_MONOTONIC)
249 /* =====
250    The POSIX clock_gettime() interface provides a few ways to get at a
251    monotonic clock.  CLOCK_MONOTONIC is most widely supported.  Linux also
252    provides a CLOCK_MONOTONIC_COARSE with accuracy of about 1-4 msec.
253 
254    On all platforms I'm aware of, CLOCK_MONOTONIC really is monotonic.
255    Platforms don't agree about whether it should jump on a sleep/resume.
256  */
257 
258 int
evutil_configure_monotonic_time_(struct evutil_monotonic_timer * base,int flags)259 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
260     int flags)
261 {
262 	/* CLOCK_MONOTONIC exists on FreeBSD, Linux, and Solaris.  You need to
263 	 * check for it at runtime, because some older kernel versions won't
264 	 * have it working. */
265 #ifdef CLOCK_MONOTONIC_COARSE
266 	const int precise = flags & EV_MONOT_PRECISE;
267 #endif
268 	const int fallback = flags & EV_MONOT_FALLBACK;
269 	struct timespec	ts;
270 
271 #ifdef CLOCK_MONOTONIC_COARSE
272 	if (CLOCK_MONOTONIC_COARSE < 0) {
273 		/* Technically speaking, nothing keeps CLOCK_* from being
274 		 * negative (as far as I know). This check and the one below
275 		 * make sure that it's safe for us to use -1 as an "unset"
276 		 * value. */
277 		event_errx(1,"I didn't expect CLOCK_MONOTONIC_COARSE to be < 0");
278 	}
279 	if (! precise && ! fallback) {
280 		if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0) {
281 			base->monotonic_clock = CLOCK_MONOTONIC_COARSE;
282 			return 0;
283 		}
284 	}
285 #endif
286 	if (!fallback && clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
287 		base->monotonic_clock = CLOCK_MONOTONIC;
288 		return 0;
289 	}
290 
291 	if (CLOCK_MONOTONIC < 0) {
292 		event_errx(1,"I didn't expect CLOCK_MONOTONIC to be < 0");
293 	}
294 
295 	base->monotonic_clock = -1;
296 	return 0;
297 }
298 
299 int
evutil_gettime_monotonic_(struct evutil_monotonic_timer * base,struct timeval * tp)300 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
301     struct timeval *tp)
302 {
303 	struct timespec ts;
304 
305 	if (base->monotonic_clock < 0) {
306 		if (evutil_gettimeofday(tp, NULL) < 0)
307 			return -1;
308 		adjust_monotonic_time(base, tp);
309 		return 0;
310 	}
311 
312 	if (clock_gettime(base->monotonic_clock, &ts) == -1)
313 		return -1;
314 	tp->tv_sec = ts.tv_sec;
315 	tp->tv_usec = ts.tv_nsec / 1000;
316 
317 	return 0;
318 }
319 #endif
320 
321 #if defined(HAVE_MACH_MONOTONIC)
322 /* ======
323    Apple is a little late to the POSIX party.  And why not?  Instead of
324    clock_gettime(), they provide mach_absolute_time().  Its units are not
325    fixed; we need to use mach_timebase_info() to get the right functions to
326    convert its units into nanoseconds.
327 
328    To all appearances, mach_absolute_time() seems to be honest-to-goodness
329    monotonic.  Whether it stops during sleep or not is unspecified in
330    principle, and dependent on CPU architecture in practice.
331  */
332 
333 int
evutil_configure_monotonic_time_(struct evutil_monotonic_timer * base,int flags)334 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
335     int flags)
336 {
337 	const int fallback = flags & EV_MONOT_FALLBACK;
338 	struct mach_timebase_info mi;
339 	memset(base, 0, sizeof(*base));
340 	/* OSX has mach_absolute_time() */
341 	if (!fallback &&
342 	    mach_timebase_info(&mi) == 0 &&
343 	    mach_absolute_time() != 0) {
344 		/* mach_timebase_info tells us how to convert
345 		 * mach_absolute_time() into nanoseconds, but we
346 		 * want to use microseconds instead. */
347 		mi.denom *= 1000;
348 		memcpy(&base->mach_timebase_units, &mi, sizeof(mi));
349 	} else {
350 		base->mach_timebase_units.numer = 0;
351 	}
352 	return 0;
353 }
354 
355 int
evutil_gettime_monotonic_(struct evutil_monotonic_timer * base,struct timeval * tp)356 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
357     struct timeval *tp)
358 {
359 	ev_uint64_t abstime, usec;
360 	if (base->mach_timebase_units.numer == 0) {
361 		if (evutil_gettimeofday(tp, NULL) < 0)
362 			return -1;
363 		adjust_monotonic_time(base, tp);
364 		return 0;
365 	}
366 
367 	abstime = mach_absolute_time();
368 	usec = (abstime * base->mach_timebase_units.numer)
369 	    / (base->mach_timebase_units.denom);
370 	tp->tv_sec = usec / 1000000;
371 	tp->tv_usec = usec % 1000000;
372 
373 	return 0;
374 }
375 #endif
376 
377 #if defined(HAVE_WIN32_MONOTONIC)
378 /* =====
379    Turn we now to Windows.  Want monontonic time on Windows?
380 
381    Windows has QueryPerformanceCounter(), which gives time most high-
382    resolution time.  It's a pity it's not so monotonic in practice; it's
383    also got some fun bugs, especially: with older Windowses, under
384    virtualizations, with funny hardware, on multiprocessor systems, and so
385    on.  PEP418 [1] has a nice roundup of the issues here.
386 
387    There's GetTickCount64() on Vista and later, which gives a number of 1-msec
388    ticks since startup.  The accuracy here might be as bad as 10-20 msec, I
389    hear.  There's an undocumented function (NtSetTimerResolution) that
390    allegedly increases the accuracy. Good luck!
391 
392    There's also GetTickCount(), which is only 32 bits, but seems to be
393    supported on pre-Vista versions of Windows.  Apparently, you can coax
394    another 14 bits out of it, giving you 2231 years before rollover.
395 
396    The less said about timeGetTime() the better.
397 
398    "We don't care.  We don't have to.  We're the Phone Company."
399             -- Lily Tomlin, SNL
400 
401    Our strategy, if precise timers are turned off, is to just use the best
402    GetTickCount equivalent available.  If we've been asked for precise timing,
403    then we mostly[2] assume that GetTickCount is monotonic, and correct
404    GetPerformanceCounter to approximate it.
405 
406    [1] http://www.python.org/dev/peps/pep-0418
407    [2] Of course, we feed the Windows stuff into adjust_monotonic_time()
408        anyway, just in case it isn't.
409 
410  */
411 /*
412     Parts of our logic in the win32 timer code here are closely based on
413     BitTorrent's libUTP library.  That code is subject to the following
414     license:
415 
416       Copyright (c) 2010 BitTorrent, Inc.
417 
418       Permission is hereby granted, free of charge, to any person obtaining a
419       copy of this software and associated documentation files (the
420       "Software"), to deal in the Software without restriction, including
421       without limitation the rights to use, copy, modify, merge, publish,
422       distribute, sublicense, and/or sell copies of the Software, and to
423       permit persons to whom the Software is furnished to do so, subject to
424       the following conditions:
425 
426       The above copyright notice and this permission notice shall be included
427       in all copies or substantial portions of the Software.
428 
429       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
430       OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
431       MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
432       NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
433       LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
434       OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
435       WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
436 */
437 
438 static ev_uint64_t
evutil_GetTickCount_(struct evutil_monotonic_timer * base)439 evutil_GetTickCount_(struct evutil_monotonic_timer *base)
440 {
441 	if (base->GetTickCount64_fn) {
442 		/* Let's just use GetTickCount64 if we can. */
443 		return base->GetTickCount64_fn();
444 	} else if (base->GetTickCount_fn) {
445 		/* Greg Hazel assures me that this works, that BitTorrent has
446 		 * done it for years, and this it won't turn around and
447 		 * bite us.  He says they found it on some game programmers'
448 		 * forum some time around 2007.
449 		 */
450 		ev_uint64_t v = base->GetTickCount_fn();
451 		return (DWORD)v | ((v >> 18) & 0xFFFFFFFF00000000);
452 	} else {
453 		/* Here's the fallback implementation. We have to use
454 		 * GetTickCount() with its given signature, so we only get
455 		 * 32 bits worth of milliseconds, which will roll ove every
456 		 * 49 days or so.  */
457 		DWORD ticks = GetTickCount();
458 		if (ticks < base->last_tick_count) {
459 			base->adjust_tick_count += ((ev_uint64_t)1) << 32;
460 		}
461 		base->last_tick_count = ticks;
462 		return ticks + base->adjust_tick_count;
463 	}
464 }
465 
466 int
evutil_configure_monotonic_time_(struct evutil_monotonic_timer * base,int flags)467 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
468     int flags)
469 {
470 	const int precise = flags & EV_MONOT_PRECISE;
471 	const int fallback = flags & EV_MONOT_FALLBACK;
472 	HANDLE h;
473 	memset(base, 0, sizeof(*base));
474 
475 	h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
476 	if (h != NULL && !fallback) {
477 		base->GetTickCount64_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount64");
478 		base->GetTickCount_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount");
479 	}
480 
481 	base->first_tick = base->last_tick_count = evutil_GetTickCount_(base);
482 	if (precise && !fallback) {
483 		LARGE_INTEGER freq;
484 		if (QueryPerformanceFrequency(&freq)) {
485 			LARGE_INTEGER counter;
486 			QueryPerformanceCounter(&counter);
487 			base->first_counter = counter.QuadPart;
488 			base->usec_per_count = 1.0e6 / freq.QuadPart;
489 			base->use_performance_counter = 1;
490 		}
491 	}
492 
493 	return 0;
494 }
495 
496 static inline ev_int64_t
abs64(ev_int64_t i)497 abs64(ev_int64_t i)
498 {
499 	return i < 0 ? -i : i;
500 }
501 
502 
503 int
evutil_gettime_monotonic_(struct evutil_monotonic_timer * base,struct timeval * tp)504 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
505     struct timeval *tp)
506 {
507 	ev_uint64_t ticks = evutil_GetTickCount_(base);
508 	if (base->use_performance_counter) {
509 		/* Here's a trick we took from BitTorrent's libutp, at Greg
510 		 * Hazel's recommendation.  We use QueryPerformanceCounter for
511 		 * our high-resolution timer, but use GetTickCount*() to keep
512 		 * it sane, and adjust_monotonic_time() to keep it monotonic.
513 		 */
514 		LARGE_INTEGER counter;
515 		ev_int64_t counter_elapsed, counter_usec_elapsed, ticks_elapsed;
516 		QueryPerformanceCounter(&counter);
517 		counter_elapsed = (ev_int64_t)
518 		    (counter.QuadPart - base->first_counter);
519 		ticks_elapsed = ticks - base->first_tick;
520 		/* TODO: This may upset VC6. If you need this to work with
521 		 * VC6, please supply an appropriate patch. */
522 		counter_usec_elapsed = (ev_int64_t)
523 		    (counter_elapsed * base->usec_per_count);
524 
525 		if (abs64(ticks_elapsed*1000 - counter_usec_elapsed) > 1000000) {
526 			/* It appears that the QueryPerformanceCounter()
527 			 * result is more than 1 second away from
528 			 * GetTickCount() result. Let's adjust it to be as
529 			 * accurate as we can; adjust_monotnonic_time() below
530 			 * will keep it monotonic. */
531 			counter_usec_elapsed = ticks_elapsed * 1000;
532 			base->first_counter = (ev_uint64_t) (counter.QuadPart - counter_usec_elapsed / base->usec_per_count);
533 		}
534 		tp->tv_sec = (time_t) (counter_usec_elapsed / 1000000);
535 		tp->tv_usec = counter_usec_elapsed % 1000000;
536 
537 	} else {
538 		/* We're just using GetTickCount(). */
539 		tp->tv_sec = (time_t) (ticks / 1000);
540 		tp->tv_usec = (ticks % 1000) * 1000;
541 	}
542 	adjust_monotonic_time(base, tp);
543 
544 	return 0;
545 }
546 #endif
547 
548 #if defined(HAVE_FALLBACK_MONOTONIC)
549 /* =====
550    And if none of the other options work, let's just use gettimeofday(), and
551    ratchet it forward so that it acts like a monotonic timer, whether it
552    wants to or not.
553  */
554 
555 int
evutil_configure_monotonic_time_(struct evutil_monotonic_timer * base,int precise)556 evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
557     int precise)
558 {
559 	memset(base, 0, sizeof(*base));
560 	return 0;
561 }
562 
563 int
evutil_gettime_monotonic_(struct evutil_monotonic_timer * base,struct timeval * tp)564 evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
565     struct timeval *tp)
566 {
567 	if (evutil_gettimeofday(tp, NULL) < 0)
568 		return -1;
569 	adjust_monotonic_time(base, tp);
570 	return 0;
571 
572 }
573 #endif
574