File: send_receive.c

package info (click to toggle)
netexpect 0.22-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,672 kB
  • ctags: 3,840
  • sloc: ansic: 19,903; sh: 14,032; xml: 3,280; yacc: 1,179; lex: 469; makefile: 185
file content (497 lines) | stat: -rw-r--r-- 12,601 bytes parent folder | download | duplicates (3)
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/* send_expect.c
  
   The "send_receive" Tcl command is implemented here.

   Note that our "send_receive" command has nothing to do with Scapy's
   send-and-receive family of functions - our "send_expect" command is
   equivalent to Scapy's send-and-receive family of functions, and
   "send_receive" is just a simple thoughput tester that injects stimuli
   and then counts the number of received packets.

   Copyright (C) 2007, 2008, 2009, 2010 Eloy Paris

   This is part of Network Expect.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "includes.h"

#include "nexp_speakers.h"
#include "util-tcl.h"

/*
 * List of listeners we'll monitor for answers to injected stimulus. The
 * maximum number of listeners in this list is just an arbitrary number.
 * I reckon most people will only use a handful of listeners at the most,
 * and dynamically managing the size of this list is not worth the trouble.
 */
static struct nexp_listener *listener;

static struct timeval timeout, receive_start_time, curr_time;

static int count;
static pcb_t pcb;

static int nreceived;

static void
usage(void)
{
    fprintf(stderr, "\
usage: send_receive [-speaker <speaker ID>] [-listener <listener ID>]\n\
          [-count <count>] [-delay <secs>] [-rate <pps>] [-timeout <secs>]\n\
          <PDU definition>");
}

static int
process_options(Tcl_Interp *interp, int argc, Tcl_Obj * const *objv)
{
    int i, index;
    char *pdudef = NULL; 
    double delay, t;
    char errbuf[PDU_ERRBUF_SIZE];
    static const char *options[] = {
	"-o", "-i", "-delay", "-rate", "-timeout", "-count", NULL
    };
    enum options {
	OPT_SPEAKER, OPT_LISTENER, OPT_DELAY, OPT_RATE, OPT_TIMEOUT,
	OPT_COUNT
    };

    /*
     * Parse command-line arguments.
     */
    for (i = 1; i < argc && *Tcl_GetString(objv[i]) == '-'; i++) {
	if (Tcl_GetIndexFromObj(interp, objv[i], options, "option", 0, &index)
	    != TCL_OK)
	    return -1;

	switch ( (enum options) index) {
	case OPT_SPEAKER:
	    if (++i >= argc) {
		Tcl_WrongNumArgs(interp, 1, objv, "-o speaker");
		goto error;
	    }

	    pcb.speaker = lookup_speaker(Tcl_GetString(objv[i]) );
	    if (!pcb.speaker) {
		nexp_error(interp, "No speaker named \"%s\". Use "
			   "\"spawn_network -info\" to find out existing "
			   "speakers.", Tcl_GetString(objv[i]) );
		goto error;
	    }
	    break;
	case OPT_LISTENER:
	    if (++i >= argc) {
		Tcl_WrongNumArgs(interp, 1, objv, "-o listener");
		goto error;
	    }

	    listener = lookup_listener(Tcl_GetString(objv[i]) );
	    if (!listener) {
		nexp_error(interp, "No listener named \"%s\". Use "
			   "\"spawn_network -info\" to find out existing "
			   "listeners.", Tcl_GetString(objv[i]) );
		goto error;
	    }

	    if (listener->type != LISTENER_LIVE) {
		nexp_error(interp, "The send_expect command only supports "
				   "live listeners.");
		goto error;
	    }
	    break;
	case OPT_DELAY:
	    if (++i >= argc) {
		Tcl_WrongNumArgs(interp, 1, objv, "-d seconds");
		goto error;
	    }

	    if (Tcl_GetDoubleFromObj(interp, objv[i], &delay) != TCL_OK)
		goto error;

	    pcb.delay.tv_sec = delay;
	    pcb.delay.tv_usec = (delay - pcb.delay.tv_sec)*1000000UL;
	    break;
	case OPT_RATE:
	    if (++i >= argc) {
		Tcl_WrongNumArgs(interp, 1, objv, "-r PPS");
		goto error;
	    }

	    /* Convert a packets-per-second rate to a usecs delay */
	    if (Tcl_GetDoubleFromObj(interp, objv[i], &delay) != TCL_OK)
		goto error;

	    if (delay == 0.0) {
		nexp_error(interp, "Rate can't be 0 packets per second.");
		goto error;
	    }

	    delay = 1/delay;

	    pcb.delay.tv_sec = delay;
	    pcb.delay.tv_usec = (delay - pcb.delay.tv_sec)*1000000UL;
	    break;
	case OPT_TIMEOUT:
	    if (++i >= argc) {
		Tcl_WrongNumArgs(interp, 1, objv, "-timeout seconds");
		goto error;
	    }

	    t = strtod(Tcl_GetString(objv[i]), NULL);
	    if (t < 0.0) {
		nexp_error(interp, "Timeout can't be negative");
		goto error;
	    }

	    timeout.tv_sec = t;
	    timeout.tv_usec = (t - timeout.tv_sec)*1000000UL;
	    break;
	case OPT_COUNT:
	    if (++i >= argc) {
		Tcl_WrongNumArgs(interp, 1, objv, "-c npackets");
		goto error;
	    }

	    if (Tcl_GetIntFromObj(interp, objv[i], &count) != TCL_OK)
		goto error;
	    break;
	}
    }

    /*
     * We treat whatever is left on the command line, i.e. anything that
     * is not an option (anything that doesn't start with '-'), as a PDU
     * definition.
     */
    pdudef = copy_objv(argc - i, &objv[i]);
    if (!pdudef) {
	usage();
	return -1;
    }

#ifdef DEBUG
    printf("PDU definition = %s\n", pdudef);
#endif

    if ( (pcb.pdu = pb_parsedef(pdudef, errbuf) ) == NULL) {
	nexp_error(interp, "%s", errbuf);
	goto error;
    }

    pcb.def = pdudef;

    return 0;

error:
    if (pdudef)
	free(pdudef);

    return -1;
}

static int
send_packets(void)
{
    int i, j;
    int packet_count, packets_sent;
    uint8_t *packet;
    size_t packet_size;

    packet_count = count ? count : pb_permutation_count(pcb.pdu);
    packet = xmalloc(pb_len(pcb.pdu) );

    for (packets_sent = i = 0; i < packet_count; i++) {
	packet_size = pb_build(pcb.pdu, packet, NULL);

	for (j = 0; j < pcb.repeat_count + 1; j++) {
	    /*
	     * Handle inter-packet sending delay.
	     */
	    if (timerisset(&pcb.delay)
		&& timerisset(&pcb.speaker->ts) ) {
		struct timeval now, later;

		timeradd(&pcb.speaker->ts, &pcb.delay, &later);

		gettimeofday(&now, NULL);
		/*
		 * Some versions of Solaris (seen in Solaris 8) don't
		 * like using timercmp() with "<=" or ">=". Rearranging
		 * the operands and just using '>' or '<' works around
		 * this limitation.
		 */
		while (timercmp(&later, &now, >) )
		    gettimeofday(&now, NULL);
	    }

	    nexp_pdu_output(&pcb, packet, packet_size);

	    if (vflag)
		putchar('S');

	    packets_sent++;
	}
    }

    if (vflag)
	putchar('\n');

    free(packet);

    return packets_sent;
}

/*
 * Process a received packet where "process" just means "count".
 */
static void
process_pkt(u_char *user _U_, const struct pcap_pkthdr *h,
	    const u_char *bytes _U_)
{
    curr_time = h->ts;

    if (!timerisset(&receive_start_time) )
	receive_start_time = curr_time;

    nreceived++;
}

/*
 * Handles the SIGUSR1 signal sent by the forked process that injects packets.
 * This happens when the forked process is finished injecting packets. This
 * handler needs to set an interval timer that will let us know, when it
 * expires, that packet reception needs to stop.
 */
static void
sigusr1_handler(int signum _U_)
{
    struct itimerval timer;
#ifdef DEBUG
    printf("Caught SIGUSR1 (%d); packet injection has finished\n", signum);
#endif

    timer.it_interval = timer.it_value = timeout;

    if (setitimer(ITIMER_REAL, &timer, NULL) == -1)
	fprintf(stderr, "setitimer(): %s (errno = %d)\n", strerror(errno),
		errno);
}

static void
sigalrm_handler(int signum _U_)
{
    struct itimerval timer;
#ifdef DEBUG
    printf("Caught SIGALRM (%d); packet reception has finished\n", signum);
#endif

    /* Stop timer */
    timerclear(&timer.it_interval);
    timerclear(&timer.it_value);

    if (setitimer(ITIMER_REAL, &timer, NULL) == -1)
	fprintf(stderr, "setitimer(): %s (errno = %d)\n", strerror(errno),
		errno);

    pcap_breakloop(listener->_live.pd);
}

static int
NExp_SendReceiveObjCmd(ClientData clientData _U_, Tcl_Interp *interp, int argc,
		       Tcl_Obj * const *objv)
{
    int retval;
    struct timeval time_delta;
    Tcl_Obj *obj;
    double receive_time;
    int pfds[2]; /* Pipe file descriptors */
    int pid;
    int nsent;
    struct sigaction sigusr1_action, sigalrm_action;

    listener = NULL;
    timeout.tv_sec = 1; timeout.tv_usec = 0;
    nreceived = 0;

    memset(&pcb, 0, sizeof(pcb) );

    retval = process_options(interp, argc, objv);
    if (retval == -1)
	goto error;

    /*
     * Make sure we have a listener we can use to listen for answers.
     */
    if (!listener) {
	listener = lookup_listener(nexp_get_var(interp,
						LISTENER_SPAWN_ID_VARNAME) );
	if (!listener) {
	    nexp_error(interp, "Can't find a suitable listener! Use "
			       "spawn_network to create one.");
	    goto error;
	}
    }

    /*
     * Make sure the PCB has an assigned speaker: if the user has not
     * explicitely specified a speaker, then we use the default speaker,
     * which is referred to by name via the Tcl variable "speaker_id"
     * (SPEAKER_SPAWN_ID_VARNAME).
     */
    if (!pcb.speaker) {
	pcb.speaker = lookup_speaker(nexp_get_var(interp,
					SPEAKER_SPAWN_ID_VARNAME) );
	if (!pcb.speaker) {
	    nexp_error(interp, "Can't find a suitable speaker! Use "
			       "spawn_network to create one.");
	    goto error;
	}
    }

    if (pipe(pfds) == -1) {
	nexp_error(interp, "Couldn't open pipe: %s", strerror(errno) );
	goto error;
    }

    /* Set up handler for SIGUSR1 (indicates end of injection) */
    memset(&sigusr1_action, 0, sizeof(sigusr1_action) );
    sigusr1_action.sa_handler = sigusr1_handler;
    sigusr1_action.sa_flags = SA_RESETHAND;
    sigemptyset(&sigusr1_action.sa_mask);
    sigaction(SIGUSR1, &sigusr1_action, NULL);

    /* Set up handler for SIGALRM (indicates end of reception) */
    memset(&sigalrm_action, 0, sizeof(sigalrm_action) );
    sigalrm_action.sa_handler = sigalrm_handler;
    sigalrm_action.sa_flags = SA_RESETHAND;
    sigemptyset(&sigalrm_action.sa_mask);
    sigaction(SIGALRM, &sigalrm_action, NULL);

    /*
     * Stimulus injection is done by a forked (child) process. Receiving
     * packets is done by the parent process.
     */

    pid = fork();
    if (pid == 0) {
	/*
	 * Child.
	 */

	close(pfds[0]); /* Child doesn't read from parent */

	nsent = send_packets();

	/* Let parent know how many packets we sent. */
	write(pfds[1], &nsent, sizeof(nsent) );

	/* Let parent know that packet injection has finished. */
	kill(getppid(), SIGUSR1);

	close(pfds[1]);
	_exit(EXIT_SUCCESS);
    } else if (pid < 0) {
	nexp_error(interp, "fork(): %s", strerror(errno) );
	goto error;
    }

    /*
     * Parent.
     */

    /* All the work is done by the pcap_handler callback function. */
    retval = pcap_loop(listener->_live.pd, -1, process_pkt, NULL);
    if (retval == -1) {
	nexp_error(interp, "pcap_loop(): %s", pcap_geterr(listener->_live.pd) );
	goto error;
    }

    if (vflag)
	putchar('\n');

    wait(NULL);

    /*
     * Done sending and receiving packets.
     */

    /*
     * Read from the pipe between parent and child the number of packets
     * sent by the child process.
     */
    retval = read(pfds[0], &nsent, sizeof(nsent) );
    if (retval == 0) {
	/* EOF */
	nexp_error(interp, "read(): got EOF. This should not happen!");
	goto error;
    } else if (retval == -1) {
	/* read() error */
	nexp_error(interp, "read(): %s", strerror(errno) );
	goto error;
    } else if (retval != sizeof(nsent) ) {
	/* We got less than what we asked for */
	nexp_error(interp, "read() read less than requested. This "
			   "should not happen!");
	goto error;
    }

    close(pfds[0]);

    if (vflag)
	printf("Sent %d packets; received %d\n", nsent, nreceived);

    obj = Tcl_NewIntObj(nsent);
    Tcl_SetVar2Ex(interp, "_", "sent", obj, 0);

    obj = Tcl_NewIntObj(nreceived);
    Tcl_SetVar2Ex(interp, "_", "received", obj, 0);

    time_delta = curr_time;
    timersub(&time_delta, &receive_start_time, &time_delta);

    receive_time = time_delta.tv_sec + time_delta.tv_usec/1e6;

    obj = Tcl_NewDoubleObj(receive_time);
    Tcl_SetVar2Ex(interp, "_", "time", obj, 0);

    obj = Tcl_NewDoubleObj( (nreceived - 1)/receive_time);
    Tcl_SetVar2Ex(interp, "_", "pps", obj, 0);

    /*
     * Clean up.
     */

    pcb_destroy(&pcb);

    return TCL_OK;

error:
    return TCL_ERROR;
}

static struct nexp_cmd_data cmd_data[] = {
    {"send_receive", NExp_SendReceiveObjCmd, NULL, 0, 0},

    {NULL, NULL, NULL, 0, 0}
};

void
nexp_init_send_receive_cmd(Tcl_Interp *interp)
{
    nexp_create_commands(interp, cmd_data);
}