]> git.cameronkatri.com Git - apple_cmds.git/blob - network_cmds/dnctl/dnctl.c
file_cmds: gzip: Fix BINDIR
[apple_cmds.git] / network_cmds / dnctl / dnctl.c
1 /*
2 * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 /*
30 * Copyright (c) 2002-2003 Luigi Rizzo
31 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
32 * Copyright (c) 1994 Ugen J.S.Antsilevich
33 *
34 * Idea and grammar partially left from:
35 * Copyright (c) 1993 Daniel Boulet
36 *
37 * Redistribution and use in source forms, with and without modification,
38 * are permitted provided that this entire comment appears intact.
39 *
40 * Redistribution in binary form may occur without any restrictions.
41 * Obviously, it would be nice if you gave credit where credit is due
42 * but requiring it would be too onerous.
43 *
44 * This software is provided ``AS IS'' without any warranties of any kind.
45 */
46
47 /*
48 * Ripped off ipfw2.c
49 */
50
51 #include <sys/param.h>
52 #include <sys/socket.h>
53 #include <sys/sysctl.h>
54
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <netdb.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <stdarg.h>
63 #include <string.h>
64 #include <unistd.h>
65 #include <sysexits.h>
66
67 #include <net/if.h>
68 #include <netinet/in.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_dummynet.h>
71 #include <arpa/inet.h>
72
73 #include <libiosexec.h>
74
75 /*
76 * Limit delay to avoid computation overflow
77 */
78 #define MAX_DELAY (INT_MAX / 1000)
79
80
81 int
82 do_quiet, /* Be quiet in add and flush */
83 do_pipe, /* this cmd refers to a pipe */
84 do_sort, /* field to sort results (0 = no) */
85 test_only, /* only check syntax */
86 verbose;
87
88 #define IP_MASK_ALL 0xffffffff
89
90 /*
91 * _s_x is a structure that stores a string <-> token pairs, used in
92 * various places in the parser. Entries are stored in arrays,
93 * with an entry with s=NULL as terminator.
94 * The search routines are match_token() and match_value().
95 * Often, an element with x=0 contains an error string.
96 *
97 */
98 struct _s_x {
99 char const *s;
100 int x;
101 };
102
103 enum tokens {
104 TOK_NULL=0,
105
106 TOK_ACCEPT,
107 TOK_COUNT,
108 TOK_PIPE,
109 TOK_QUEUE,
110
111 TOK_PLR,
112 TOK_NOERROR,
113 TOK_BUCKETS,
114 TOK_DSTIP,
115 TOK_SRCIP,
116 TOK_DSTPORT,
117 TOK_SRCPORT,
118 TOK_ALL,
119 TOK_MASK,
120 TOK_BW,
121 TOK_DELAY,
122 TOK_RED,
123 TOK_GRED,
124 TOK_DROPTAIL,
125 TOK_PROTO,
126 TOK_WEIGHT,
127
128 TOK_DSTIP6,
129 TOK_SRCIP6,
130 };
131
132 struct _s_x dummynet_params[] = {
133 { "plr", TOK_PLR },
134 { "noerror", TOK_NOERROR },
135 { "buckets", TOK_BUCKETS },
136 { "dst-ip", TOK_DSTIP },
137 { "src-ip", TOK_SRCIP },
138 { "dst-port", TOK_DSTPORT },
139 { "src-port", TOK_SRCPORT },
140 { "proto", TOK_PROTO },
141 { "weight", TOK_WEIGHT },
142 { "all", TOK_ALL },
143 { "mask", TOK_MASK },
144 { "droptail", TOK_DROPTAIL },
145 { "red", TOK_RED },
146 { "gred", TOK_GRED },
147 { "bw", TOK_BW },
148 { "bandwidth", TOK_BW },
149 { "delay", TOK_DELAY },
150 { "pipe", TOK_PIPE },
151 { "queue", TOK_QUEUE },
152 { "dst-ipv6", TOK_DSTIP6},
153 { "dst-ip6", TOK_DSTIP6},
154 { "src-ipv6", TOK_SRCIP6},
155 { "src-ip6", TOK_SRCIP6},
156 { "dummynet-params", TOK_NULL },
157 { NULL, 0 } /* terminator */
158 };
159
160 static void show_usage(void);
161
162
163 void n2mask(struct in6_addr *, int );
164 unsigned long long align_uint64(const uint64_t *);
165
166 /* n2mask sets n bits of the mask */
167 void
168 n2mask(struct in6_addr *mask, int n)
169 {
170 static int minimask[9] =
171 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
172 u_char *p;
173
174 memset(mask, 0, sizeof(struct in6_addr));
175 p = (u_char *) mask;
176 for (; n > 0; p++, n -= 8) {
177 if (n >= 8)
178 *p = 0xff;
179 else
180 *p = minimask[n];
181 }
182 return;
183 }
184
185 /*
186 * The following is used to generate a printable argument for
187 * 64-bit numbers, irrespective of platform alignment and bit size.
188 * Because all the printf in this program use %llu as a format,
189 * we just return an unsigned long long, which is larger than
190 * we need in certain cases, but saves the hassle of using
191 * PRIu64 as a format specifier.
192 * We don't care about inlining, this is not performance critical code.
193 */
194 unsigned long long
195 align_uint64(const uint64_t *pll)
196 {
197 uint64_t ret;
198
199 bcopy (pll, &ret, sizeof(ret));
200 return ret;
201 }
202
203 /*
204 * conditionally runs the command.
205 */
206 static int
207 do_cmd(int optname, void *optval, socklen_t *optlen)
208 {
209 static int s = -1; /* the socket */
210 int i;
211
212 if (test_only)
213 return 0;
214
215 if (s == -1)
216 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
217 if (s < 0)
218 err(EX_UNAVAILABLE, "socket");
219
220 if (optname == IP_DUMMYNET_GET)
221 i = getsockopt(s, IPPROTO_IP, optname, optval, optlen);
222 else
223 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen ? *optlen : 0);
224 return i;
225 }
226
227 /**
228 * match_token takes a table and a string, returns the value associated
229 * with the string (-1 in case of failure).
230 */
231 static int
232 match_token(struct _s_x *table, char *string)
233 {
234 struct _s_x *pt;
235 size_t i = strlen(string);
236
237 for (pt = table ; i && pt->s != NULL ; pt++)
238 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
239 return pt->x;
240 return -1;
241 };
242
243 static int
244 sort_q(const void *pa, const void *pb)
245 {
246 int rev = (do_sort < 0);
247 int field = rev ? -do_sort : do_sort;
248 long long res = 0;
249 const struct dn_flow_queue *a = pa;
250 const struct dn_flow_queue *b = pb;
251
252 switch (field) {
253 case 1: /* pkts */
254 res = a->len - b->len;
255 break;
256 case 2: /* bytes */
257 res = a->len_bytes - b->len_bytes;
258 break;
259
260 case 3: /* tot pkts */
261 res = a->tot_pkts - b->tot_pkts;
262 break;
263
264 case 4: /* tot bytes */
265 res = a->tot_bytes - b->tot_bytes;
266 break;
267 }
268 if (res < 0)
269 res = -1;
270 if (res > 0)
271 res = 1;
272 return (int)(rev ? res : -res);
273 }
274
275 static void
276 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
277 {
278 int l;
279 int index_printed = 0, indexes = 0;
280 char buff[255];
281 struct protoent *pe;
282
283 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
284 fs->flow_mask.proto,
285 fs->flow_mask.src_ip, fs->flow_mask.src_port,
286 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
287 if (fs->rq_elements == 0)
288 return;
289
290 printf("BKT Prot ___Source IP/port____ "
291 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
292 if (do_sort != 0)
293 heapsort(q, fs->rq_elements, sizeof(struct dn_flow_queue), sort_q);
294
295 /* Print IPv4 flows */
296 for (l = 0; l < fs->rq_elements; l++) {
297 struct in_addr ina;
298
299 /* XXX: Should check for IPv4 flows */
300 if (IS_IP6_FLOW_ID(&(q[l].id)))
301 continue;
302
303 if (!index_printed) {
304 index_printed = 1;
305 if (indexes > 0) /* currently a no-op */
306 printf("\n");
307 indexes++;
308 printf(" "
309 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
310 fs->flow_mask.proto,
311 fs->flow_mask.src_ip, fs->flow_mask.src_port,
312 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
313
314 printf("BKT Prot ___Source IP/port____ "
315 "____Dest. IP/port____ "
316 "Tot_pkt/bytes Pkt/Byte Drp\n");
317 }
318
319 printf("%3d ", q[l].hash_slot);
320 pe = getprotobynumber(q[l].id.proto);
321 if (pe)
322 printf("%-4s ", pe->p_name);
323 else
324 printf("%4u ", q[l].id.proto);
325 ina.s_addr = htonl(q[l].id.src_ip);
326 printf("%15s/%-5d ",
327 inet_ntoa(ina), q[l].id.src_port);
328 ina.s_addr = htonl(q[l].id.dst_ip);
329 printf("%15s/%-5d ",
330 inet_ntoa(ina), q[l].id.dst_port);
331 printf("%4llu %8llu %2u %4u %3u\n",
332 align_uint64(&q[l].tot_pkts),
333 align_uint64(&q[l].tot_bytes),
334 q[l].len, q[l].len_bytes, q[l].drops);
335 if (verbose)
336 printf(" S %20llu F %20llu\n",
337 align_uint64(&q[l].S), align_uint64(&q[l].F));
338 }
339
340 /* Print IPv6 flows */
341 index_printed = 0;
342 for (l = 0; l < fs->rq_elements; l++) {
343 if (!IS_IP6_FLOW_ID(&(q[l].id)))
344 continue;
345
346 if (!index_printed) {
347 index_printed = 1;
348 if (indexes > 0)
349 printf("\n");
350 indexes++;
351 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ",
352 fs->flow_mask.proto, fs->flow_mask.flow_id6);
353 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
354 buff, sizeof(buff));
355 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
356 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
357 buff, sizeof(buff) );
358 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
359
360 printf("BKT ___Prot___ _flow-id_ "
361 "______________Source IPv6/port_______________ "
362 "_______________Dest. IPv6/port_______________ "
363 "Tot_pkt/bytes Pkt/Byte Drp\n");
364 }
365 printf("%3d ", q[l].hash_slot);
366 pe = getprotobynumber(q[l].id.proto);
367 if (pe != NULL)
368 printf("%9s ", pe->p_name);
369 else
370 printf("%9u ", q[l].id.proto);
371 printf("%7d %39s/%-5d ", q[l].id.flow_id6,
372 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
373 q[l].id.src_port);
374 printf(" %39s/%-5d ",
375 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
376 q[l].id.dst_port);
377 printf(" %4llu %8llu %2u %4u %3u\n",
378 align_uint64(&q[l].tot_pkts),
379 align_uint64(&q[l].tot_bytes),
380 q[l].len, q[l].len_bytes, q[l].drops);
381 if (verbose)
382 printf(" S %20llu F %20llu\n",
383 align_uint64(&q[l].S),
384 align_uint64(&q[l].F));
385 }
386 }
387
388 static void
389 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
390 {
391 int l;
392 char qs[30];
393 char plr[30];
394 char red[90]; /* Display RED parameters */
395
396 l = fs->qsize;
397 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
398 if (l >= 8192)
399 snprintf(qs, sizeof(qs), "%d KB", l / 1024);
400 else
401 snprintf(qs, sizeof(qs), "%d B", l);
402 } else
403 snprintf(qs, sizeof(qs), "%3d sl.", l);
404 if (fs->plr)
405 snprintf(plr, sizeof(plr), "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
406 else
407 plr[0] = '\0';
408 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
409 snprintf(red, sizeof(red),
410 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
411 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
412 1.0 * fs->w_q / (double)(1 << SCALE_RED),
413 SCALE_VAL(fs->min_th),
414 SCALE_VAL(fs->max_th),
415 1.0 * fs->max_p / (double)(1 << SCALE_RED));
416 else
417 snprintf(red, sizeof(red), "droptail");
418
419 printf("%s %s%s %d queues (%d buckets) %s\n",
420 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
421 }
422
423 static void
424 list_pipes(void *data, size_t nbytes, int ac, char *av[])
425 {
426 unsigned int rulenum;
427 void *next = data;
428 struct dn_pipe *p = (struct dn_pipe *) data;
429 struct dn_flow_set *fs;
430 struct dn_flow_queue *q;
431 size_t l;
432
433 if (ac > 0)
434 rulenum = (unsigned int)strtoul(*av++, NULL, 10);
435 else
436 rulenum = 0;
437 for (; nbytes >= sizeof(struct dn_pipe); p = (struct dn_pipe *)next) {
438 double b = p->bandwidth;
439 char buf[30];
440 char prefix[80];
441
442 if (p->next.sle_next != (struct dn_pipe *)DN_IS_PIPE)
443 break; /* done with pipes, now queues */
444
445 /*
446 * compute length, as pipe have variable size
447 */
448 l = sizeof(struct dn_pipe) + p->fs.rq_elements * sizeof(struct dn_flow_queue);
449 next = (char *)p + l;
450 nbytes -= l;
451
452 if (rulenum != 0 && rulenum != p->pipe_nr)
453 continue;
454
455 /*
456 * Print rate (or clocking interface)
457 */
458 if (p->if_name[0] != '\0')
459 snprintf(buf, sizeof(buf), "%s", p->if_name);
460 else if (b == 0)
461 snprintf(buf, sizeof(buf), "unlimited");
462 else if (b >= 1000000)
463 snprintf(buf, sizeof(buf), "%7.3f Mbit/s", b/1000000);
464 else if (b >= 1000)
465 snprintf(buf, sizeof(buf), "%7.3f Kbit/s", b/1000);
466 else
467 snprintf(buf, sizeof(buf), "%7.3f bit/s ", b);
468
469 snprintf(prefix, sizeof(prefix), "%05d: %s %4d ms ",
470 p->pipe_nr, buf, p->delay);
471 print_flowset_parms(&(p->fs), prefix);
472 if (verbose)
473 printf(" V %20qd\n", p->V >> MY_M);
474
475 q = (struct dn_flow_queue *)(p+1);
476 list_queues(&(p->fs), q);
477 }
478 for (fs = next; nbytes >= sizeof *fs; fs = next) {
479 char prefix[80];
480
481 if (fs->next.sle_next != (struct dn_flow_set *)DN_IS_QUEUE)
482 break;
483 l = sizeof(struct dn_flow_set) + fs->rq_elements * sizeof(struct dn_flow_queue);
484 next = (char *)fs + l;
485 nbytes -= l;
486 q = (struct dn_flow_queue *)(fs+1);
487 snprintf(prefix, sizeof(prefix), "q%05d: weight %d pipe %d ",
488 fs->fs_nr, fs->weight, fs->parent_nr);
489 print_flowset_parms(fs, prefix);
490 list_queues(fs, q);
491 }
492 }
493
494 static void
495 list(int ac, char *av[], int show_counters)
496 {
497 void *data = NULL;
498 socklen_t nbytes;
499 int exitval = EX_OK;
500
501 int nalloc = 1024; /* start somewhere... */
502
503 if (test_only) {
504 fprintf(stderr, "Testing only, list disabled\n");
505 return;
506 }
507
508 ac--;
509 av++;
510
511 /* get rules or pipes from kernel, resizing array as necessary */
512 nbytes = nalloc;
513
514 while (nbytes >= nalloc) {
515 nalloc = nalloc * 2 + 200;
516 nbytes = nalloc;
517 if ((data = realloc(data, nbytes)) == NULL)
518 err(EX_OSERR, "realloc");
519
520 if (do_cmd(IP_DUMMYNET_GET, data, &nbytes) < 0) {
521 if (errno == ENOBUFS) {
522 nbytes = 0;
523 break;
524 }
525 err(EX_OSERR, "getsockopt(IP_DUMMYNET_GET)");
526
527 }
528 }
529
530 list_pipes(data, nbytes, ac, av);
531
532 free(data);
533
534 if (exitval != EX_OK)
535 exit(exitval);
536 }
537
538 static void
539 show_usage(void)
540 {
541 fprintf(stderr, "usage: dnctl [options]\n"
542 "do \"dnctl -h\" or see dnctl manpage for details\n"
543 );
544 exit(EX_USAGE);
545 }
546
547 static void
548 help(void)
549 {
550 fprintf(stderr,
551 "dnclt [-acdeftTnNpqS] <command> where <command> is one of:\n"
552 "{pipe|queue} N config PIPE-BODY\n"
553 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
554 );
555 exit(0);
556 }
557
558 static void
559 delete(int ac, char *av[])
560 {
561 struct dn_pipe p;
562 int i;
563 int exitval = EX_OK;
564 socklen_t len;
565
566 memset(&p, 0, sizeof(struct dn_pipe));
567
568 av++; ac--;
569
570 while (ac && isdigit(**av)) {
571 i = atoi(*av); av++; ac--;
572
573 if (do_pipe == 1)
574 p.pipe_nr = i;
575 else
576 p.fs.fs_nr = i;
577 len = sizeof(struct dn_pipe);
578 i = do_cmd(IP_DUMMYNET_DEL, &p, &len);
579 if (i) {
580 exitval = 1;
581 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
582 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
583 }
584 }
585 if (exitval != EX_OK)
586 exit(exitval);
587 }
588
589 /*
590 * the following macro returns an error message if we run out of
591 * arguments.
592 */
593 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
594 #define NEED2(msg, arg) {if (!ac) errx(EX_USAGE, msg, arg);}
595
596 static void
597 config_pipe(int ac, char **av)
598 {
599 struct dn_pipe p;
600 int i;
601 char *end;
602 void *par = NULL;
603 socklen_t len;
604
605 memset(&p, 0, sizeof(struct dn_pipe));
606
607 av++; ac--;
608 /* Pipe number */
609 if (ac && isdigit(**av)) {
610 i = atoi(*av); av++; ac--;
611 if (do_pipe == 1)
612 p.pipe_nr = i;
613 else
614 p.fs.fs_nr = i;
615 }
616 while (ac > 0) {
617 double d;
618 int tok = match_token(dummynet_params, *av);
619 ac--; av++;
620
621 switch(tok) {
622 case TOK_NOERROR:
623 p.fs.flags_fs |= DN_NOERROR;
624 break;
625
626 case TOK_PLR:
627 NEED1("plr needs argument 0..1\n");
628 d = strtod(av[0], NULL);
629 if (d > 1)
630 d = 1;
631 else if (d < 0)
632 d = 0;
633 p.fs.plr = (int)(d*0x7fffffff);
634 ac--; av++;
635 break;
636
637 case TOK_QUEUE:
638 NEED1("queue needs queue size\n");
639 end = NULL;
640 p.fs.qsize = (int)strtoul(av[0], &end, 0);
641 if (*end == 'K' || *end == 'k') {
642 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
643 p.fs.qsize *= 1024;
644 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
645 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
646 }
647 ac--; av++;
648 break;
649
650 case TOK_BUCKETS:
651 NEED1("buckets needs argument\n");
652 p.fs.rq_size = (int)strtoul(av[0], NULL, 0);
653 ac--; av++;
654 break;
655
656 case TOK_MASK:
657 NEED1("mask needs mask specifier\n");
658 /*
659 * per-flow queue, mask is dst_ip, dst_port,
660 * src_ip, src_port, proto measured in bits
661 */
662 par = NULL;
663
664 p.fs.flow_mask.dst_ip = 0;
665 p.fs.flow_mask.src_ip = 0;
666 p.fs.flow_mask.dst_port = 0;
667 p.fs.flow_mask.src_port = 0;
668 p.fs.flow_mask.proto = 0;
669 end = NULL;
670
671 while (ac >= 1) {
672 uint32_t *p32 = NULL;
673 uint16_t *p16 = NULL;
674 struct in6_addr *pa6 = NULL;
675 uint32_t a;
676
677 tok = match_token(dummynet_params, *av);
678 ac--; av++;
679 switch(tok) {
680 case TOK_ALL:
681 /*
682 * special case, all bits significant
683 */
684 p.fs.flow_mask.dst_ip = ~0;
685 p.fs.flow_mask.src_ip = ~0;
686 p.fs.flow_mask.dst_port = ~0;
687 p.fs.flow_mask.src_port = ~0;
688 p.fs.flow_mask.proto = ~0;
689 n2mask(&(p.fs.flow_mask.dst_ip6), 128);
690 n2mask(&(p.fs.flow_mask.src_ip6), 128);
691 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
692 goto end_mask;
693
694 case TOK_DSTIP:
695 p32 = &p.fs.flow_mask.dst_ip;
696 break;
697
698 case TOK_SRCIP:
699 p32 = &p.fs.flow_mask.src_ip;
700 break;
701
702 case TOK_DSTIP6:
703 pa6 = &(p.fs.flow_mask.dst_ip6);
704 break;
705
706 case TOK_SRCIP6:
707 pa6 = &(p.fs.flow_mask.src_ip6);
708 break;
709
710 case TOK_DSTPORT:
711 p16 = &p.fs.flow_mask.dst_port;
712 break;
713
714 case TOK_SRCPORT:
715 p16 = &p.fs.flow_mask.src_port;
716 break;
717
718 case TOK_PROTO:
719 break;
720
721 default:
722 ac++; av--; /* backtrack */
723 goto end_mask;
724 }
725 if (ac < 1)
726 errx(EX_USAGE, "mask: value missing");
727 if (*av[0] == '/') {
728 a = (int)strtoul(av[0]+1, &end, 0);
729 if (pa6 == NULL)
730 a = (a == 32) ? ~0 : (1 << a) - 1;
731 } else
732 a = (int)strtoul(av[0], &end, 0);
733 if (p32 != NULL)
734 *p32 = a;
735 else if (p16 != NULL) {
736 if (a > 65535)
737 errx(EX_DATAERR,
738 "mask: must be 16 bit");
739 *p16 = (uint16_t)a;
740 } else if (pa6 != NULL) {
741 if (a > 128)
742 errx(EX_DATAERR,
743 "in6addr invalid mask len");
744 else
745 n2mask(pa6, a);
746 } else {
747 if (a > 255)
748 errx(EX_DATAERR,
749 "mask: must be 8 bit");
750 p.fs.flow_mask.proto = (uint8_t)a;
751 }
752 if (a != 0)
753 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
754 ac--; av++;
755 } /* end while, config masks */
756 end_mask:
757 break;
758
759 case TOK_RED:
760 case TOK_GRED:
761 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
762 p.fs.flags_fs |= DN_IS_RED;
763 if (tok == TOK_GRED)
764 p.fs.flags_fs |= DN_IS_GENTLE_RED;
765 /*
766 * the format for parameters is w_q/min_th/max_th/max_p
767 */
768 if ((end = strsep(&av[0], "/"))) {
769 double w_q = strtod(end, NULL);
770 if (w_q > 1 || w_q <= 0)
771 errx(EX_DATAERR, "0 < w_q <= 1");
772 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
773 }
774 if ((end = strsep(&av[0], "/"))) {
775 p.fs.min_th = (int)strtoul(end, &end, 0);
776 if (*end == 'K' || *end == 'k')
777 p.fs.min_th *= 1024;
778 }
779 if ((end = strsep(&av[0], "/"))) {
780 p.fs.max_th = (int)strtoul(end, &end, 0);
781 if (*end == 'K' || *end == 'k')
782 p.fs.max_th *= 1024;
783 }
784 if ((end = strsep(&av[0], "/"))) {
785 double max_p = strtod(end, NULL);
786 if (max_p > 1 || max_p <= 0)
787 errx(EX_DATAERR, "0 < max_p <= 1");
788 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
789 }
790 ac--; av++;
791 break;
792
793 case TOK_DROPTAIL:
794 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
795 break;
796
797 case TOK_BW:
798 NEED1("bw needs bandwidth or interface\n");
799 if (do_pipe != 1)
800 errx(EX_DATAERR, "bandwidth only valid for pipes");
801 /*
802 * set clocking interface or bandwidth value
803 */
804 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
805 /* interface name */
806 strlcpy(p.if_name, av[0], sizeof(p.if_name));
807 p.bandwidth = 0;
808 } else {
809 p.if_name[0] = '\0';
810 p.bandwidth = (int)strtoul(av[0], &end, 0);
811 if (*end == 'K' || *end == 'k') {
812 end++;
813 p.bandwidth *= 1000;
814 } else if (*end == 'M') {
815 end++;
816 p.bandwidth *= 1000000;
817 }
818 if (*end == 'B' || !strncmp(end, "by", 2))
819 p.bandwidth *= 8;
820 if (p.bandwidth < 0)
821 errx(EX_DATAERR, "bandwidth too large");
822 }
823 ac--; av++;
824 break;
825
826 case TOK_DELAY:
827 if (do_pipe != 1)
828 errx(EX_DATAERR, "delay only valid for pipes");
829 NEED2("delay needs argument 0..%d\n", MAX_DELAY);
830 p.delay = (int)strtoul(av[0], NULL, 0);
831 ac--; av++;
832 break;
833
834 case TOK_WEIGHT:
835 if (do_pipe == 1)
836 errx(EX_DATAERR,"weight only valid for queues");
837 NEED1("weight needs argument 0..100\n");
838 p.fs.weight = (int)strtoul(av[0], &end, 0);
839 ac--; av++;
840 break;
841
842 case TOK_PIPE:
843 if (do_pipe == 1)
844 errx(EX_DATAERR,"pipe only valid for queues");
845 NEED1("pipe needs pipe_number\n");
846 p.fs.parent_nr = strtoul(av[0], &end, 0);
847 ac--; av++;
848 break;
849
850 default:
851 errx(EX_DATAERR, "unrecognised option ``%s''", *(--av));
852 }
853 }
854 if (do_pipe == 1) {
855 if (p.pipe_nr == 0)
856 errx(EX_DATAERR, "pipe_nr must be > 0");
857 if (p.delay > MAX_DELAY)
858 errx(EX_DATAERR, "delay must be < %d ms", MAX_DELAY);
859 } else { /* do_pipe == 2, queue */
860 if (p.fs.parent_nr == 0)
861 errx(EX_DATAERR, "pipe must be > 0");
862 if (p.fs.weight >100)
863 errx(EX_DATAERR, "weight must be <= 100");
864 }
865 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
866 if (p.fs.qsize > 1024*1024)
867 errx(EX_DATAERR, "queue size must be < 1MB");
868 } else {
869 if (p.fs.qsize > 100)
870 errx(EX_DATAERR, "2 <= queue size <= 100");
871 }
872 if (p.fs.flags_fs & DN_IS_RED) {
873 size_t len;
874 int lookup_depth, avg_pkt_size;
875 double s, idle, weight, w_q;
876 struct clockinfo ck;
877 int t;
878
879 if (p.fs.min_th >= p.fs.max_th)
880 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
881 p.fs.min_th, p.fs.max_th);
882 if (p.fs.max_th == 0)
883 errx(EX_DATAERR, "max_th must be > 0");
884
885 len = sizeof(int);
886 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
887 &lookup_depth, &len, NULL, 0) == -1)
888
889 errx(1, "sysctlbyname(\"%s\")",
890 "net.inet.ip.dummynet.red_lookup_depth");
891 if (lookup_depth == 0)
892 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
893 " must be greater than zero");
894
895 len = sizeof(int);
896 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
897 &avg_pkt_size, &len, NULL, 0) == -1)
898
899 errx(1, "sysctlbyname(\"%s\")",
900 "net.inet.ip.dummynet.red_avg_pkt_size");
901 if (avg_pkt_size == 0)
902 errx(EX_DATAERR,
903 "net.inet.ip.dummynet.red_avg_pkt_size must"
904 " be greater than zero");
905
906 len = sizeof(struct clockinfo);
907 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
908 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
909
910 /*
911 * Ticks needed for sending a medium-sized packet.
912 * Unfortunately, when we are configuring a WF2Q+ queue, we
913 * do not have bandwidth information, because that is stored
914 * in the parent pipe, and also we have multiple queues
915 * competing for it. So we set s=0, which is not very
916 * correct. But on the other hand, why do we want RED with
917 * WF2Q+ ?
918 */
919 if (p.bandwidth==0) /* this is a WF2Q+ queue */
920 s = 0;
921 else
922 s = ck.hz * avg_pkt_size * 8 / p.bandwidth;
923
924 /*
925 * max idle time (in ticks) before avg queue size becomes 0.
926 * NOTA: (3/w_q) is approx the value x so that
927 * (1-w_q)^x < 10^-3.
928 */
929 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
930 idle = s * 3. / w_q;
931 p.fs.lookup_step = (int)idle / lookup_depth;
932 if (!p.fs.lookup_step)
933 p.fs.lookup_step = 1;
934 weight = 1 - w_q;
935 for (t = p.fs.lookup_step; t > 0; --t)
936 weight *= weight;
937 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
938 }
939 len = sizeof(struct dn_pipe);
940 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, &len);
941 if (i)
942 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
943 }
944
945 static void
946 flush(int force)
947 {
948 if (!force && !do_quiet) { /* need to ask user */
949 int c;
950
951 printf("Are you sure? [yn] ");
952 fflush(stdout);
953 do {
954 c = toupper(getc(stdin));
955 while (c != '\n' && getc(stdin) != '\n')
956 if (feof(stdin))
957 return; /* and do not flush */
958 } while (c != 'Y' && c != 'N');
959 printf("\n");
960 if (c == 'N') /* user said no */
961 return;
962 }
963
964 if (do_cmd(IP_DUMMYNET_FLUSH, NULL, 0) < 0)
965 err(EX_UNAVAILABLE, "setsockopt(IP_DUMMYNET_FLUSH)");
966
967 if (!do_quiet)
968 printf("Flushed all pipes.\n");
969 }
970
971 /*
972 * Free a the (locally allocated) copy of command line arguments.
973 */
974 static void
975 free_args(int ac, char **av)
976 {
977 int i;
978
979 for (i=0; i < ac; i++)
980 free(av[i]);
981 free(av);
982 }
983
984 /*
985 * Called with the arguments (excluding program name).
986 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
987 */
988 static int
989 parse_args(int oldac, char **oldav)
990 {
991 int ch, ac, save_ac;
992 char **av, **save_av;
993 int do_acct = 0; /* Show packet/byte count */
994 int do_force = 0; /* Don't ask for confirmation */
995
996 #define WHITESP " \t\f\v\n\r"
997 if (oldac == 0)
998 return 1;
999 else if (oldac == 1) {
1000 /*
1001 * If we are called with a single string, try to split it into
1002 * arguments for subsequent parsing.
1003 * But first, remove spaces after a ',', by copying the string
1004 * in-place.
1005 */
1006 char *arg = oldav[0]; /* The string... */
1007 size_t l = strlen(arg);
1008 int copy = 0; /* 1 if we need to copy, 0 otherwise */
1009 int i, j;
1010 for (i = j = 0; i < l; i++) {
1011 if (arg[i] == '#') /* comment marker */
1012 break;
1013 if (copy) {
1014 arg[j++] = arg[i];
1015 copy = !index("," WHITESP, arg[i]);
1016 } else {
1017 copy = !index(WHITESP, arg[i]);
1018 if (copy)
1019 arg[j++] = arg[i];
1020 }
1021 }
1022 if (!copy && j > 0) /* last char was a 'blank', remove it */
1023 j--;
1024 l = j; /* the new argument length */
1025 arg[j++] = '\0';
1026 if (l == 0) /* empty string! */
1027 return 1;
1028
1029 /*
1030 * First, count number of arguments. Because of the previous
1031 * processing, this is just the number of blanks plus 1.
1032 */
1033 for (i = 0, ac = 1; i < l; i++)
1034 if (index(WHITESP, arg[i]) != NULL)
1035 ac++;
1036
1037 av = calloc(ac, sizeof(char *));
1038
1039 /*
1040 * Second, copy arguments from cmd[] to av[]. For each one,
1041 * j is the initial character, i is the one past the end.
1042 */
1043 for (ac = 0, i = j = 0; i < l; i++)
1044 if (index(WHITESP, arg[i]) != NULL || i == l-1) {
1045 if (i == l-1)
1046 i++;
1047 av[ac] = calloc(i-j+1, 1);
1048 bcopy(arg+j, av[ac], i-j);
1049 ac++;
1050 j = i + 1;
1051 }
1052 } else {
1053 /*
1054 * If an argument ends with ',' join with the next one.
1055 * Just add its length to 'l' and continue. When we have a string
1056 * without a ',' ending, we'll have the combined length in 'l'
1057 */
1058 int first, i;
1059 size_t l;
1060
1061 av = calloc(oldac, sizeof(char *));
1062 for (first = i = ac = 0, l = 0; i < oldac; i++) {
1063 char *arg = oldav[i];
1064 size_t k = strlen(arg);
1065
1066 l += k;
1067 if (arg[k-1] != ',' || i == oldac-1) {
1068 size_t buflen = l+1;
1069 /* Time to copy. */
1070 av[ac] = calloc(l+1, 1);
1071 for (l=0; first <= i; first++) {
1072 strlcat(av[ac]+l, oldav[first], buflen-l);
1073 l += strlen(oldav[first]);
1074 }
1075 ac++;
1076 l = 0;
1077 first = i+1;
1078 }
1079 }
1080 }
1081
1082 /* Set the force flag for non-interactive processes */
1083 do_force = !isatty(STDIN_FILENO);
1084
1085 /* Save arguments for final freeing of memory. */
1086 save_ac = ac;
1087 save_av = av;
1088
1089 optind = optreset = 0;
1090 while ((ch = getopt(ac, av, "afhnqsv")) != -1)
1091 switch (ch) {
1092 case 'a':
1093 do_acct = 1;
1094 break;
1095
1096 case 'f':
1097 do_force = 1;
1098 break;
1099
1100 case 'h': /* help */
1101 free_args(save_ac, save_av);
1102 help();
1103 break; /* NOTREACHED */
1104
1105 case 'n':
1106 test_only = 1;
1107 break;
1108
1109 case 'q':
1110 do_quiet = 1;
1111 break;
1112
1113 case 's': /* sort */
1114 do_sort = atoi(optarg);
1115 break;
1116
1117 case 'v': /* verbose */
1118 verbose = 1;
1119 break;
1120
1121 default:
1122 free_args(save_ac, save_av);
1123 return 1;
1124 }
1125
1126 ac -= optind;
1127 av += optind;
1128 NEED1("bad arguments, for usage summary ``dnctl''");
1129
1130 /*
1131 * An undocumented behaviour of dnctl1 was to allow rule numbers first,
1132 * e.g. "100 add allow ..." instead of "add 100 allow ...".
1133 * In case, swap first and second argument to get the normal form.
1134 */
1135 if (ac > 1 && isdigit(*av[0])) {
1136 char *p = av[0];
1137
1138 av[0] = av[1];
1139 av[1] = p;
1140 }
1141
1142 /*
1143 * optional: pipe or queue
1144 */
1145 do_pipe = 0;
1146 if (!strncmp(*av, "pipe", strlen(*av)))
1147 do_pipe = 1;
1148 else if (!strncmp(*av, "queue", strlen(*av)))
1149 do_pipe = 2;
1150 if (do_pipe) {
1151 ac--;
1152 av++;
1153 }
1154 NEED1("missing command");
1155
1156 /*
1157 * For pipes and queues we normally say 'pipe NN config'
1158 * but the code is easier to parse as 'pipe config NN'
1159 * so we swap the two arguments.
1160 */
1161 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) {
1162 char *p = av[0];
1163
1164 av[0] = av[1];
1165 av[1] = p;
1166 }
1167
1168 if (do_pipe && !strncmp(*av, "config", strlen(*av)))
1169 config_pipe(ac, av);
1170 else if (!strncmp(*av, "delete", strlen(*av)))
1171 delete(ac, av);
1172 else if (!strncmp(*av, "flush", strlen(*av)))
1173 flush(do_force);
1174 else if (!strncmp(*av, "print", strlen(*av)) ||
1175 !strncmp(*av, "list", strlen(*av)))
1176 list(ac, av, do_acct);
1177 else if (!strncmp(*av, "show", strlen(*av)))
1178 list(ac, av, 1 /* show counters */);
1179 else
1180 errx(EX_USAGE, "bad command `%s'", *av);
1181
1182 /* Free memory allocated in the argument parsing. */
1183 free_args(save_ac, save_av);
1184 return 0;
1185 }
1186
1187 static void
1188 dnctl_readfile(int ac, char *av[])
1189 {
1190 #define MAX_ARGS 32
1191 char buf[BUFSIZ];
1192 char *cmd = NULL, *filename = av[ac-1];
1193 int c, lineno=0;
1194 FILE *f = NULL;
1195 pid_t preproc = 0;
1196
1197 while ((c = getopt(ac, av, "np:q")) != -1) {
1198 switch(c) {
1199 case 'n':
1200 test_only = 1;
1201 break;
1202
1203 case 'p':
1204 cmd = optarg;
1205 /*
1206 * Skip previous args and delete last one, so we
1207 * pass all but the last argument to the preprocessor
1208 * via av[optind-1]
1209 */
1210 av += optind - 1;
1211 ac -= optind - 1;
1212 av[ac-1] = NULL;
1213 fprintf(stderr, "command is %s\n", av[0]);
1214 break;
1215
1216 case 'q':
1217 do_quiet = 1;
1218 break;
1219
1220 default:
1221 errx(EX_USAGE, "bad arguments, for usage"
1222 " summary ``dnctl''");
1223 }
1224
1225 if (cmd != NULL)
1226 break;
1227 }
1228
1229 if (cmd == NULL && ac != optind + 1) {
1230 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
1231 errx(EX_USAGE, "extraneous filename arguments");
1232 }
1233
1234 if ((f = fopen(filename, "r")) == NULL)
1235 err(EX_UNAVAILABLE, "fopen: %s", filename);
1236
1237 if (cmd != NULL) { /* pipe through preprocessor */
1238 int pipedes[2];
1239
1240 if (pipe(pipedes) == -1)
1241 err(EX_OSERR, "cannot create pipe");
1242
1243 preproc = fork();
1244 if (preproc == -1)
1245 err(EX_OSERR, "cannot fork");
1246
1247 if (preproc == 0) {
1248 /*
1249 * Child, will run the preprocessor with the
1250 * file on stdin and the pipe on stdout.
1251 */
1252 if (dup2(fileno(f), 0) == -1
1253 || dup2(pipedes[1], 1) == -1)
1254 err(EX_OSERR, "dup2()");
1255 fclose(f);
1256 close(pipedes[1]);
1257 close(pipedes[0]);
1258 execvp(cmd, av);
1259 err(EX_OSERR, "execvp(%s) failed", cmd);
1260 } else { /* parent, will reopen f as the pipe */
1261 fclose(f);
1262 close(pipedes[1]);
1263 if ((f = fdopen(pipedes[0], "r")) == NULL) {
1264 int savederrno = errno;
1265
1266 (void)kill(preproc, SIGTERM);
1267 errno = savederrno;
1268 err(EX_OSERR, "fdopen()");
1269 }
1270 }
1271 }
1272
1273 while (fgets(buf, BUFSIZ, f)) { /* read commands */
1274 char linename[16];
1275 char *args[1];
1276
1277 lineno++;
1278 snprintf(linename, sizeof(linename), "Line %d", lineno);
1279 setprogname(linename); /* XXX */
1280 args[0] = buf;
1281 parse_args(1, args);
1282 }
1283 fclose(f);
1284 if (cmd != NULL) {
1285 int status;
1286
1287 if (waitpid(preproc, &status, 0) == -1)
1288 errx(EX_OSERR, "waitpid()");
1289 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
1290 errx(EX_UNAVAILABLE,
1291 "preprocessor exited with status %d",
1292 WEXITSTATUS(status));
1293 else if (WIFSIGNALED(status))
1294 errx(EX_UNAVAILABLE,
1295 "preprocessor exited with signal %d",
1296 WTERMSIG(status));
1297 }
1298 }
1299
1300 int
1301 main(int ac, char *av[])
1302 {
1303 /*
1304 * If the last argument is an absolute pathname, interpret it
1305 * as a file to be preprocessed.
1306 */
1307
1308 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
1309 dnctl_readfile(ac, av);
1310 else {
1311 if (parse_args(ac-1, av+1))
1312 show_usage();
1313 }
1314 return EX_OK;
1315 }