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