• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
3  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 #include "util-internal.h"
28 
29 #ifdef _WIN32
30 #include <winsock2.h>
31 #include <windows.h>
32 #include <io.h>
33 #include <fcntl.h>
34 #endif
35 
36 /* move_pthread_to_realtime_scheduling_class() */
37 #ifdef EVENT__HAVE_MACH_MACH_H
38 #include <mach/mach.h>
39 #endif
40 #ifdef EVENT__HAVE_MACH_MACH_TIME_H
41 #include <mach/mach_time.h>
42 #endif
43 
44 #if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
45 #if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \
46     __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
47 #define FORK_BREAKS_GCOV
48 #include <vproc.h>
49 #endif
50 #endif
51 
52 #include "event2/event-config.h"
53 
54 #if 0
55 #include <sys/types.h>
56 #include <sys/stat.h>
57 #ifdef EVENT__HAVE_SYS_TIME_H
58 #include <sys/time.h>
59 #endif
60 #include <sys/queue.h>
61 #include <signal.h>
62 #include <errno.h>
63 #endif
64 
65 #include <sys/types.h>
66 #ifdef EVENT__HAVE_SYS_STAT_H
67 #include <sys/stat.h>
68 #endif
69 
70 #ifndef _WIN32
71 #include <sys/socket.h>
72 #include <sys/wait.h>
73 #include <signal.h>
74 #include <unistd.h>
75 #include <netdb.h>
76 #endif
77 
78 #include <stdlib.h>
79 #include <stdio.h>
80 #include <string.h>
81 #include <assert.h>
82 
83 #include "event2/util.h"
84 #include "event2/event.h"
85 #include "event2/event_compat.h"
86 #include "event2/dns.h"
87 #include "event2/dns_compat.h"
88 #include "event2/thread.h"
89 
90 #include "event2/event-config.h"
91 #include "regress.h"
92 #include "regress_thread.h"
93 #include "tinytest.h"
94 #include "tinytest_macros.h"
95 #include "../iocp-internal.h"
96 #include "../event-internal.h"
97 #include "../evthread-internal.h"
98 
99 struct evutil_weakrand_state test_weakrand_state;
100 
101 long
timeval_msec_diff(const struct timeval * start,const struct timeval * end)102 timeval_msec_diff(const struct timeval *start, const struct timeval *end)
103 {
104 	long ms = end->tv_sec - start->tv_sec;
105 	ms *= 1000;
106 	ms += ((end->tv_usec - start->tv_usec)+500) / 1000;
107 	return ms;
108 }
109 
110 /* ============================================================ */
111 /* Code to wrap up old legacy test cases that used setup() and cleanup().
112  *
113  * Not all of the tests designated "legacy" are ones that used setup() and
114  * cleanup(), of course.  A test is legacy it it uses setup()/cleanup(), OR
115  * if it wants to find its event base/socketpair in global variables (ugh),
116  * OR if it wants to communicate success/failure through test_ok.
117  */
118 
119 /* This is set to true if we're inside a legacy test wrapper.  It lets the
120    setup() and cleanup() functions in regress.c know they're not needed.
121  */
122 int in_legacy_test_wrapper = 0;
123 
dnslogcb(int w,const char * m)124 static void dnslogcb(int w, const char *m)
125 {
126 	TT_BLATHER(("%s", m));
127 }
128 
129 /* creates a temporary file with the data in it.  If *filename_out gets set,
130  * the caller should try to unlink it. */
131 int
regress_make_tmpfile(const void * data,size_t datalen,char ** filename_out)132 regress_make_tmpfile(const void *data, size_t datalen, char **filename_out)
133 {
134 #ifndef _WIN32
135 	char tmpfilename[32];
136 	int fd;
137 	*filename_out = NULL;
138 	strcpy(tmpfilename, "/tmp/eventtmp.XXXXXX");
139 #ifdef EVENT__HAVE_UMASK
140 	umask(0077);
141 #endif
142 	fd = mkstemp(tmpfilename);
143 	if (fd == -1)
144 		return (-1);
145 	if (write(fd, data, datalen) != (int)datalen) {
146 		close(fd);
147 		return (-1);
148 	}
149 	lseek(fd, 0, SEEK_SET);
150 	/* remove it from the file system */
151 	unlink(tmpfilename);
152 	return (fd);
153 #else
154 	/* XXXX actually delete the file later */
155 	char tmpfilepath[MAX_PATH];
156 	char tmpfilename[MAX_PATH];
157 	DWORD r, written;
158 	int tries = 16;
159 	HANDLE h;
160 	r = GetTempPathA(MAX_PATH, tmpfilepath);
161 	if (r > MAX_PATH || r == 0)
162 		return (-1);
163 	for (; tries > 0; --tries) {
164 		r = GetTempFileNameA(tmpfilepath, "LIBEVENT", 0, tmpfilename);
165 		if (r == 0)
166 			return (-1);
167 		h = CreateFileA(tmpfilename, GENERIC_READ|GENERIC_WRITE,
168 		    0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
169 		if (h != INVALID_HANDLE_VALUE)
170 			break;
171 	}
172 	if (tries == 0)
173 		return (-1);
174 	written = 0;
175 	*filename_out = strdup(tmpfilename);
176 	WriteFile(h, data, (DWORD)datalen, &written, NULL);
177 	/* Closing the fd returned by this function will indeed close h. */
178 	return _open_osfhandle((intptr_t)h,_O_RDONLY);
179 #endif
180 }
181 
182 #ifndef _WIN32
183 pid_t
regress_fork(void)184 regress_fork(void)
185 {
186 	pid_t pid = fork();
187 #ifdef FORK_BREAKS_GCOV
188 	vproc_transaction_begin(0);
189 #endif
190 	return pid;
191 }
192 #endif
193 
194 static void
ignore_log_cb(int s,const char * msg)195 ignore_log_cb(int s, const char *msg)
196 {
197 }
198 
199 /**
200  * Put into the real time scheduling class for better timers latency.
201  * https://developer.apple.com/library/archive/technotes/tn2169/_index.html#//apple_ref/doc/uid/DTS40013172-CH1-TNTAG6000
202  */
203 #if defined(__APPLE__)
move_pthread_to_realtime_scheduling_class(pthread_t pthread)204 static void move_pthread_to_realtime_scheduling_class(pthread_t pthread)
205 {
206 	mach_timebase_info_data_t info;
207 	mach_timebase_info(&info);
208 
209 	const uint64_t NANOS_PER_MSEC = 1000000ULL;
210 	double clock2abs =
211 		((double)info.denom / (double)info.numer) * NANOS_PER_MSEC;
212 
213 	thread_time_constraint_policy_data_t policy;
214 	policy.period      = 0;
215 	policy.computation = (uint32_t)(5 * clock2abs); // 5 ms of work
216 	policy.constraint  = (uint32_t)(10 * clock2abs);
217 	policy.preemptible = FALSE;
218 
219 	int kr = thread_policy_set(pthread_mach_thread_np(pthread),
220 		THREAD_TIME_CONSTRAINT_POLICY,
221 		(thread_policy_t)&policy,
222 		THREAD_TIME_CONSTRAINT_POLICY_COUNT);
223 	if (kr != KERN_SUCCESS) {
224 		mach_error("thread_policy_set:", kr);
225 		exit(1);
226 	}
227 }
228 
thread_setup(THREAD_T pthread)229 void thread_setup(THREAD_T pthread)
230 {
231 	move_pthread_to_realtime_scheduling_class(pthread);
232 }
233 #else /** \__APPLE__ */
thread_setup(THREAD_T pthread)234 void thread_setup(THREAD_T pthread) {}
235 #endif /** \!__APPLE__ */
236 
237 
238 void *
basic_test_setup(const struct testcase_t * testcase)239 basic_test_setup(const struct testcase_t *testcase)
240 {
241 	struct event_base *base = NULL;
242 	evutil_socket_t spair[2] = { -1, -1 };
243 	struct basic_test_data *data = NULL;
244 
245 	thread_setup(THREAD_SELF());
246 
247 #ifndef _WIN32
248 	if (testcase->flags & TT_ENABLE_IOCP_FLAG)
249 		return (void*)TT_SKIP;
250 #endif
251 
252 	if (testcase->flags & TT_ENABLE_DEBUG_MODE &&
253 		!libevent_tests_running_in_debug_mode) {
254 		event_enable_debug_mode();
255 		libevent_tests_running_in_debug_mode = 1;
256 	}
257 
258 	if (testcase->flags & TT_NEED_THREADS) {
259 		if (!(testcase->flags & TT_FORK))
260 			return NULL;
261 #if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
262 		if (evthread_use_pthreads())
263 			exit(1);
264 #elif defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
265 		if (evthread_use_windows_threads())
266 			exit(1);
267 #else
268 		return (void*)TT_SKIP;
269 #endif
270 	}
271 
272 	if (testcase->flags & TT_NEED_SOCKETPAIR) {
273 		if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, spair) == -1) {
274 			fprintf(stderr, "%s: socketpair\n", __func__);
275 			exit(1);
276 		}
277 
278 		if (evutil_make_socket_nonblocking(spair[0]) == -1) {
279 			fprintf(stderr, "fcntl(O_NONBLOCK)");
280 			exit(1);
281 		}
282 
283 		if (evutil_make_socket_nonblocking(spair[1]) == -1) {
284 			fprintf(stderr, "fcntl(O_NONBLOCK)");
285 			exit(1);
286 		}
287 	}
288 	if (testcase->flags & TT_NEED_BASE) {
289 		if (testcase->flags & TT_LEGACY)
290 			base = event_init();
291 		else
292 			base = event_base_new();
293 		if (!base)
294 			exit(1);
295 	}
296 	if (testcase->flags & TT_ENABLE_IOCP_FLAG) {
297 		if (event_base_start_iocp_(base, 0)<0) {
298 			event_base_free(base);
299 			return (void*)TT_SKIP;
300 		}
301 	}
302 
303 	if (testcase->flags & TT_NEED_DNS) {
304 		evdns_set_log_fn(dnslogcb);
305 		if (evdns_init())
306 			return NULL; /* fast failure */ /*XXX asserts. */
307 	}
308 
309 	if (testcase->flags & TT_NO_LOGS)
310 		event_set_log_callback(ignore_log_cb);
311 
312 	data = calloc(1, sizeof(*data));
313 	if (!data)
314 		exit(1);
315 	data->base = base;
316 	data->pair[0] = spair[0];
317 	data->pair[1] = spair[1];
318 	data->setup_data = testcase->setup_data;
319 	return data;
320 }
321 
322 int
basic_test_cleanup(const struct testcase_t * testcase,void * ptr)323 basic_test_cleanup(const struct testcase_t *testcase, void *ptr)
324 {
325 	struct basic_test_data *data = ptr;
326 
327 	if (testcase->flags & TT_NO_LOGS)
328 		event_set_log_callback(NULL);
329 
330 	if (testcase->flags & TT_NEED_SOCKETPAIR) {
331 		if (data->pair[0] != -1)
332 			evutil_closesocket(data->pair[0]);
333 		if (data->pair[1] != -1)
334 			evutil_closesocket(data->pair[1]);
335 	}
336 
337 	if (testcase->flags & TT_NEED_DNS) {
338 		evdns_shutdown(0);
339 	}
340 
341 	if (testcase->flags & TT_NEED_BASE) {
342 		if (data->base) {
343 			event_base_assert_ok_(data->base);
344 			event_base_free(data->base);
345 		}
346 	}
347 
348 	if (testcase->flags & TT_FORK)
349 		libevent_global_shutdown();
350 
351 	free(data);
352 
353 	return 1;
354 }
355 
356 const struct testcase_setup_t basic_setup = {
357 	basic_test_setup, basic_test_cleanup
358 };
359 
360 /* The "data" for a legacy test is just a pointer to the void fn(void)
361    function implementing the test case.  We need to set up some globals,
362    though, since that's where legacy tests expect to find a socketpair
363    (sometimes) and a global event_base (sometimes).
364  */
365 static void *
legacy_test_setup(const struct testcase_t * testcase)366 legacy_test_setup(const struct testcase_t *testcase)
367 {
368 	struct basic_test_data *data = basic_test_setup(testcase);
369 	if (data == (void*)TT_SKIP || data == NULL)
370 		return data;
371 	global_base = data->base;
372 	pair[0] = data->pair[0];
373 	pair[1] = data->pair[1];
374 	data->legacy_test_fn = testcase->setup_data;
375 	return data;
376 }
377 
378 /* This function is the implementation of every legacy test case.  It
379    sets test_ok to 0, invokes the test function, and tells tinytest that
380    the test failed if the test didn't set test_ok to 1.
381  */
382 void
run_legacy_test_fn(void * ptr)383 run_legacy_test_fn(void *ptr)
384 {
385 	struct basic_test_data *data = ptr;
386 	test_ok = called = 0;
387 
388 	in_legacy_test_wrapper = 1;
389 	data->legacy_test_fn(); /* This part actually calls the test */
390 	in_legacy_test_wrapper = 0;
391 
392 	if (!test_ok)
393 		tt_abort_msg("Legacy unit test failed");
394 
395 end:
396 	test_ok = 0;
397 }
398 
399 /* This function doesn't have to clean up ptr (which is just a pointer
400    to the test function), but it may need to close the socketpair or
401    free the event_base.
402  */
403 static int
legacy_test_cleanup(const struct testcase_t * testcase,void * ptr)404 legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
405 {
406 	int r = basic_test_cleanup(testcase, ptr);
407 	pair[0] = pair[1] = -1;
408 	global_base = NULL;
409 	return r;
410 }
411 
412 const struct testcase_setup_t legacy_setup = {
413 	legacy_test_setup, legacy_test_cleanup
414 };
415 
416 /* ============================================================ */
417 
418 #if (!defined(EVENT__HAVE_PTHREADS) && !defined(_WIN32)) || defined(EVENT__DISABLE_THREAD_SUPPORT)
419 struct testcase_t thread_testcases[] = {
420 	{ "basic", NULL, TT_SKIP, NULL, NULL },
421 	END_OF_TESTCASES
422 };
423 #endif
424 
425 struct testgroup_t testgroups[] = {
426 	{ "main/", main_testcases },
427 	{ "heap/", minheap_testcases },
428 	{ "et/", edgetriggered_testcases },
429 	{ "finalize/", finalize_testcases },
430 	{ "evbuffer/", evbuffer_testcases },
431 	{ "signal/", signal_testcases },
432 	{ "util/", util_testcases },
433 	{ "bufferevent/", bufferevent_testcases },
434 	{ "http/", http_testcases },
435 	{ "dns/", dns_testcases },
436 	{ "evtag/", evtag_testcases },
437 	{ "rpc/", rpc_testcases },
438 	{ "thread/", thread_testcases },
439 	{ "listener/", listener_testcases },
440 #ifdef _WIN32
441 	{ "iocp/", iocp_testcases },
442 	{ "iocp/bufferevent/", bufferevent_iocp_testcases },
443 	{ "iocp/listener/", listener_iocp_testcases },
444 	{ "iocp/http/", http_iocp_testcases },
445 #endif
446 #ifdef EVENT__HAVE_OPENSSL
447 	{ "ssl/", ssl_testcases },
448 #endif
449 	END_OF_GROUPS
450 };
451 
452 const char *alltests[] = { "+..", NULL };
453 const char *livenettests[] = {
454 	"+util/getaddrinfo_live",
455 	"+dns/gethostby..",
456 	"+dns/resolve_reverse",
457 	NULL
458 };
459 const char *finetimetests[] = {
460 	"+util/monotonic_res_precise",
461 	"+util/monotonic_res_fallback",
462 	"+thread/deferred_cb_skew",
463 	"+http/connection_retry",
464 	"+http/https_connection_retry",
465 	NULL
466 };
467 struct testlist_alias_t testaliases[] = {
468 	{ "all", alltests },
469 	{ "live_net", livenettests },
470 	{ "fine_timing", finetimetests },
471 	END_OF_ALIASES
472 };
473 
474 int libevent_tests_running_in_debug_mode = 0;
475 
476 int
main(int argc,const char ** argv)477 main(int argc, const char **argv)
478 {
479 #ifdef _WIN32
480 	WORD wVersionRequested;
481 	WSADATA wsaData;
482 
483 	wVersionRequested = MAKEWORD(2, 2);
484 
485 	(void) WSAStartup(wVersionRequested, &wsaData);
486 #endif
487 
488 #ifndef _WIN32
489 	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
490 		return 1;
491 #endif
492 
493 #ifdef _WIN32
494 	tinytest_skip(testgroups, "http/connection_retry");
495 	tinytest_skip(testgroups, "http/https_connection_retry");
496 	tinytest_skip(testgroups, "http/read_on_write_error");
497 #endif
498 
499 #ifndef EVENT__DISABLE_THREAD_SUPPORT
500 	if (!getenv("EVENT_NO_DEBUG_LOCKS"))
501 		evthread_enable_lock_debugging();
502 #endif
503 
504 	if (getenv("EVENT_DEBUG_MODE")) {
505 		event_enable_debug_mode();
506 		libevent_tests_running_in_debug_mode = 1;
507 	}
508 	if (getenv("EVENT_DEBUG_LOGGING_ALL")) {
509 		event_enable_debug_logging(EVENT_DBG_ALL);
510 	}
511 
512 	tinytest_set_aliases(testaliases);
513 
514 	evutil_weakrand_seed_(&test_weakrand_state, 0);
515 
516 	if (getenv("EVENT_NO_FILE_BUFFERING")) {
517 		setbuf(stdout, NULL);
518 		setbuf(stderr, NULL);
519 	}
520 
521 	if (tinytest_main(argc,argv,testgroups))
522 		return 1;
523 
524 	libevent_global_shutdown();
525 
526 	return 0;
527 }
528 
529