fd8fc4d30790c0cf61cf394a54eb3f0718585475
[ipfw.git] / ipfw / dummynet.c
1 /*
2  * Copyright (c) 2002-2003 Luigi Rizzo
3  * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4  * Copyright (c) 1994 Ugen J.S.Antsilevich
5  *
6  * Idea and grammar partially left from:
7  * Copyright (c) 1993 Daniel Boulet
8  *
9  * Redistribution and use in source forms, with and without modification,
10  * are permitted provided that this entire comment appears intact.
11  *
12  * Redistribution in binary form may occur without any restrictions.
13  * Obviously, it would be nice if you gave credit where credit is due
14  * but requiring it would be too onerous.
15  *
16  * This software is provided ``AS IS'' without any warranties of any kind.
17  *
18  * NEW command line interface for IP firewall facility
19  *
20  * $FreeBSD: head/sbin/ipfw/dummynet.c 187769 2009-01-27 11:06:59Z luigi $
21  *
22  * dummynet support
23  */
24
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/queue.h>
28 /* XXX there are several sysctl leftover here */
29 #include <sys/sysctl.h>
30
31 #include "ipfw2.h"
32
33 #include <ctype.h>
34 #include <err.h>
35 #include <netdb.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sysexits.h>
40
41 #include <net/if.h>
42 #include <netinet/in.h>
43 #include <netinet/ip_fw.h>
44 #include <netinet/ip_dummynet.h>
45 #include <arpa/inet.h>  /* inet_ntoa */
46
47 static struct _s_x dummynet_params[] = {
48         { "plr",                TOK_PLR },
49         { "noerror",            TOK_NOERROR },
50         { "buckets",            TOK_BUCKETS },
51         { "dst-ip",             TOK_DSTIP },
52         { "src-ip",             TOK_SRCIP },
53         { "dst-port",           TOK_DSTPORT },
54         { "src-port",           TOK_SRCPORT },
55         { "proto",              TOK_PROTO },
56         { "weight",             TOK_WEIGHT },
57         { "all",                TOK_ALL },
58         { "mask",               TOK_MASK },
59         { "droptail",           TOK_DROPTAIL },
60         { "red",                TOK_RED },
61         { "gred",               TOK_GRED },
62         { "bw",                 TOK_BW },
63         { "bandwidth",          TOK_BW },
64         { "delay",              TOK_DELAY },
65         { "pipe",               TOK_PIPE },
66         { "queue",              TOK_QUEUE },
67         { "flow-id",            TOK_FLOWID},
68         { "dst-ipv6",           TOK_DSTIP6},
69         { "dst-ip6",            TOK_DSTIP6},
70         { "src-ipv6",           TOK_SRCIP6},
71         { "src-ip6",            TOK_SRCIP6},
72         { "profile",            TOK_PIPE_PROFILE},
73         { "dummynet-params",    TOK_NULL },
74         { NULL, 0 }     /* terminator */
75 };
76
77 static int
78 sort_q(const void *pa, const void *pb)
79 {
80         int rev = (co.do_sort < 0);
81         int field = rev ? -co.do_sort : co.do_sort;
82         long long res = 0;
83         const struct dn_flow_queue *a = pa;
84         const struct dn_flow_queue *b = pb;
85
86         switch (field) {
87         case 1: /* pkts */
88                 res = a->len - b->len;
89                 break;
90         case 2: /* bytes */
91                 res = a->len_bytes - b->len_bytes;
92                 break;
93
94         case 3: /* tot pkts */
95                 res = a->tot_pkts - b->tot_pkts;
96                 break;
97
98         case 4: /* tot bytes */
99                 res = a->tot_bytes - b->tot_bytes;
100                 break;
101         }
102         if (res < 0)
103                 res = -1;
104         if (res > 0)
105                 res = 1;
106         return (int)(rev ? res : -res);
107 }
108
109 static void
110 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
111 {
112         int l;
113         int index_printed, indexes = 0;
114         char buff[255];
115         struct protoent *pe;
116
117         if (fs->rq_elements == 0)
118                 return;
119
120         if (co.do_sort != 0)
121                 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
122
123         /* Print IPv4 flows */
124         index_printed = 0;
125         for (l = 0; l < fs->rq_elements; l++) {
126                 struct in_addr ina;
127
128                 /* XXX: Should check for IPv4 flows */
129                 if (IS_IP6_FLOW_ID(&(q[l].id)))
130                         continue;
131
132                 if (!index_printed) {
133                         index_printed = 1;
134                         if (indexes > 0)        /* currently a no-op */
135                                 printf("\n");
136                         indexes++;
137                         printf("    "
138                             "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
139                             fs->flow_mask.proto,
140                             fs->flow_mask.src_ip, fs->flow_mask.src_port,
141                             fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
142
143                         printf("BKT Prot ___Source IP/port____ "
144                             "____Dest. IP/port____ "
145                             "Tot_pkt/bytes Pkt/Byte Drp\n");
146                 }
147
148                 printf("%3d ", q[l].hash_slot);
149                 pe = getprotobynumber(q[l].id.proto);
150                 if (pe)
151                         printf("%-4s ", pe->p_name);
152                 else
153                         printf("%4u ", q[l].id.proto);
154                 ina.s_addr = htonl(q[l].id.src_ip);
155                 printf("%15s/%-5d ",
156                     inet_ntoa(ina), q[l].id.src_port);
157                 ina.s_addr = htonl(q[l].id.dst_ip);
158                 printf("%15s/%-5d ",
159                     inet_ntoa(ina), q[l].id.dst_port);
160                 printf("%4llu %8llu %2u %4u %3u\n",
161                     align_uint64(&q[l].tot_pkts),
162                     align_uint64(&q[l].tot_bytes),
163                     q[l].len, q[l].len_bytes, q[l].drops);
164                 if (co.verbose)
165                         printf("   S %20llu  F %20llu\n",
166                             align_uint64(&q[l].S), align_uint64(&q[l].F));
167         }
168
169         /* Print IPv6 flows */
170         index_printed = 0;
171         for (l = 0; l < fs->rq_elements; l++) {
172                 if (!IS_IP6_FLOW_ID(&(q[l].id)))
173                         continue;
174
175                 if (!index_printed) {
176                         index_printed = 1;
177                         if (indexes > 0)
178                                 printf("\n");
179                         indexes++;
180                         printf("\n        mask: proto: 0x%02x, flow_id: 0x%08x,  ",
181                             fs->flow_mask.proto, fs->flow_mask.flow_id6);
182                         inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
183                             buff, sizeof(buff));
184                         printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
185                         inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
186                             buff, sizeof(buff) );
187                         printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
188
189                         printf("BKT ___Prot___ _flow-id_ "
190                             "______________Source IPv6/port_______________ "
191                             "_______________Dest. IPv6/port_______________ "
192                             "Tot_pkt/bytes Pkt/Byte Drp\n");
193                 }
194                 printf("%3d ", q[l].hash_slot);
195                 pe = getprotobynumber(q[l].id.proto);
196                 if (pe != NULL)
197                         printf("%9s ", pe->p_name);
198                 else
199                         printf("%9u ", q[l].id.proto);
200                 printf("%7d  %39s/%-5d ", q[l].id.flow_id6,
201                     inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
202                     q[l].id.src_port);
203                 printf(" %39s/%-5d ",
204                     inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
205                     q[l].id.dst_port);
206                 printf(" %4llu %8llu %2u %4u %3u\n",
207                     align_uint64(&q[l].tot_pkts),
208                     align_uint64(&q[l].tot_bytes),
209                     q[l].len, q[l].len_bytes, q[l].drops);
210                 if (co.verbose)
211                         printf("   S %20llu  F %20llu\n",
212                             align_uint64(&q[l].S),
213                             align_uint64(&q[l].F));
214         }
215 }
216
217 static void
218 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
219 {
220         int l;
221         char qs[30];
222         char plr[30];
223         char red[90];   /* Display RED parameters */
224
225         l = fs->qsize;
226         if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
227                 if (l >= 8192)
228                         sprintf(qs, "%d KB", l / 1024);
229                 else
230                         sprintf(qs, "%d B", l);
231         } else
232                 sprintf(qs, "%3d sl.", l);
233         if (fs->plr)
234                 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
235         else
236                 plr[0] = '\0';
237         if (fs->flags_fs & DN_IS_RED)   /* RED parameters */
238                 sprintf(red,
239                     "\n\t  %cRED w_q %f min_th %d max_th %d max_p %f",
240                     (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
241                     1.0 * fs->w_q / (double)(1 << SCALE_RED),
242                     SCALE_VAL(fs->min_th),
243                     SCALE_VAL(fs->max_th),
244                     1.0 * fs->max_p / (double)(1 << SCALE_RED));
245         else
246                 sprintf(red, "droptail");
247
248         printf("%s %s%s %d queues (%d buckets) %s\n",
249             prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
250 }
251
252 static void
253 print_extra_delay_parms(struct dn_pipe *p, char *prefix)
254 {
255         double loss;
256         if (p->samples_no <= 0)
257                 return;
258
259         loss = p->loss_level;
260         loss /= p->samples_no;
261         printf("%s profile: name \"%s\" loss %f samples %d\n",
262                 prefix, p->name, loss, p->samples_no);
263 }
264
265 void
266 ipfw_list_pipes(void *data, uint nbytes, int ac, char *av[])
267 {
268         int rulenum;
269         void *next = data;
270         struct dn_pipe *p = (struct dn_pipe *) data;
271         struct dn_flow_set *fs;
272         struct dn_flow_queue *q;
273         int l;
274
275         if (ac > 0)
276                 rulenum = strtoul(*av++, NULL, 10);
277         else
278                 rulenum = 0;
279         for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
280                 double b = p->bandwidth;
281                 char buf[30];
282                 char prefix[80];
283
284                 if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE)
285                         break;  /* done with pipes, now queues */
286
287                 /*
288                  * compute length, as pipe have variable size
289                  */
290                 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
291                 next = (char *)p + l;
292                 nbytes -= l;
293
294                 if ((rulenum != 0 && rulenum != p->pipe_nr) || co.do_pipe == 2)
295                         continue;
296
297                 /*
298                  * Print rate (or clocking interface)
299                  */
300                 if (p->if_name[0] != '\0')
301                         sprintf(buf, "%s", p->if_name);
302                 else if (b == 0)
303                         sprintf(buf, "unlimited");
304                 else if (b >= 1000000)
305                         sprintf(buf, "%7.3f Mbit/s", b/1000000);
306                 else if (b >= 1000)
307                         sprintf(buf, "%7.3f Kbit/s", b/1000);
308                 else
309                         sprintf(buf, "%7.3f bit/s ", b);
310
311                 sprintf(prefix, "%05d: %s %4d ms ",
312                     p->pipe_nr, buf, p->delay);
313
314                 print_extra_delay_parms(p, prefix);
315
316                 print_flowset_parms(&(p->fs), prefix);
317
318                 q = (struct dn_flow_queue *)(p+1);
319                 list_queues(&(p->fs), q);
320         }
321         for (fs = next; nbytes >= sizeof *fs; fs = next) {
322                 char prefix[80];
323
324                 if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE)
325                         break;
326                 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
327                 next = (char *)fs + l;
328                 nbytes -= l;
329
330                 if (rulenum != 0 && ((rulenum != fs->fs_nr && co.do_pipe == 2) ||
331                     (rulenum != fs->parent_nr && co.do_pipe == 1))) {
332                         continue;
333                 }
334
335                 q = (struct dn_flow_queue *)(fs+1);
336                 sprintf(prefix, "q%05d: weight %d pipe %d ",
337                     fs->fs_nr, fs->weight, fs->parent_nr);
338                 print_flowset_parms(fs, prefix);
339                 list_queues(fs, q);
340         }
341 }
342
343 /*
344  * Delete pipe or queue i
345  */
346 int
347 ipfw_delete_pipe(int pipe_or_queue, int i)
348 {
349         struct dn_pipe p;
350
351         memset(&p, 0, sizeof p);
352         if (pipe_or_queue == 1)
353                 p.pipe_nr = i;          /* pipe */
354         else
355                 p.fs.fs_nr = i;         /* queue */
356         i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
357         if (i) {
358                 i = 1;
359                 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", i);
360         }
361         return i;
362 }
363
364 /*
365  * Code to parse delay profiles.
366  *
367  * Some link types introduce extra delays in the transmission
368  * of a packet, e.g. because of MAC level framing, contention on
369  * the use of the channel, MAC level retransmissions and so on.
370  * From our point of view, the channel is effectively unavailable
371  * for this extra time, which is constant or variable depending
372  * on the link type. Additionally, packets may be dropped after this
373  * time (e.g. on a wireless link after too many retransmissions).
374  * We can model the additional delay with an empirical curve
375  * that represents its distribution.
376  *
377  *      cumulative probability
378  *      1.0 ^
379  *          |
380  *      L   +-- loss-level          x
381  *          |                 ******
382  *          |                *
383  *          |           *****
384  *          |          *
385  *          |        **
386  *          |       *                         
387  *          +-------*------------------->
388  *                      delay
389  *
390  * The empirical curve may have both vertical and horizontal lines.
391  * Vertical lines represent constant delay for a range of
392  * probabilities; horizontal lines correspond to a discontinuty
393  * in the delay distribution: the pipe will use the largest delay
394  * for a given probability.
395  * 
396  * To pass the curve to dummynet, we must store the parameters
397  * in a file as described below, and issue the command
398  *
399  *      ipfw pipe <n> config ... bw XXX profile <filename> ...
400  *
401  * The file format is the following, with whitespace acting as
402  * a separator and '#' indicating the beginning a comment:
403  *
404  *      samples N
405  *              the number of samples used in the internal
406  *              representation (2..1024; default 100);
407  *
408  *      loss-level L 
409  *              The probability above which packets are lost.
410  *               (0.0 <= L <= 1.0, default 1.0 i.e. no loss);
411  *
412  *      name identifier
413  *              Optional a name (listed by "ipfw pipe show")
414  *              to identify the distribution;
415  *
416  *      "delay prob" | "prob delay"
417  *              One of these two lines is mandatory and defines
418  *              the format of the following lines with data points.
419  *
420  *      XXX YYY
421  *              2 or more lines representing points in the curve,
422  *              with either delay or probability first, according
423  *              to the chosen format.
424  *              The unit for delay is milliseconds.
425  *
426  * Data points does not need to be ordered or equal to the number
427  * specified in the "samples" line. ipfw will sort and interpolate
428  * the curve as needed.
429  *
430  * Example of a profile file:
431  
432         name    bla_bla_bla
433         samples 100
434         loss-level    0.86
435         prob    delay
436         0       200     # minimum overhead is 200ms
437         0.5     200
438         0.5     300
439         0.8     1000
440         0.9     1300
441         1       1300
442  
443  * Internally, we will convert the curve to a fixed number of
444  * samples, and when it is time to transmit a packet we will
445  * model the extra delay as extra bits in the packet.
446  *
447  */
448
449 /* XXX move to an array definition ? */
450 #define ED_MAX_LINE_LEN 256+ED_MAX_NAME_LEN
451 #define ED_TOK_SAMPLES  "samples"
452 #define ED_TOK_LOSS     "loss-level"
453 #define ED_TOK_NAME     "name"
454 #define ED_TOK_DELAY    "delay"
455 #define ED_TOK_PROB     "prob"
456 #define ED_TOK_BW       "bw"
457 #define ED_SEPARATORS   " \t\n"
458 #define ED_MIN_SAMPLES_NO       2
459
460 /*
461  * returns 1 if s is a non-negative number, with at least one '.'
462  */
463 static int
464 is_valid_number(const char *s)
465 {
466         int i, dots_found = 0;
467         int len = strlen(s);
468
469         for (i = 0; i<len; ++i)
470                 if (!isdigit(s[i]) && (s[i] !='.' || ++dots_found > 1))
471                         return 0;
472         return 1;
473 }
474
475 /*
476  * Take as input a string describing a bandwidth value
477  * and return the numeric bandwidth value.
478  * set clocking interface or bandwidth value
479  */
480 void
481 read_bandwidth(char *arg, int *bandwidth, char *if_name, int namelen)
482 {
483         if (*bandwidth != -1)
484                 warn("duplicate token, override bandwidth value!");
485
486         if (arg[0] >= 'a' && arg[0] <= 'z') {
487                 if (namelen >= IFNAMSIZ)
488                         warn("interface name truncated");
489                 namelen--;
490                 /* interface name */
491                 strncpy(if_name, arg, namelen);
492                 if_name[namelen] = '\0';
493                 *bandwidth = 0;
494         } else {        /* read bandwidth value */
495                 int bw;
496                 char *end = NULL;
497
498                 bw = strtoul(arg, &end, 0);
499                 if (*end == 'K' || *end == 'k') {
500                         end++;
501                         bw *= 1000;
502                 } else if (*end == 'M') {
503                         end++;
504                         bw *= 1000000;
505                 }
506                 if ((*end == 'B' &&
507                     _substrcmp2(end, "Bi", "Bit/s") != 0) ||
508                     _substrcmp2(end, "by", "bytes") == 0)
509                         bw *= 8;
510
511                 if (bw < 0)
512                         errx(EX_DATAERR, "bandwidth too large");
513
514                 *bandwidth = bw;
515                 if_name[0] = '\0';
516         }
517 }
518
519 struct point {
520         double prob;
521         double delay;
522 };
523
524 int
525 compare_points(const void *vp1, const void *vp2)
526 {
527         const struct point *p1 = vp1;
528         const struct point *p2 = vp2;
529         double res = 0;
530
531         res = p1->prob - p2->prob;
532         if (res == 0)
533                 res = p1->delay - p2->delay;
534         if (res < 0)
535                 return -1;
536         else if (res > 0)
537                 return 1;
538         else
539                 return 0;
540 }
541
542 #define ED_EFMT(s) EX_DATAERR,"error in %s at line %d: "#s,filename,lineno
543
544 static void
545 load_extra_delays(const char *filename, struct dn_pipe *p)
546 {
547         char    line[ED_MAX_LINE_LEN];
548         FILE    *f;
549         int     lineno = 0;
550         int     i;
551
552         int     samples = -1;
553         double  loss = -1.0;
554         char    profile_name[ED_MAX_NAME_LEN];
555         int     delay_first = -1;
556         int     do_points = 0;
557         struct point    points[ED_MAX_SAMPLES_NO];
558         int     points_no = 0;
559
560         profile_name[0] = '\0';
561         f = fopen(filename, "r");
562         if (f == NULL)
563                 err(EX_UNAVAILABLE, "fopen: %s", filename);
564
565         while (fgets(line, ED_MAX_LINE_LEN, f)) {         /* read commands */
566                 char *s, *cur = line, *name = NULL, *arg = NULL;
567
568                 ++lineno;
569
570                 /* parse the line */
571                 while (cur) {
572                         s = strsep(&cur, ED_SEPARATORS);
573                         if (s == NULL || *s == '#')
574                                 break;
575                         if (*s == '\0')
576                                 continue;
577                         if (arg)
578                                 errx(ED_EFMT("too many arguments"));
579                         if (name == NULL)
580                                 name = s;
581                         else
582                                 arg = s;
583                 }
584                 if (name == NULL)       /* empty line */
585                         continue;
586                 if (arg == NULL)
587                         errx(ED_EFMT("missing arg for %s"), name);
588
589                 if (!strcasecmp(name, ED_TOK_SAMPLES)) {
590                     if (samples > 0)
591                         errx(ED_EFMT("duplicate ``samples'' line"));
592                     if (atoi(arg) <=0)
593                         errx(ED_EFMT("invalid number of samples"));
594                     samples = atoi(arg);
595                     if (samples>ED_MAX_SAMPLES_NO)
596                             errx(ED_EFMT("too many samples, maximum is %d"),
597                                 ED_MAX_SAMPLES_NO);
598                     do_points = 0;
599                 } else if (!strcasecmp(name, ED_TOK_BW)) {
600                     read_bandwidth(arg, &p->bandwidth, p->if_name, sizeof(p->if_name));
601                 } else if (!strcasecmp(name, ED_TOK_LOSS)) {
602                     if (loss != -1.0)
603                         errx(ED_EFMT("duplicated token: %s"), name);
604                     if (!is_valid_number(arg))
605                         errx(ED_EFMT("invalid %s"), arg);
606                     loss = atof(arg);
607                     if (loss > 1)
608                         errx(ED_EFMT("%s greater than 1.0"), name);
609                     do_points = 0;
610                 } else if (!strcasecmp(name, ED_TOK_NAME)) {
611                     if (profile_name[0] != '\0')
612                         errx(ED_EFMT("duplicated token: %s"), name);
613                     strncpy(profile_name, arg, sizeof(profile_name) - 1);
614                     profile_name[sizeof(profile_name)-1] = '\0';
615                     do_points = 0;
616                 } else if (!strcasecmp(name, ED_TOK_DELAY)) {
617                     if (do_points)
618                         errx(ED_EFMT("duplicated token: %s"), name);
619                     delay_first = 1;
620                     do_points = 1;
621                 } else if (!strcasecmp(name, ED_TOK_PROB)) {
622                     if (do_points)
623                         errx(ED_EFMT("duplicated token: %s"), name);
624                     delay_first = 0;
625                     do_points = 1;
626                 } else if (do_points) {
627                     if (!is_valid_number(name) || !is_valid_number(arg))
628                         errx(ED_EFMT("invalid point found"));
629                     if (delay_first) {
630                         points[points_no].delay = atof(name);
631                         points[points_no].prob = atof(arg);
632                     } else {
633                         points[points_no].delay = atof(arg);
634                         points[points_no].prob = atof(name);
635                     }
636                     if (points[points_no].prob > 1.0)
637                         errx(ED_EFMT("probability greater than 1.0"));
638                     ++points_no;
639                 } else {
640                     errx(ED_EFMT("unrecognised command '%s'"), name);
641                 }
642         }
643
644         if (samples == -1) {
645             warnx("'%s' not found, assuming 100", ED_TOK_SAMPLES);
646             samples = 100;
647         }
648
649         if (loss == -1.0) {
650             warnx("'%s' not found, assuming no loss", ED_TOK_LOSS);
651             loss = 1;
652         }
653
654         /* make sure that there are enough points. */
655         if (points_no < ED_MIN_SAMPLES_NO)
656             errx(ED_EFMT("too few samples, need at least %d"),
657                 ED_MIN_SAMPLES_NO);
658
659         qsort(points, points_no, sizeof(struct point), compare_points);
660
661         /* interpolation */
662         for (i = 0; i<points_no-1; ++i) {
663             double y1 = points[i].prob * samples;
664             double x1 = points[i].delay;
665             double y2 = points[i+1].prob * samples;
666             double x2 = points[i+1].delay;
667
668             int index = y1;
669             int stop = y2;
670
671             if (x1 == x2) {
672                 for (; index<stop; ++index)
673                     p->samples[index] = x1;
674             } else {
675                 double m = (y2-y1)/(x2-x1);
676                 double c = y1 - m*x1;
677                 for (; index<stop ; ++index)
678                     p->samples[index] = (index - c)/m;
679             }
680         }
681         p->samples_no = samples;
682         p->loss_level = loss * samples;
683         strncpy(p->name, profile_name, sizeof(p->name));
684 }
685
686 void
687 ipfw_config_pipe(int ac, char **av)
688 {
689         int samples[ED_MAX_SAMPLES_NO];
690         struct dn_pipe p;
691         int i;
692         char *end;
693         void *par = NULL;
694
695         memset(&p, 0, sizeof p);
696         p.bandwidth = -1;
697
698         av++; ac--;
699         /* Pipe number */
700         if (ac && isdigit(**av)) {
701                 i = atoi(*av); av++; ac--;
702                 if (co.do_pipe == 1)
703                         p.pipe_nr = i;
704                 else
705                         p.fs.fs_nr = i;
706         }
707         while (ac > 0) {
708                 double d;
709                 int tok = match_token(dummynet_params, *av);
710                 ac--; av++;
711
712                 switch(tok) {
713                 case TOK_NOERROR:
714                         p.fs.flags_fs |= DN_NOERROR;
715                         break;
716
717                 case TOK_PLR:
718                         NEED1("plr needs argument 0..1\n");
719                         d = strtod(av[0], NULL);
720                         if (d > 1)
721                                 d = 1;
722                         else if (d < 0)
723                                 d = 0;
724                         p.fs.plr = (int)(d*0x7fffffff);
725                         ac--; av++;
726                         break;
727
728                 case TOK_QUEUE:
729                         NEED1("queue needs queue size\n");
730                         end = NULL;
731                         p.fs.qsize = strtoul(av[0], &end, 0);
732                         if (*end == 'K' || *end == 'k') {
733                                 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
734                                 p.fs.qsize *= 1024;
735                         } else if (*end == 'B' ||
736                             _substrcmp2(end, "by", "bytes") == 0) {
737                                 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
738                         }
739                         ac--; av++;
740                         break;
741
742                 case TOK_BUCKETS:
743                         NEED1("buckets needs argument\n");
744                         p.fs.rq_size = strtoul(av[0], NULL, 0);
745                         ac--; av++;
746                         break;
747
748                 case TOK_MASK:
749                         NEED1("mask needs mask specifier\n");
750                         /*
751                          * per-flow queue, mask is dst_ip, dst_port,
752                          * src_ip, src_port, proto measured in bits
753                          */
754                         par = NULL;
755
756                         bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
757                         end = NULL;
758
759                         while (ac >= 1) {
760                             uint32_t *p32 = NULL;
761                             uint16_t *p16 = NULL;
762                             uint32_t *p20 = NULL;
763                             struct in6_addr *pa6 = NULL;
764                             uint32_t a;
765
766                             tok = match_token(dummynet_params, *av);
767                             ac--; av++;
768                             switch(tok) {
769                             case TOK_ALL:
770                                     /*
771                                      * special case, all bits significant
772                                      */
773                                     p.fs.flow_mask.dst_ip = ~0;
774                                     p.fs.flow_mask.src_ip = ~0;
775                                     p.fs.flow_mask.dst_port = ~0;
776                                     p.fs.flow_mask.src_port = ~0;
777                                     p.fs.flow_mask.proto = ~0;
778                                     n2mask(&(p.fs.flow_mask.dst_ip6), 128);
779                                     n2mask(&(p.fs.flow_mask.src_ip6), 128);
780                                     p.fs.flow_mask.flow_id6 = ~0;
781                                     p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
782                                     goto end_mask;
783
784                             case TOK_DSTIP:
785                                     p32 = &p.fs.flow_mask.dst_ip;
786                                     break;
787
788                             case TOK_SRCIP:
789                                     p32 = &p.fs.flow_mask.src_ip;
790                                     break;
791
792                             case TOK_DSTIP6:
793                                     pa6 = &(p.fs.flow_mask.dst_ip6);
794                                     break;
795                             
796                             case TOK_SRCIP6:
797                                     pa6 = &(p.fs.flow_mask.src_ip6);
798                                     break;
799
800                             case TOK_FLOWID:
801                                     p20 = &p.fs.flow_mask.flow_id6;
802                                     break;
803
804                             case TOK_DSTPORT:
805                                     p16 = &p.fs.flow_mask.dst_port;
806                                     break;
807
808                             case TOK_SRCPORT:
809                                     p16 = &p.fs.flow_mask.src_port;
810                                     break;
811
812                             case TOK_PROTO:
813                                     break;
814
815                             default:
816                                     ac++; av--; /* backtrack */
817                                     goto end_mask;
818                             }
819                             if (ac < 1)
820                                     errx(EX_USAGE, "mask: value missing");
821                             if (*av[0] == '/') {
822                                     a = strtoul(av[0]+1, &end, 0);
823                                     if (pa6 == NULL)
824                                             a = (a == 32) ? ~0 : (1 << a) - 1;
825                             } else
826                                     a = strtoul(av[0], &end, 0);
827                             if (p32 != NULL)
828                                     *p32 = a;
829                             else if (p16 != NULL) {
830                                     if (a > 0xFFFF)
831                                             errx(EX_DATAERR,
832                                                 "port mask must be 16 bit");
833                                     *p16 = (uint16_t)a;
834                             } else if (p20 != NULL) {
835                                     if (a > 0xfffff)
836                                         errx(EX_DATAERR,
837                                             "flow_id mask must be 20 bit");
838                                     *p20 = (uint32_t)a;
839                             } else if (pa6 != NULL) {
840                                     if (a > 128)
841                                         errx(EX_DATAERR,
842                                             "in6addr invalid mask len");
843                                     else
844                                         n2mask(pa6, a);
845                             } else {
846                                     if (a > 0xFF)
847                                             errx(EX_DATAERR,
848                                                 "proto mask must be 8 bit");
849                                     p.fs.flow_mask.proto = (uint8_t)a;
850                             }
851                             if (a != 0)
852                                     p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
853                             ac--; av++;
854                         } /* end while, config masks */
855 end_mask:
856                         break;
857
858                 case TOK_RED:
859                 case TOK_GRED:
860                         NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
861                         p.fs.flags_fs |= DN_IS_RED;
862                         if (tok == TOK_GRED)
863                                 p.fs.flags_fs |= DN_IS_GENTLE_RED;
864                         /*
865                          * the format for parameters is w_q/min_th/max_th/max_p
866                          */
867                         if ((end = strsep(&av[0], "/"))) {
868                             double w_q = strtod(end, NULL);
869                             if (w_q > 1 || w_q <= 0)
870                                 errx(EX_DATAERR, "0 < w_q <= 1");
871                             p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
872                         }
873                         if ((end = strsep(&av[0], "/"))) {
874                             p.fs.min_th = strtoul(end, &end, 0);
875                             if (*end == 'K' || *end == 'k')
876                                 p.fs.min_th *= 1024;
877                         }
878                         if ((end = strsep(&av[0], "/"))) {
879                             p.fs.max_th = strtoul(end, &end, 0);
880                             if (*end == 'K' || *end == 'k')
881                                 p.fs.max_th *= 1024;
882                         }
883                         if ((end = strsep(&av[0], "/"))) {
884                             double max_p = strtod(end, NULL);
885                             if (max_p > 1 || max_p <= 0)
886                                 errx(EX_DATAERR, "0 < max_p <= 1");
887                             p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
888                         }
889                         ac--; av++;
890                         break;
891
892                 case TOK_DROPTAIL:
893                         p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
894                         break;
895
896                 case TOK_BW:
897                         NEED1("bw needs bandwidth or interface\n");
898                         if (co.do_pipe != 1)
899                             errx(EX_DATAERR, "bandwidth only valid for pipes");
900                         read_bandwidth(av[0], &p.bandwidth, p.if_name, sizeof(p.if_name));
901                         ac--; av++;
902                         break;
903
904                 case TOK_DELAY:
905                         if (co.do_pipe != 1)
906                                 errx(EX_DATAERR, "delay only valid for pipes");
907                         NEED1("delay needs argument 0..10000ms\n");
908                         p.delay = strtoul(av[0], NULL, 0);
909                         ac--; av++;
910                         break;
911
912                 case TOK_WEIGHT:
913                         if (co.do_pipe == 1)
914                                 errx(EX_DATAERR,"weight only valid for queues");
915                         NEED1("weight needs argument 0..100\n");
916                         p.fs.weight = strtoul(av[0], &end, 0);
917                         ac--; av++;
918                         break;
919
920                 case TOK_PIPE:
921                         if (co.do_pipe == 1)
922                                 errx(EX_DATAERR,"pipe only valid for queues");
923                         NEED1("pipe needs pipe_number\n");
924                         p.fs.parent_nr = strtoul(av[0], &end, 0);
925                         ac--; av++;
926                         break;
927
928                 case TOK_PIPE_PROFILE:
929                         if (co.do_pipe != 1)
930                             errx(EX_DATAERR, "extra delay only valid for pipes");
931                         NEED1("extra delay needs the file name\n");
932                         p.samples = &samples[0];
933                         load_extra_delays(av[0], &p);
934                         --ac; ++av;
935                         break;
936
937                 default:
938                         errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
939                 }
940         }
941         if (co.do_pipe == 1) {
942                 if (p.pipe_nr == 0)
943                         errx(EX_DATAERR, "pipe_nr must be > 0");
944                 if (p.delay > 10000)
945                         errx(EX_DATAERR, "delay must be < 10000");
946         } else { /* co.do_pipe == 2, queue */
947                 if (p.fs.parent_nr == 0)
948                         errx(EX_DATAERR, "pipe must be > 0");
949                 if (p.fs.weight >100)
950                         errx(EX_DATAERR, "weight must be <= 100");
951         }
952
953         /* check for bandwidth value */
954         if (p.bandwidth == -1) {
955                 p.bandwidth = 0;
956                 if (p.samples_no > 0)
957                         errx(EX_DATAERR, "profile requires a bandwidth limit");
958         }
959
960         if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
961                 size_t len;
962                 long limit;
963
964                 len = sizeof(limit);
965                 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
966                         &limit, &len, NULL, 0) == -1)
967                         limit = 1024*1024;
968                 if (p.fs.qsize > limit)
969                         errx(EX_DATAERR, "queue size must be < %ldB", limit);
970         } else {
971                 size_t len;
972                 long limit;
973
974                 len = sizeof(limit);
975                 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
976                         &limit, &len, NULL, 0) == -1)
977                         limit = 100;
978                 if (p.fs.qsize > limit)
979                         errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
980         }
981         if (p.fs.flags_fs & DN_IS_RED) {
982                 size_t len;
983                 int lookup_depth, avg_pkt_size;
984                 double s, idle, weight, w_q;
985                 struct clockinfo ck;
986                 int t;
987
988                 if (p.fs.min_th >= p.fs.max_th)
989                     errx(EX_DATAERR, "min_th %d must be < than max_th %d",
990                         p.fs.min_th, p.fs.max_th);
991                 if (p.fs.max_th == 0)
992                     errx(EX_DATAERR, "max_th must be > 0");
993
994                 len = sizeof(int);
995                 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
996                         &lookup_depth, &len, NULL, 0) == -1)
997                     errx(1, "sysctlbyname(\"%s\")",
998                         "net.inet.ip.dummynet.red_lookup_depth");
999                 if (lookup_depth == 0)
1000                     errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
1001                         " must be greater than zero");
1002
1003                 len = sizeof(int);
1004                 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
1005                         &avg_pkt_size, &len, NULL, 0) == -1)
1006
1007                     errx(1, "sysctlbyname(\"%s\")",
1008                         "net.inet.ip.dummynet.red_avg_pkt_size");
1009                 if (avg_pkt_size == 0)
1010                         errx(EX_DATAERR,
1011                             "net.inet.ip.dummynet.red_avg_pkt_size must"
1012                             " be greater than zero");
1013
1014                 len = sizeof(struct clockinfo);
1015                 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
1016                         errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
1017
1018                 /*
1019                  * Ticks needed for sending a medium-sized packet.
1020                  * Unfortunately, when we are configuring a WF2Q+ queue, we
1021                  * do not have bandwidth information, because that is stored
1022                  * in the parent pipe, and also we have multiple queues
1023                  * competing for it. So we set s=0, which is not very
1024                  * correct. But on the other hand, why do we want RED with
1025                  * WF2Q+ ?
1026                  */
1027                 if (p.bandwidth==0) /* this is a WF2Q+ queue */
1028                         s = 0;
1029                 else
1030                         s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
1031
1032                 /*
1033                  * max idle time (in ticks) before avg queue size becomes 0.
1034                  * NOTA:  (3/w_q) is approx the value x so that
1035                  * (1-w_q)^x < 10^-3.
1036                  */
1037                 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
1038                 idle = s * 3. / w_q;
1039                 p.fs.lookup_step = (int)idle / lookup_depth;
1040                 if (!p.fs.lookup_step)
1041                         p.fs.lookup_step = 1;
1042                 weight = 1 - w_q;
1043                 for (t = p.fs.lookup_step; t > 1; --t)
1044                         weight *= 1 - w_q;
1045                 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
1046         }
1047         if (p.samples_no <= 0) {
1048         i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
1049         } else {
1050                 struct dn_pipe_max pm;
1051                 int len = sizeof(pm);
1052
1053                 memcpy(&pm.pipe, &p, sizeof(pm.pipe));
1054                 memcpy(&pm.samples, samples, sizeof(pm.samples));
1055
1056                 i = do_cmd(IP_DUMMYNET_CONFIGURE, &pm, len);
1057         }
1058
1059         if (i)
1060                 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
1061 }