1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
/*
* Nsock regression test suite
* Same license as nmap -- see https://nmap.org/book/man-legal.html
*/
#include "test-common.h"
#include <time.h>
#define TIMERS_BUFFLEN 1024
struct timer_test_data {
nsock_pool nsp;
nsock_event_id timer_list[TIMERS_BUFFLEN];
size_t timer_count;
int stop; /* set to non-zero to stop the test */
};
static void timer_handler(nsock_pool nsp, nsock_event nse, void *tdata);
static void add_timer(struct timer_test_data *ttd, int timeout) {
nsock_event_id id;
id = nsock_timer_create(ttd->nsp, timer_handler, timeout, ttd);
ttd->timer_list[ttd->timer_count++] = id;
}
static void timer_handler(nsock_pool nsp, nsock_event nse, void *tdata) {
struct timer_test_data *ttd = (struct timer_test_data *)tdata;
int rnd, rnd2;
if (nse_status(nse) != NSE_STATUS_SUCCESS) {
ttd->stop = -nsock_pool_get_error(nsp);
return;
}
if (ttd->timer_count > TIMERS_BUFFLEN - 3)
return;
rnd = rand() % ttd->timer_count;
rnd2 = rand() % 3;
switch (rnd2) {
case 0:
/* Do nothing */
/* Actually I think I'll create two timers :) */
add_timer(ttd, rand() % 3000);
add_timer(ttd, rand() % 3000);
break;
case 1:
/* Try to kill another id (which may or may not be active */
nsock_event_cancel(nsp, ttd->timer_list[rnd], rand() % 2);
break;
case 2:
/* Create a new timer */
add_timer(ttd, rand() % 3000);
break;
default:
assert(0);
}
}
static int timer_setup(void **tdata) {
struct timer_test_data *ttd;
srand(time(NULL));
ttd = calloc(1, sizeof(struct timer_test_data));
if (ttd == NULL)
return -ENOMEM;
ttd->nsp = nsock_pool_new(NULL);
AssertNonNull(ttd->nsp);
*tdata = ttd;
return 0;
}
static int timer_teardown(void *tdata) {
struct timer_test_data *ttd = (struct timer_test_data *)tdata;
if (tdata) {
nsock_pool_delete(ttd->nsp);
free(tdata);
}
return 0;
}
static int timer_totalmess(void *tdata) {
struct timer_test_data *ttd = (struct timer_test_data *)tdata;
enum nsock_loopstatus loopret;
int num_loops = 0;
add_timer(ttd, 1800);
add_timer(ttd, 800);
add_timer(ttd, 1300);
add_timer(ttd, 0);
add_timer(ttd, 100);
/* Now lets get this party started right! */
while (num_loops++ < 5 && !ttd->stop) {
loopret = nsock_loop(ttd->nsp, 1500);
switch (loopret) {
case NSOCK_LOOP_TIMEOUT:
/* nothing to do */
break;
case NSOCK_LOOP_NOEVENTS:
return 0;
default:
return -(nsock_pool_get_error(ttd->nsp));
}
}
return ttd->stop;
}
const struct test_case TestTimer = {
.t_name = "test timer operations",
.t_setup = timer_setup,
.t_run = timer_totalmess,
.t_teardown = timer_teardown
};
|