xref: /freebsd/sbin/ipfw/dummynet.c (revision 40a8ac8f62b535d30349faf28cf47106b7041b83)
1 /*
2  * Copyright (c) 2002-2003,2010 Luigi Rizzo
3  *
4  * Redistribution and use in source forms, with and without modification,
5  * are permitted provided that this entire comment appears intact.
6  *
7  * Redistribution in binary form may occur without any restrictions.
8  * Obviously, it would be nice if you gave credit where credit is due
9  * but requiring it would be too onerous.
10  *
11  * This software is provided ``AS IS'' without any warranties of any kind.
12  *
13  * $FreeBSD$
14  *
15  * dummynet support
16  */
17 
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 /* XXX there are several sysctl leftover here */
21 #include <sys/sysctl.h>
22 
23 #include "ipfw2.h"
24 
25 #include <ctype.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <libutil.h>
29 #include <netdb.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sysexits.h>
34 
35 #include <net/if.h>
36 #include <netinet/in.h>
37 #include <netinet/ip_fw.h>
38 #include <netinet/ip_dummynet.h>
39 #include <arpa/inet.h>	/* inet_ntoa */
40 
41 
42 static struct _s_x dummynet_params[] = {
43 	{ "plr",		TOK_PLR },
44 	{ "noerror",		TOK_NOERROR },
45 	{ "buckets",		TOK_BUCKETS },
46 	{ "dst-ip",		TOK_DSTIP },
47 	{ "src-ip",		TOK_SRCIP },
48 	{ "dst-port",		TOK_DSTPORT },
49 	{ "src-port",		TOK_SRCPORT },
50 	{ "proto",		TOK_PROTO },
51 	{ "weight",		TOK_WEIGHT },
52 	{ "lmax",		TOK_LMAX },
53 	{ "maxlen",		TOK_LMAX },
54 	{ "all",		TOK_ALL },
55 	{ "mask",		TOK_MASK }, /* alias for both */
56 	{ "sched_mask",		TOK_SCHED_MASK },
57 	{ "flow_mask",		TOK_FLOW_MASK },
58 	{ "droptail",		TOK_DROPTAIL },
59 	{ "ecn",		TOK_ECN },
60 	{ "red",		TOK_RED },
61 	{ "gred",		TOK_GRED },
62 	{ "bw",			TOK_BW },
63 	{ "bandwidth",		TOK_BW },
64 	{ "delay",		TOK_DELAY },
65 	{ "link",		TOK_LINK },
66 	{ "pipe",		TOK_PIPE },
67 	{ "queue",		TOK_QUEUE },
68 	{ "flowset",		TOK_FLOWSET },
69 	{ "sched",		TOK_SCHED },
70 	{ "pri",		TOK_PRI },
71 	{ "priority",		TOK_PRI },
72 	{ "type",		TOK_TYPE },
73 	{ "flow-id",		TOK_FLOWID},
74 	{ "dst-ipv6",		TOK_DSTIP6},
75 	{ "dst-ip6",		TOK_DSTIP6},
76 	{ "src-ipv6",		TOK_SRCIP6},
77 	{ "src-ip6",		TOK_SRCIP6},
78 	{ "profile",		TOK_PROFILE},
79 	{ "burst",		TOK_BURST},
80 	{ "dummynet-params",	TOK_NULL },
81 	{ NULL, 0 }	/* terminator */
82 };
83 
84 #define O_NEXT(p, len) ((void *)((char *)p + len))
85 
86 static void
87 oid_fill(struct dn_id *oid, int len, int type, uintptr_t id)
88 {
89 	oid->len = len;
90 	oid->type = type;
91 	oid->subtype = 0;
92 	oid->id = id;
93 }
94 
95 /* make room in the buffer and move the pointer forward */
96 static void *
97 o_next(struct dn_id **o, int len, int type)
98 {
99 	struct dn_id *ret = *o;
100 	oid_fill(ret, len, type, 0);
101 	*o = O_NEXT(*o, len);
102 	return ret;
103 }
104 
105 #if 0
106 static int
107 sort_q(void *arg, const void *pa, const void *pb)
108 {
109 	int rev = (co.do_sort < 0);
110 	int field = rev ? -co.do_sort : co.do_sort;
111 	long long res = 0;
112 	const struct dn_flow_queue *a = pa;
113 	const struct dn_flow_queue *b = pb;
114 
115 	switch (field) {
116 	case 1: /* pkts */
117 		res = a->len - b->len;
118 		break;
119 	case 2: /* bytes */
120 		res = a->len_bytes - b->len_bytes;
121 		break;
122 
123 	case 3: /* tot pkts */
124 		res = a->tot_pkts - b->tot_pkts;
125 		break;
126 
127 	case 4: /* tot bytes */
128 		res = a->tot_bytes - b->tot_bytes;
129 		break;
130 	}
131 	if (res < 0)
132 		res = -1;
133 	if (res > 0)
134 		res = 1;
135 	return (int)(rev ? res : -res);
136 }
137 #endif
138 
139 /* print a mask and header for the subsequent list of flows */
140 static void
141 print_mask(struct ipfw_flow_id *id)
142 {
143 	if (!IS_IP6_FLOW_ID(id)) {
144 		printf("    "
145 		    "mask: %s 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
146 		    id->extra ? "queue," : "",
147 		    id->proto,
148 		    id->src_ip, id->src_port,
149 		    id->dst_ip, id->dst_port);
150 	} else {
151 		char buf[255];
152 		printf("\n        mask: %sproto: 0x%02x, flow_id: 0x%08x,  ",
153 		    id->extra ? "queue," : "",
154 		    id->proto, id->flow_id6);
155 		inet_ntop(AF_INET6, &(id->src_ip6), buf, sizeof(buf));
156 		printf("%s/0x%04x -> ", buf, id->src_port);
157 		inet_ntop(AF_INET6, &(id->dst_ip6), buf, sizeof(buf));
158 		printf("%s/0x%04x\n", buf, id->dst_port);
159 	}
160 }
161 
162 static void
163 print_header(struct ipfw_flow_id *id)
164 {
165 	if (!IS_IP6_FLOW_ID(id))
166 		printf("BKT Prot ___Source IP/port____ "
167 		    "____Dest. IP/port____ "
168 		    "Tot_pkt/bytes Pkt/Byte Drp\n");
169 	else
170 		printf("BKT ___Prot___ _flow-id_ "
171 		    "______________Source IPv6/port_______________ "
172 		    "_______________Dest. IPv6/port_______________ "
173 		    "Tot_pkt/bytes Pkt/Byte Drp\n");
174 }
175 
176 static void
177 list_flow(struct buf_pr *bp, struct dn_flow *ni)
178 {
179 	char buff[255];
180 	struct protoent *pe = NULL;
181 	struct in_addr ina;
182 	struct ipfw_flow_id *id = &ni->fid;
183 
184 	pe = getprotobynumber(id->proto);
185 		/* XXX: Should check for IPv4 flows */
186 	bprintf(bp, "%3u%c", (ni->oid.id) & 0xff,
187 		id->extra ? '*' : ' ');
188 	if (!IS_IP6_FLOW_ID(id)) {
189 		if (pe)
190 			bprintf(bp, "%-4s ", pe->p_name);
191 		else
192 			bprintf(bp, "%4u ", id->proto);
193 		ina.s_addr = htonl(id->src_ip);
194 		bprintf(bp, "%15s/%-5d ",
195 		    inet_ntoa(ina), id->src_port);
196 		ina.s_addr = htonl(id->dst_ip);
197 		bprintf(bp, "%15s/%-5d ",
198 		    inet_ntoa(ina), id->dst_port);
199 	} else {
200 		/* Print IPv6 flows */
201 		if (pe != NULL)
202 			bprintf(bp, "%9s ", pe->p_name);
203 		else
204 			bprintf(bp, "%9u ", id->proto);
205 		bprintf(bp, "%7d  %39s/%-5d ", id->flow_id6,
206 		    inet_ntop(AF_INET6, &(id->src_ip6), buff, sizeof(buff)),
207 		    id->src_port);
208 		bprintf(bp, " %39s/%-5d ",
209 		    inet_ntop(AF_INET6, &(id->dst_ip6), buff, sizeof(buff)),
210 		    id->dst_port);
211 	}
212 	pr_u64(bp, &ni->tot_pkts, 4);
213 	pr_u64(bp, &ni->tot_bytes, 8);
214 	bprintf(bp, "%2u %4u %3u",
215 	    ni->length, ni->len_bytes, ni->drops);
216 }
217 
218 static void
219 print_flowset_parms(struct dn_fs *fs, char *prefix)
220 {
221 	int l;
222 	char qs[30];
223 	char plr[30];
224 	char red[90];	/* Display RED parameters */
225 
226 	l = fs->qsize;
227 	if (fs->flags & DN_QSIZE_BYTES) {
228 		if (l >= 8192)
229 			sprintf(qs, "%d KB", l / 1024);
230 		else
231 			sprintf(qs, "%d B", l);
232 	} else
233 		sprintf(qs, "%3d sl.", l);
234 	if (fs->plr)
235 		sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
236 	else
237 		plr[0] = '\0';
238 
239 	if (fs->flags & DN_IS_RED) {	/* RED parameters */
240 		sprintf(red,
241 		    "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
242 		    (fs->flags & DN_IS_GENTLE_RED) ? 'G' : ' ',
243 		    1.0 * fs->w_q / (double)(1 << SCALE_RED),
244 		    fs->min_th,
245 		    fs->max_th,
246 		    1.0 * fs->max_p / (double)(1 << SCALE_RED));
247 		if (fs->flags & DN_IS_ECN)
248 			strncat(red, " (ecn)", 6);
249 	} else
250 		sprintf(red, "droptail");
251 
252 	if (prefix[0]) {
253 	    printf("%s %s%s %d queues (%d buckets) %s\n",
254 		prefix, qs, plr, fs->oid.id, fs->buckets, red);
255 	    prefix[0] = '\0';
256 	} else {
257 	    printf("q%05d %s%s %d flows (%d buckets) sched %d "
258 			"weight %d lmax %d pri %d %s\n",
259 		fs->fs_nr, qs, plr, fs->oid.id, fs->buckets,
260 		fs->sched_nr, fs->par[0], fs->par[1], fs->par[2], red);
261 	    if (fs->flags & DN_HAVE_MASK)
262 		print_mask(&fs->flow_mask);
263 	}
264 }
265 
266 static void
267 print_extra_delay_parms(struct dn_profile *p)
268 {
269 	double loss;
270 	if (p->samples_no <= 0)
271 		return;
272 
273 	loss = p->loss_level;
274 	loss /= p->samples_no;
275 	printf("\t profile: name \"%s\" loss %f samples %d\n",
276 		p->name, loss, p->samples_no);
277 }
278 
279 static void
280 flush_buf(char *buf)
281 {
282 	if (buf[0])
283 		printf("%s\n", buf);
284 	buf[0] = '\0';
285 }
286 
287 /*
288  * generic list routine. We expect objects in a specific order, i.e.
289  * PIPES AND SCHEDULERS:
290  *	link; scheduler; internal flowset if any; instances
291  * we can tell a pipe from the number.
292  *
293  * FLOWSETS:
294  *	flowset; queues;
295  * link i (int queue); scheduler i; si(i) { flowsets() : queues }
296  */
297 static void
298 list_pipes(struct dn_id *oid, struct dn_id *end)
299 {
300     char buf[160];	/* pending buffer */
301     int toPrint = 1;	/* print header */
302     struct buf_pr bp;
303 
304     buf[0] = '\0';
305     bp_alloc(&bp, 4096);
306     for (; oid != end; oid = O_NEXT(oid, oid->len)) {
307 	if (oid->len < sizeof(*oid))
308 		errx(1, "invalid oid len %d\n", oid->len);
309 
310 	switch (oid->type) {
311 	default:
312 	    flush_buf(buf);
313 	    printf("unrecognized object %d size %d\n", oid->type, oid->len);
314 	    break;
315 	case DN_TEXT: /* list of attached flowsets */
316 	    {
317 		int i, l;
318 		struct {
319 			struct dn_id id;
320 			uint32_t p[0];
321 		} *d = (void *)oid;
322 		l = (oid->len - sizeof(*oid))/sizeof(d->p[0]);
323 		if (l == 0)
324 		    break;
325 		printf("   Children flowsets: ");
326 		for (i = 0; i < l; i++)
327 			printf("%u ", d->p[i]);
328 		printf("\n");
329 		break;
330 	    }
331 	case DN_CMD_GET:
332 	    if (co.verbose)
333 		printf("answer for cmd %d, len %d\n", oid->type, oid->id);
334 	    break;
335 	case DN_SCH: {
336 	    struct dn_sch *s = (struct dn_sch *)oid;
337 	    flush_buf(buf);
338 	    printf(" sched %d type %s flags 0x%x %d buckets %d active\n",
339 			s->sched_nr,
340 			s->name, s->flags, s->buckets, s->oid.id);
341 	    if (s->flags & DN_HAVE_MASK)
342 		print_mask(&s->sched_mask);
343 	    }
344 	    break;
345 
346 	case DN_FLOW:
347 	    if (toPrint != 0) {
348 		    print_header(&((struct dn_flow *)oid)->fid);
349 		    toPrint = 0;
350 	    }
351 	    list_flow(&bp, (struct dn_flow *)oid);
352 	    printf("%s\n", bp.buf);
353 	    break;
354 
355 	case DN_LINK: {
356 	    struct dn_link *p = (struct dn_link *)oid;
357 	    double b = p->bandwidth;
358 	    char bwbuf[30];
359 	    char burst[5 + 7];
360 
361 	    /* This starts a new object so flush buffer */
362 	    flush_buf(buf);
363 	    /* data rate */
364 	    if (b == 0)
365 		sprintf(bwbuf, "unlimited     ");
366 	    else if (b >= 1000000)
367 		sprintf(bwbuf, "%7.3f Mbit/s", b/1000000);
368 	    else if (b >= 1000)
369 		sprintf(bwbuf, "%7.3f Kbit/s", b/1000);
370 	    else
371 		sprintf(bwbuf, "%7.3f bit/s ", b);
372 
373 	    if (humanize_number(burst, sizeof(burst), p->burst,
374 		    "", HN_AUTOSCALE, 0) < 0 || co.verbose)
375 		sprintf(burst, "%d", (int)p->burst);
376 	    sprintf(buf, "%05d: %s %4d ms burst %s",
377 		p->link_nr % DN_MAX_ID, bwbuf, p->delay, burst);
378 	    }
379 	    break;
380 
381 	case DN_FS:
382 	    print_flowset_parms((struct dn_fs *)oid, buf);
383 	    break;
384 	case DN_PROFILE:
385 	    flush_buf(buf);
386 	    print_extra_delay_parms((struct dn_profile *)oid);
387 	}
388 	flush_buf(buf); // XXX does it really go here ?
389     }
390 
391     bp_free(&bp);
392 }
393 
394 /*
395  * Delete pipe, queue or scheduler i
396  */
397 int
398 ipfw_delete_pipe(int do_pipe, int i)
399 {
400 	struct {
401 		struct dn_id oid;
402 		uintptr_t a[1];	/* add more if we want a list */
403 	} cmd;
404 	oid_fill((void *)&cmd, sizeof(cmd), DN_CMD_DELETE, DN_API_VERSION);
405 	cmd.oid.subtype = (do_pipe == 1) ? DN_LINK :
406 		( (do_pipe == 2) ? DN_FS : DN_SCH);
407 	cmd.a[0] = i;
408 	i = do_cmd(IP_DUMMYNET3, &cmd, cmd.oid.len);
409 	if (i) {
410 		i = 1;
411 		warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", i);
412 	}
413 	return i;
414 }
415 
416 /*
417  * Code to parse delay profiles.
418  *
419  * Some link types introduce extra delays in the transmission
420  * of a packet, e.g. because of MAC level framing, contention on
421  * the use of the channel, MAC level retransmissions and so on.
422  * From our point of view, the channel is effectively unavailable
423  * for this extra time, which is constant or variable depending
424  * on the link type. Additionally, packets may be dropped after this
425  * time (e.g. on a wireless link after too many retransmissions).
426  * We can model the additional delay with an empirical curve
427  * that represents its distribution.
428  *
429  *      cumulative probability
430  *      1.0 ^
431  *          |
432  *      L   +-- loss-level          x
433  *          |                 ******
434  *          |                *
435  *          |           *****
436  *          |          *
437  *          |        **
438  *          |       *
439  *          +-------*------------------->
440  *                      delay
441  *
442  * The empirical curve may have both vertical and horizontal lines.
443  * Vertical lines represent constant delay for a range of
444  * probabilities; horizontal lines correspond to a discontinuty
445  * in the delay distribution: the link will use the largest delay
446  * for a given probability.
447  *
448  * To pass the curve to dummynet, we must store the parameters
449  * in a file as described below, and issue the command
450  *
451  *      ipfw pipe <n> config ... bw XXX profile <filename> ...
452  *
453  * The file format is the following, with whitespace acting as
454  * a separator and '#' indicating the beginning a comment:
455  *
456  *	samples N
457  *		the number of samples used in the internal
458  *		representation (2..1024; default 100);
459  *
460  *	loss-level L
461  *		The probability above which packets are lost.
462  *	       (0.0 <= L <= 1.0, default 1.0 i.e. no loss);
463  *
464  *	name identifier
465  *		Optional a name (listed by "ipfw pipe show")
466  *		to identify the distribution;
467  *
468  *	"delay prob" | "prob delay"
469  *		One of these two lines is mandatory and defines
470  *		the format of the following lines with data points.
471  *
472  *	XXX YYY
473  *		2 or more lines representing points in the curve,
474  *		with either delay or probability first, according
475  *		to the chosen format.
476  *		The unit for delay is milliseconds.
477  *
478  * Data points does not need to be ordered or equal to the number
479  * specified in the "samples" line. ipfw will sort and interpolate
480  * the curve as needed.
481  *
482  * Example of a profile file:
483 
484 	name    bla_bla_bla
485 	samples 100
486 	loss-level    0.86
487 	prob    delay
488 	0       200	# minimum overhead is 200ms
489 	0.5     200
490 	0.5     300
491 	0.8     1000
492 	0.9     1300
493 	1       1300
494 
495  * Internally, we will convert the curve to a fixed number of
496  * samples, and when it is time to transmit a packet we will
497  * model the extra delay as extra bits in the packet.
498  *
499  */
500 
501 #define ED_MAX_LINE_LEN	256+ED_MAX_NAME_LEN
502 #define ED_TOK_SAMPLES	"samples"
503 #define ED_TOK_LOSS	"loss-level"
504 #define ED_TOK_NAME	"name"
505 #define ED_TOK_DELAY	"delay"
506 #define ED_TOK_PROB	"prob"
507 #define ED_TOK_BW	"bw"
508 #define ED_SEPARATORS	" \t\n"
509 #define ED_MIN_SAMPLES_NO	2
510 
511 /*
512  * returns 1 if s is a non-negative number, with at least one '.'
513  */
514 static int
515 is_valid_number(const char *s)
516 {
517 	int i, dots_found = 0;
518 	int len = strlen(s);
519 
520 	for (i = 0; i<len; ++i)
521 		if (!isdigit(s[i]) && (s[i] !='.' || ++dots_found > 1))
522 			return 0;
523 	return 1;
524 }
525 
526 /*
527  * Take as input a string describing a bandwidth value
528  * and return the numeric bandwidth value.
529  * set clocking interface or bandwidth value
530  */
531 static void
532 read_bandwidth(char *arg, int *bandwidth, char *if_name, int namelen)
533 {
534 	if (*bandwidth != -1)
535 		warnx("duplicate token, override bandwidth value!");
536 
537 	if (arg[0] >= 'a' && arg[0] <= 'z') {
538 		if (!if_name) {
539 			errx(1, "no if support");
540 		}
541 		if (namelen >= IFNAMSIZ)
542 			warn("interface name truncated");
543 		namelen--;
544 		/* interface name */
545 		strncpy(if_name, arg, namelen);
546 		if_name[namelen] = '\0';
547 		*bandwidth = 0;
548 	} else {	/* read bandwidth value */
549 		int bw;
550 		char *end = NULL;
551 
552 		bw = strtoul(arg, &end, 0);
553 		if (*end == 'K' || *end == 'k') {
554 			end++;
555 			bw *= 1000;
556 		} else if (*end == 'M' || *end == 'm') {
557 			end++;
558 			bw *= 1000000;
559 		}
560 		if ((*end == 'B' &&
561 			_substrcmp2(end, "Bi", "Bit/s") != 0) ||
562 		    _substrcmp2(end, "by", "bytes") == 0)
563 			bw *= 8;
564 
565 		if (bw < 0)
566 			errx(EX_DATAERR, "bandwidth too large");
567 
568 		*bandwidth = bw;
569 		if (if_name)
570 			if_name[0] = '\0';
571 	}
572 }
573 
574 struct point {
575 	double prob;
576 	double delay;
577 };
578 
579 static int
580 compare_points(const void *vp1, const void *vp2)
581 {
582 	const struct point *p1 = vp1;
583 	const struct point *p2 = vp2;
584 	double res = 0;
585 
586 	res = p1->prob - p2->prob;
587 	if (res == 0)
588 		res = p1->delay - p2->delay;
589 	if (res < 0)
590 		return -1;
591 	else if (res > 0)
592 		return 1;
593 	else
594 		return 0;
595 }
596 
597 #define ED_EFMT(s) EX_DATAERR,"error in %s at line %d: "#s,filename,lineno
598 
599 static void
600 load_extra_delays(const char *filename, struct dn_profile *p,
601 	struct dn_link *link)
602 {
603 	char    line[ED_MAX_LINE_LEN];
604 	FILE    *f;
605 	int     lineno = 0;
606 	int     i;
607 
608 	int     samples = -1;
609 	double  loss = -1.0;
610 	char    profile_name[ED_MAX_NAME_LEN];
611 	int     delay_first = -1;
612 	int     do_points = 0;
613 	struct point    points[ED_MAX_SAMPLES_NO];
614 	int     points_no = 0;
615 
616 	/* XXX link never NULL? */
617 	p->link_nr = link->link_nr;
618 
619 	profile_name[0] = '\0';
620 	f = fopen(filename, "r");
621 	if (f == NULL)
622 		err(EX_UNAVAILABLE, "fopen: %s", filename);
623 
624 	while (fgets(line, ED_MAX_LINE_LEN, f)) {	 /* read commands */
625 		char *s, *cur = line, *name = NULL, *arg = NULL;
626 
627 		++lineno;
628 
629 		/* parse the line */
630 		while (cur) {
631 			s = strsep(&cur, ED_SEPARATORS);
632 			if (s == NULL || *s == '#')
633 				break;
634 			if (*s == '\0')
635 				continue;
636 			if (arg)
637 				errx(ED_EFMT("too many arguments"));
638 			if (name == NULL)
639 				name = s;
640 			else
641 				arg = s;
642 		}
643 		if (name == NULL)	/* empty line */
644 			continue;
645 		if (arg == NULL)
646 			errx(ED_EFMT("missing arg for %s"), name);
647 
648 		if (!strcasecmp(name, ED_TOK_SAMPLES)) {
649 		    if (samples > 0)
650 			errx(ED_EFMT("duplicate ``samples'' line"));
651 		    if (atoi(arg) <=0)
652 			errx(ED_EFMT("invalid number of samples"));
653 		    samples = atoi(arg);
654 		    if (samples>ED_MAX_SAMPLES_NO)
655 			    errx(ED_EFMT("too many samples, maximum is %d"),
656 				ED_MAX_SAMPLES_NO);
657 		    do_points = 0;
658 		} else if (!strcasecmp(name, ED_TOK_BW)) {
659 		    char buf[IFNAMSIZ];
660 		    read_bandwidth(arg, &link->bandwidth, buf, sizeof(buf));
661 		} else if (!strcasecmp(name, ED_TOK_LOSS)) {
662 		    if (loss != -1.0)
663 			errx(ED_EFMT("duplicated token: %s"), name);
664 		    if (!is_valid_number(arg))
665 			errx(ED_EFMT("invalid %s"), arg);
666 		    loss = atof(arg);
667 		    if (loss > 1)
668 			errx(ED_EFMT("%s greater than 1.0"), name);
669 		    do_points = 0;
670 		} else if (!strcasecmp(name, ED_TOK_NAME)) {
671 		    if (profile_name[0] != '\0')
672 			errx(ED_EFMT("duplicated token: %s"), name);
673 		    strncpy(profile_name, arg, sizeof(profile_name) - 1);
674 		    profile_name[sizeof(profile_name)-1] = '\0';
675 		    do_points = 0;
676 		} else if (!strcasecmp(name, ED_TOK_DELAY)) {
677 		    if (do_points)
678 			errx(ED_EFMT("duplicated token: %s"), name);
679 		    delay_first = 1;
680 		    do_points = 1;
681 		} else if (!strcasecmp(name, ED_TOK_PROB)) {
682 		    if (do_points)
683 			errx(ED_EFMT("duplicated token: %s"), name);
684 		    delay_first = 0;
685 		    do_points = 1;
686 		} else if (do_points) {
687 		    if (!is_valid_number(name) || !is_valid_number(arg))
688 			errx(ED_EFMT("invalid point found"));
689 		    if (delay_first) {
690 			points[points_no].delay = atof(name);
691 			points[points_no].prob = atof(arg);
692 		    } else {
693 			points[points_no].delay = atof(arg);
694 			points[points_no].prob = atof(name);
695 		    }
696 		    if (points[points_no].prob > 1.0)
697 			errx(ED_EFMT("probability greater than 1.0"));
698 		    ++points_no;
699 		} else {
700 		    errx(ED_EFMT("unrecognised command '%s'"), name);
701 		}
702 	}
703 
704 	fclose (f);
705 
706 	if (samples == -1) {
707 	    warnx("'%s' not found, assuming 100", ED_TOK_SAMPLES);
708 	    samples = 100;
709 	}
710 
711 	if (loss == -1.0) {
712 	    warnx("'%s' not found, assuming no loss", ED_TOK_LOSS);
713 	    loss = 1;
714 	}
715 
716 	/* make sure that there are enough points. */
717 	if (points_no < ED_MIN_SAMPLES_NO)
718 	    errx(ED_EFMT("too few samples, need at least %d"),
719 		ED_MIN_SAMPLES_NO);
720 
721 	qsort(points, points_no, sizeof(struct point), compare_points);
722 
723 	/* interpolation */
724 	for (i = 0; i<points_no-1; ++i) {
725 	    double y1 = points[i].prob * samples;
726 	    double x1 = points[i].delay;
727 	    double y2 = points[i+1].prob * samples;
728 	    double x2 = points[i+1].delay;
729 
730 	    int ix = y1;
731 	    int stop = y2;
732 
733 	    if (x1 == x2) {
734 		for (; ix<stop; ++ix)
735 		    p->samples[ix] = x1;
736 	    } else {
737 		double m = (y2-y1)/(x2-x1);
738 		double c = y1 - m*x1;
739 		for (; ix<stop ; ++ix)
740 		    p->samples[ix] = (ix - c)/m;
741 	    }
742 	}
743 	p->samples_no = samples;
744 	p->loss_level = loss * samples;
745 	strncpy(p->name, profile_name, sizeof(p->name));
746 }
747 
748 /*
749  * configuration of pipes, schedulers, flowsets.
750  * When we configure a new scheduler, an empty pipe is created, so:
751  *
752  * do_pipe = 1 -> "pipe N config ..." only for backward compatibility
753  *	sched N+Delta type fifo sched_mask ...
754  *	pipe N+Delta <parameters>
755  *	flowset N+Delta pipe N+Delta (no parameters)
756  *	sched N type wf2q+ sched_mask ...
757  *	pipe N <parameters>
758  *
759  * do_pipe = 2 -> flowset N config
760  *	flowset N parameters
761  *
762  * do_pipe = 3 -> sched N config
763  *	sched N parameters (default no pipe)
764  *	optional Pipe N config ...
765  * pipe ==>
766  */
767 void
768 ipfw_config_pipe(int ac, char **av)
769 {
770 	int i;
771 	u_int j;
772 	char *end;
773 	struct dn_id *buf, *base;
774 	struct dn_sch *sch = NULL;
775 	struct dn_link *p = NULL;
776 	struct dn_fs *fs = NULL;
777 	struct dn_profile *pf = NULL;
778 	struct ipfw_flow_id *mask = NULL;
779 	int lmax;
780 	uint32_t _foo = 0, *flags = &_foo , *buckets = &_foo;
781 
782 	/*
783 	 * allocate space for 1 header,
784 	 * 1 scheduler, 1 link, 1 flowset, 1 profile
785 	 */
786 	lmax = sizeof(struct dn_id);	/* command header */
787 	lmax += sizeof(struct dn_sch) + sizeof(struct dn_link) +
788 		sizeof(struct dn_fs) + sizeof(struct dn_profile);
789 
790 	av++; ac--;
791 	/* Pipe number */
792 	if (ac && isdigit(**av)) {
793 		i = atoi(*av); av++; ac--;
794 	} else
795 		i = -1;
796 	if (i <= 0)
797 		errx(EX_USAGE, "need a pipe/flowset/sched number");
798 	base = buf = safe_calloc(1, lmax);
799 	/* all commands start with a 'CONFIGURE' and a version */
800 	o_next(&buf, sizeof(struct dn_id), DN_CMD_CONFIG);
801 	base->id = DN_API_VERSION;
802 
803 	switch (co.do_pipe) {
804 	case 1: /* "pipe N config ..." */
805 		/* Allocate space for the WF2Q+ scheduler, its link
806 		 * and the FIFO flowset. Set the number, but leave
807 		 * the scheduler subtype and other parameters to 0
808 		 * so the kernel will use appropriate defaults.
809 		 * XXX todo: add a flag to record if a parameter
810 		 * is actually configured.
811 		 * If we do a 'pipe config' mask -> sched_mask.
812 		 * The FIFO scheduler and link are derived from the
813 		 * WF2Q+ one in the kernel.
814 		 */
815 		sch = o_next(&buf, sizeof(*sch), DN_SCH);
816 		p = o_next(&buf, sizeof(*p), DN_LINK);
817 		fs = o_next(&buf, sizeof(*fs), DN_FS);
818 
819 		sch->sched_nr = i;
820 		sch->oid.subtype = 0;	/* defaults to WF2Q+ */
821 		mask = &sch->sched_mask;
822 		flags = &sch->flags;
823 		buckets = &sch->buckets;
824 		*flags |= DN_PIPE_CMD;
825 
826 		p->link_nr = i;
827 
828 		/* This flowset is only for the FIFO scheduler */
829 		fs->fs_nr = i + 2*DN_MAX_ID;
830 		fs->sched_nr = i + DN_MAX_ID;
831 		break;
832 
833 	case 2: /* "queue N config ... " */
834 		fs = o_next(&buf, sizeof(*fs), DN_FS);
835 		fs->fs_nr = i;
836 		mask = &fs->flow_mask;
837 		flags = &fs->flags;
838 		buckets = &fs->buckets;
839 		break;
840 
841 	case 3: /* "sched N config ..." */
842 		sch = o_next(&buf, sizeof(*sch), DN_SCH);
843 		fs = o_next(&buf, sizeof(*fs), DN_FS);
844 		sch->sched_nr = i;
845 		mask = &sch->sched_mask;
846 		flags = &sch->flags;
847 		buckets = &sch->buckets;
848 		/* fs is used only with !MULTIQUEUE schedulers */
849 		fs->fs_nr = i + DN_MAX_ID;
850 		fs->sched_nr = i;
851 		break;
852 	}
853 	/* set to -1 those fields for which we want to reuse existing
854 	 * values from the kernel.
855 	 * Also, *_nr and subtype = 0 mean reuse the value from the kernel.
856 	 * XXX todo: support reuse of the mask.
857 	 */
858 	if (p)
859 		p->bandwidth = -1;
860 	for (j = 0; j < sizeof(fs->par)/sizeof(fs->par[0]); j++)
861 		fs->par[j] = -1;
862 	while (ac > 0) {
863 		double d;
864 		int tok = match_token(dummynet_params, *av);
865 		ac--; av++;
866 
867 		switch(tok) {
868 		case TOK_NOERROR:
869 			NEED(fs, "noerror is only for pipes");
870 			fs->flags |= DN_NOERROR;
871 			break;
872 
873 		case TOK_PLR:
874 			NEED(fs, "plr is only for pipes");
875 			NEED1("plr needs argument 0..1\n");
876 			d = strtod(av[0], NULL);
877 			if (d > 1)
878 				d = 1;
879 			else if (d < 0)
880 				d = 0;
881 			fs->plr = (int)(d*0x7fffffff);
882 			ac--; av++;
883 			break;
884 
885 		case TOK_QUEUE:
886 			NEED(fs, "queue is only for pipes or flowsets");
887 			NEED1("queue needs queue size\n");
888 			end = NULL;
889 			fs->qsize = strtoul(av[0], &end, 0);
890 			if (*end == 'K' || *end == 'k') {
891 				fs->flags |= DN_QSIZE_BYTES;
892 				fs->qsize *= 1024;
893 			} else if (*end == 'B' ||
894 			    _substrcmp2(end, "by", "bytes") == 0) {
895 				fs->flags |= DN_QSIZE_BYTES;
896 			}
897 			ac--; av++;
898 			break;
899 
900 		case TOK_BUCKETS:
901 			NEED(fs, "buckets is only for pipes or flowsets");
902 			NEED1("buckets needs argument\n");
903 			*buckets = strtoul(av[0], NULL, 0);
904 			ac--; av++;
905 			break;
906 
907 		case TOK_FLOW_MASK:
908 		case TOK_SCHED_MASK:
909 		case TOK_MASK:
910 			NEED(mask, "tok_mask");
911 			NEED1("mask needs mask specifier\n");
912 			/*
913 			 * per-flow queue, mask is dst_ip, dst_port,
914 			 * src_ip, src_port, proto measured in bits
915 			 */
916 
917 			bzero(mask, sizeof(*mask));
918 			end = NULL;
919 
920 			while (ac >= 1) {
921 			    uint32_t *p32 = NULL;
922 			    uint16_t *p16 = NULL;
923 			    uint32_t *p20 = NULL;
924 			    struct in6_addr *pa6 = NULL;
925 			    uint32_t a;
926 
927 			    tok = match_token(dummynet_params, *av);
928 			    ac--; av++;
929 			    switch(tok) {
930 			    case TOK_ALL:
931 				    /*
932 				     * special case, all bits significant
933 				     * except 'extra' (the queue number)
934 				     */
935 				    mask->dst_ip = ~0;
936 				    mask->src_ip = ~0;
937 				    mask->dst_port = ~0;
938 				    mask->src_port = ~0;
939 				    mask->proto = ~0;
940 				    n2mask(&mask->dst_ip6, 128);
941 				    n2mask(&mask->src_ip6, 128);
942 				    mask->flow_id6 = ~0;
943 				    *flags |= DN_HAVE_MASK;
944 				    goto end_mask;
945 
946 			    case TOK_QUEUE:
947 				    mask->extra = ~0;
948 				    *flags |= DN_HAVE_MASK;
949 				    goto end_mask;
950 
951 			    case TOK_DSTIP:
952 				    mask->addr_type = 4;
953 				    p32 = &mask->dst_ip;
954 				    break;
955 
956 			    case TOK_SRCIP:
957 				    mask->addr_type = 4;
958 				    p32 = &mask->src_ip;
959 				    break;
960 
961 			    case TOK_DSTIP6:
962 				    mask->addr_type = 6;
963 				    pa6 = &mask->dst_ip6;
964 				    break;
965 
966 			    case TOK_SRCIP6:
967 				    mask->addr_type = 6;
968 				    pa6 = &mask->src_ip6;
969 				    break;
970 
971 			    case TOK_FLOWID:
972 				    mask->addr_type = 6;
973 				    p20 = &mask->flow_id6;
974 				    break;
975 
976 			    case TOK_DSTPORT:
977 				    p16 = &mask->dst_port;
978 				    break;
979 
980 			    case TOK_SRCPORT:
981 				    p16 = &mask->src_port;
982 				    break;
983 
984 			    case TOK_PROTO:
985 				    break;
986 
987 			    default:
988 				    ac++; av--; /* backtrack */
989 				    goto end_mask;
990 			    }
991 			    if (ac < 1)
992 				    errx(EX_USAGE, "mask: value missing");
993 			    if (*av[0] == '/') {
994 				    a = strtoul(av[0]+1, &end, 0);
995 				    if (pa6 == NULL)
996 					    a = (a == 32) ? ~0 : (1 << a) - 1;
997 			    } else
998 				    a = strtoul(av[0], &end, 0);
999 			    if (p32 != NULL)
1000 				    *p32 = a;
1001 			    else if (p16 != NULL) {
1002 				    if (a > 0xFFFF)
1003 					    errx(EX_DATAERR,
1004 						"port mask must be 16 bit");
1005 				    *p16 = (uint16_t)a;
1006 			    } else if (p20 != NULL) {
1007 				    if (a > 0xfffff)
1008 					errx(EX_DATAERR,
1009 					    "flow_id mask must be 20 bit");
1010 				    *p20 = (uint32_t)a;
1011 			    } else if (pa6 != NULL) {
1012 				    if (a > 128)
1013 					errx(EX_DATAERR,
1014 					    "in6addr invalid mask len");
1015 				    else
1016 					n2mask(pa6, a);
1017 			    } else {
1018 				    if (a > 0xFF)
1019 					    errx(EX_DATAERR,
1020 						"proto mask must be 8 bit");
1021 				    mask->proto = (uint8_t)a;
1022 			    }
1023 			    if (a != 0)
1024 				    *flags |= DN_HAVE_MASK;
1025 			    ac--; av++;
1026 			} /* end while, config masks */
1027 end_mask:
1028 			break;
1029 
1030 		case TOK_RED:
1031 		case TOK_GRED:
1032 			NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
1033 			fs->flags |= DN_IS_RED;
1034 			if (tok == TOK_GRED)
1035 				fs->flags |= DN_IS_GENTLE_RED;
1036 			/*
1037 			 * the format for parameters is w_q/min_th/max_th/max_p
1038 			 */
1039 			if ((end = strsep(&av[0], "/"))) {
1040 			    double w_q = strtod(end, NULL);
1041 			    if (w_q > 1 || w_q <= 0)
1042 				errx(EX_DATAERR, "0 < w_q <= 1");
1043 			    fs->w_q = (int) (w_q * (1 << SCALE_RED));
1044 			}
1045 			if ((end = strsep(&av[0], "/"))) {
1046 			    fs->min_th = strtoul(end, &end, 0);
1047 			    if (*end == 'K' || *end == 'k')
1048 				fs->min_th *= 1024;
1049 			}
1050 			if ((end = strsep(&av[0], "/"))) {
1051 			    fs->max_th = strtoul(end, &end, 0);
1052 			    if (*end == 'K' || *end == 'k')
1053 				fs->max_th *= 1024;
1054 			}
1055 			if ((end = strsep(&av[0], "/"))) {
1056 			    double max_p = strtod(end, NULL);
1057 			    if (max_p > 1 || max_p < 0)
1058 				errx(EX_DATAERR, "0 <= max_p <= 1");
1059 			    fs->max_p = (int)(max_p * (1 << SCALE_RED));
1060 			}
1061 			ac--; av++;
1062 			break;
1063 
1064 		case TOK_ECN:
1065 			fs->flags |= DN_IS_ECN;
1066 			break;
1067 
1068 		case TOK_DROPTAIL:
1069 			NEED(fs, "droptail is only for flowsets");
1070 			fs->flags &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
1071 			break;
1072 
1073 		case TOK_BW:
1074 			NEED(p, "bw is only for links");
1075 			NEED1("bw needs bandwidth or interface\n");
1076 			read_bandwidth(av[0], &p->bandwidth, NULL, 0);
1077 			ac--; av++;
1078 			break;
1079 
1080 		case TOK_DELAY:
1081 			NEED(p, "delay is only for links");
1082 			NEED1("delay needs argument 0..10000ms\n");
1083 			p->delay = strtoul(av[0], NULL, 0);
1084 			ac--; av++;
1085 			break;
1086 
1087 		case TOK_TYPE: {
1088 			int l;
1089 			NEED(sch, "type is only for schedulers");
1090 			NEED1("type needs a string");
1091 			l = strlen(av[0]);
1092 			if (l == 0 || l > 15)
1093 				errx(1, "type %s too long\n", av[0]);
1094 			strcpy(sch->name, av[0]);
1095 			sch->oid.subtype = 0; /* use string */
1096 			ac--; av++;
1097 			break;
1098 		    }
1099 
1100 		case TOK_WEIGHT:
1101 			NEED(fs, "weight is only for flowsets");
1102 			NEED1("weight needs argument\n");
1103 			fs->par[0] = strtol(av[0], &end, 0);
1104 			ac--; av++;
1105 			break;
1106 
1107 		case TOK_LMAX:
1108 			NEED(fs, "lmax is only for flowsets");
1109 			NEED1("lmax needs argument\n");
1110 			fs->par[1] = strtol(av[0], &end, 0);
1111 			ac--; av++;
1112 			break;
1113 
1114 		case TOK_PRI:
1115 			NEED(fs, "priority is only for flowsets");
1116 			NEED1("priority needs argument\n");
1117 			fs->par[2] = strtol(av[0], &end, 0);
1118 			ac--; av++;
1119 			break;
1120 
1121 		case TOK_SCHED:
1122 		case TOK_PIPE:
1123 			NEED(fs, "pipe/sched");
1124 			NEED1("pipe/link/sched needs number\n");
1125 			fs->sched_nr = strtoul(av[0], &end, 0);
1126 			ac--; av++;
1127 			break;
1128 
1129 		case TOK_PROFILE:
1130 			NEED((!pf), "profile already set");
1131 			NEED(p, "profile");
1132 		    {
1133 			NEED1("extra delay needs the file name\n");
1134 			pf = o_next(&buf, sizeof(*pf), DN_PROFILE);
1135 			load_extra_delays(av[0], pf, p); //XXX can't fail?
1136 			--ac; ++av;
1137 		    }
1138 			break;
1139 
1140 		case TOK_BURST:
1141 			NEED(p, "burst");
1142 			NEED1("burst needs argument\n");
1143 			errno = 0;
1144 			if (expand_number(av[0], &p->burst) < 0)
1145 				if (errno != ERANGE)
1146 					errx(EX_DATAERR,
1147 					    "burst: invalid argument");
1148 			if (errno || p->burst > (1ULL << 48) - 1)
1149 				errx(EX_DATAERR,
1150 				    "burst: out of range (0..2^48-1)");
1151 			ac--; av++;
1152 			break;
1153 
1154 		default:
1155 			errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
1156 		}
1157 	}
1158 
1159 	/* check validity of parameters */
1160 	if (p) {
1161 		if (p->delay > 10000)
1162 			errx(EX_DATAERR, "delay must be < 10000");
1163 		if (p->bandwidth == -1)
1164 			p->bandwidth = 0;
1165 	}
1166 	if (fs) {
1167 		/* XXX accept a 0 scheduler to keep the default */
1168 	    if (fs->flags & DN_QSIZE_BYTES) {
1169 		size_t len;
1170 		long limit;
1171 
1172 		len = sizeof(limit);
1173 		if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
1174 			&limit, &len, NULL, 0) == -1)
1175 			limit = 1024*1024;
1176 		if (fs->qsize > limit)
1177 			errx(EX_DATAERR, "queue size must be < %ldB", limit);
1178 	    } else {
1179 		size_t len;
1180 		long limit;
1181 
1182 		len = sizeof(limit);
1183 		if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
1184 			&limit, &len, NULL, 0) == -1)
1185 			limit = 100;
1186 		if (fs->qsize > limit)
1187 			errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
1188 	    }
1189 
1190 	    if ((fs->flags & DN_IS_ECN) && !(fs->flags & DN_IS_RED))
1191 		errx(EX_USAGE, "enable red/gred for ECN");
1192 
1193 	    if (fs->flags & DN_IS_RED) {
1194 		size_t len;
1195 		int lookup_depth, avg_pkt_size;
1196 
1197 		if (!(fs->flags & DN_IS_ECN) && (fs->min_th >= fs->max_th))
1198 		    errx(EX_DATAERR, "min_th %d must be < than max_th %d",
1199 			fs->min_th, fs->max_th);
1200 		else if ((fs->flags & DN_IS_ECN) && (fs->min_th > fs->max_th))
1201 		    errx(EX_DATAERR, "min_th %d must be =< than max_th %d",
1202 			fs->min_th, fs->max_th);
1203 
1204 		if (fs->max_th == 0)
1205 		    errx(EX_DATAERR, "max_th must be > 0");
1206 
1207 		len = sizeof(int);
1208 		if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
1209 			&lookup_depth, &len, NULL, 0) == -1)
1210 			lookup_depth = 256;
1211 		if (lookup_depth == 0)
1212 		    errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
1213 			" must be greater than zero");
1214 
1215 		len = sizeof(int);
1216 		if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
1217 			&avg_pkt_size, &len, NULL, 0) == -1)
1218 			avg_pkt_size = 512;
1219 
1220 		if (avg_pkt_size == 0)
1221 			errx(EX_DATAERR,
1222 			    "net.inet.ip.dummynet.red_avg_pkt_size must"
1223 			    " be greater than zero");
1224 
1225 #if 0 /* the following computation is now done in the kernel */
1226 		/*
1227 		 * Ticks needed for sending a medium-sized packet.
1228 		 * Unfortunately, when we are configuring a WF2Q+ queue, we
1229 		 * do not have bandwidth information, because that is stored
1230 		 * in the parent pipe, and also we have multiple queues
1231 		 * competing for it. So we set s=0, which is not very
1232 		 * correct. But on the other hand, why do we want RED with
1233 		 * WF2Q+ ?
1234 		 */
1235 		if (p.bandwidth==0) /* this is a WF2Q+ queue */
1236 			s = 0;
1237 		else
1238 			s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
1239 		/*
1240 		 * max idle time (in ticks) before avg queue size becomes 0.
1241 		 * NOTA:  (3/w_q) is approx the value x so that
1242 		 * (1-w_q)^x < 10^-3.
1243 		 */
1244 		w_q = ((double)fs->w_q) / (1 << SCALE_RED);
1245 		idle = s * 3. / w_q;
1246 		fs->lookup_step = (int)idle / lookup_depth;
1247 		if (!fs->lookup_step)
1248 			fs->lookup_step = 1;
1249 		weight = 1 - w_q;
1250 		for (t = fs->lookup_step; t > 1; --t)
1251 			weight *= 1 - w_q;
1252 		fs->lookup_weight = (int)(weight * (1 << SCALE_RED));
1253 #endif /* code moved in the kernel */
1254 	    }
1255 	}
1256 
1257 	i = do_cmd(IP_DUMMYNET3, base, (char *)buf - (char *)base);
1258 
1259 	if (i)
1260 		err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
1261 }
1262 
1263 void
1264 dummynet_flush(void)
1265 {
1266 	struct dn_id oid;
1267 	oid_fill(&oid, sizeof(oid), DN_CMD_FLUSH, DN_API_VERSION);
1268 	do_cmd(IP_DUMMYNET3, &oid, oid.len);
1269 }
1270 
1271 /* Parse input for 'ipfw [pipe|sched|queue] show [range list]'
1272  * Returns the number of ranges, and possibly stores them
1273  * in the array v of size len.
1274  */
1275 static int
1276 parse_range(int ac, char *av[], uint32_t *v, int len)
1277 {
1278 	int n = 0;
1279 	char *endptr, *s;
1280 	uint32_t base[2];
1281 
1282 	if (v == NULL || len < 2) {
1283 		v = base;
1284 		len = 2;
1285 	}
1286 
1287 	for (s = *av; s != NULL; av++, ac--) {
1288 		v[0] = strtoul(s, &endptr, 10);
1289 		v[1] = (*endptr != '-') ? v[0] :
1290 			 strtoul(endptr+1, &endptr, 10);
1291 		if (*endptr == '\0') { /* prepare for next round */
1292 			s = (ac > 0) ? *(av+1) : NULL;
1293 		} else {
1294 			if (*endptr != ',') {
1295 				warn("invalid number: %s", s);
1296 				s = ++endptr;
1297 				continue;
1298 			}
1299 			/* continue processing from here */
1300 			s = ++endptr;
1301 			ac++;
1302 			av--;
1303 		}
1304 		if (v[1] < v[0] ||
1305 			v[1] >= DN_MAX_ID-1 ||
1306 			v[1] >= DN_MAX_ID-1) {
1307 			continue; /* invalid entry */
1308 		}
1309 		n++;
1310 		/* translate if 'pipe list' */
1311 		if (co.do_pipe == 1) {
1312 			v[0] += DN_MAX_ID;
1313 			v[1] += DN_MAX_ID;
1314 		}
1315 		v = (n*2 < len) ? v + 2 : base;
1316 	}
1317 	return n;
1318 }
1319 
1320 /* main entry point for dummynet list functions. co.do_pipe indicates
1321  * which function we want to support.
1322  * av may contain filtering arguments, either individual entries
1323  * or ranges, or lists (space or commas are valid separators).
1324  * Format for a range can be n1-n2 or n3 n4 n5 ...
1325  * In a range n1 must be <= n2, otherwise the range is ignored.
1326  * A number 'n4' is translate in a range 'n4-n4'
1327  * All number must be > 0 and < DN_MAX_ID-1
1328  */
1329 void
1330 dummynet_list(int ac, char *av[], int show_counters)
1331 {
1332 	struct dn_id *oid, *x = NULL;
1333 	int ret, i;
1334 	int n; 		/* # of ranges */
1335 	u_int buflen, l;
1336 	u_int max_size;	/* largest obj passed up */
1337 
1338 	(void)show_counters;	// XXX unused, but we should use it.
1339 	ac--;
1340 	av++; 		/* skip 'list' | 'show' word */
1341 
1342 	n = parse_range(ac, av, NULL, 0);	/* Count # of ranges. */
1343 
1344 	/* Allocate space to store ranges */
1345 	l = sizeof(*oid) + sizeof(uint32_t) * n * 2;
1346 	oid = safe_calloc(1, l);
1347 	oid_fill(oid, l, DN_CMD_GET, DN_API_VERSION);
1348 
1349 	if (n > 0)	/* store ranges in idx */
1350 		parse_range(ac, av, (uint32_t *)(oid + 1), n*2);
1351 	/*
1352 	 * Compute the size of the largest object returned. If the
1353 	 * response leaves at least this much spare space in the
1354 	 * buffer, then surely the response is complete; otherwise
1355 	 * there might be a risk of truncation and we will need to
1356 	 * retry with a larger buffer.
1357 	 * XXX don't bother with smaller structs.
1358 	 */
1359 	max_size = sizeof(struct dn_fs);
1360 	if (max_size < sizeof(struct dn_sch))
1361 		max_size = sizeof(struct dn_sch);
1362 	if (max_size < sizeof(struct dn_flow))
1363 		max_size = sizeof(struct dn_flow);
1364 
1365 	switch (co.do_pipe) {
1366 	case 1:
1367 		oid->subtype = DN_LINK;	/* list pipe */
1368 		break;
1369 	case 2:
1370 		oid->subtype = DN_FS;	/* list queue */
1371 		break;
1372 	case 3:
1373 		oid->subtype = DN_SCH;	/* list sched */
1374 		break;
1375 	}
1376 
1377 	/*
1378 	 * Ask the kernel an estimate of the required space (result
1379 	 * in oid.id), unless we are requesting a subset of objects,
1380 	 * in which case the kernel does not give an exact answer.
1381 	 * In any case, space might grow in the meantime due to the
1382 	 * creation of new queues, so we must be prepared to retry.
1383 	 */
1384 	if (n > 0) {
1385 		buflen = 4*1024;
1386 	} else {
1387 		ret = do_cmd(-IP_DUMMYNET3, oid, (uintptr_t)&l);
1388 		if (ret != 0 || oid->id <= sizeof(*oid))
1389 			goto done;
1390 		buflen = oid->id + max_size;
1391 		oid->len = sizeof(*oid); /* restore */
1392 	}
1393 	/* Try a few times, until the buffer fits */
1394 	for (i = 0; i < 20; i++) {
1395 		l = buflen;
1396 		x = safe_realloc(x, l);
1397 		bcopy(oid, x, oid->len);
1398 		ret = do_cmd(-IP_DUMMYNET3, x, (uintptr_t)&l);
1399 		if (ret != 0 || x->id <= sizeof(*oid))
1400 			goto done; /* no response */
1401 		if (l + max_size <= buflen)
1402 			break; /* ok */
1403 		buflen *= 2;	 /* double for next attempt */
1404 	}
1405 	list_pipes(x, O_NEXT(x, l));
1406 done:
1407 	if (x)
1408 		free(x);
1409 	free(oid);
1410 }
1411