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