1 /* 2 * Copyright (c) 2002 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: src/sbin/ipfw/ipfw2.c,v 1.4.2.13 2003/05/27 22:21:11 gshapiro Exp $ 21 */ 22 23 #include <sys/param.h> 24 #include <sys/mbuf.h> 25 #include <sys/socket.h> 26 #include <sys/sockio.h> 27 #include <sys/sysctl.h> 28 #include <sys/time.h> 29 #include <sys/wait.h> 30 31 #include <ctype.h> 32 #include <err.h> 33 #include <errno.h> 34 #include <grp.h> 35 #include <limits.h> 36 #include <netdb.h> 37 #include <pwd.h> 38 #include <signal.h> 39 #include <stdio.h> 40 #include <stdlib.h> 41 #include <stdarg.h> 42 #include <string.h> 43 #include <timeconv.h> 44 #include <unistd.h> 45 #include <sysexits.h> 46 47 #include <net/if.h> 48 #include <netinet/in.h> 49 #include <netinet/in_systm.h> 50 #include <netinet/ip.h> 51 #include <netinet/ip_icmp.h> 52 #include <net/ipfw/ip_fw.h> 53 #include <net/route.h> /* def. of struct route */ 54 #include <net/ethernet.h> 55 #include <net/dummynet/ip_dummynet.h> 56 #include <netinet/tcp.h> 57 #include <arpa/inet.h> 58 59 int s, /* main RAW socket */ 60 do_resolv, /* Would try to resolve all */ 61 do_acct, /* Show packet/byte count */ 62 do_time, /* Show time stamps */ 63 do_quiet, /* Be quiet in add and flush */ 64 do_force, /* Don't ask for confirmation */ 65 do_pipe, /* this cmd refers to a pipe */ 66 do_table, /* this cmd referes to a table */ 67 do_sort, /* field to sort results (0 = no) */ 68 do_dynamic, /* display dynamic rules */ 69 do_expired, /* display expired dynamic rules */ 70 do_compact, /* show rules in compact mode */ 71 show_sets, /* display rule sets */ 72 verbose; 73 74 #define IP_MASK_ALL 0xffffffff 75 76 /* 77 * structure to hold flag names and associated values to be 78 * set in the appropriate masks. 79 * A NULL string terminates the array. 80 * Often, an element with 0 value contains an error string. 81 * 82 */ 83 struct _s_x { 84 const char *s; 85 uint32_t x; 86 }; 87 88 static struct _s_x f_tcpflags[] = { 89 { "syn", TH_SYN }, 90 { "fin", TH_FIN }, 91 { "ack", TH_ACK }, 92 { "psh", TH_PUSH }, 93 { "rst", TH_RST }, 94 { "urg", TH_URG }, 95 { "tcp flag", 0 }, 96 { NULL, 0 } 97 }; 98 99 static struct _s_x f_tcpopts[] = { 100 { "mss", IP_FW_TCPOPT_MSS }, 101 { "maxseg", IP_FW_TCPOPT_MSS }, 102 { "window", IP_FW_TCPOPT_WINDOW }, 103 { "sack", IP_FW_TCPOPT_SACK }, 104 { "ts", IP_FW_TCPOPT_TS }, 105 { "timestamp", IP_FW_TCPOPT_TS }, 106 { "cc", IP_FW_TCPOPT_CC }, 107 { "tcp option", 0 }, 108 { NULL, 0 } 109 }; 110 111 /* 112 * IP options span the range 0 to 255 so we need to remap them 113 * (though in fact only the low 5 bits are significant). 114 */ 115 static struct _s_x f_ipopts[] = { 116 { "ssrr", IP_FW_IPOPT_SSRR}, 117 { "lsrr", IP_FW_IPOPT_LSRR}, 118 { "rr", IP_FW_IPOPT_RR}, 119 { "ts", IP_FW_IPOPT_TS}, 120 { "ip option", 0 }, 121 { NULL, 0 } 122 }; 123 124 static struct _s_x f_iptos[] = { 125 { "lowdelay", IPTOS_LOWDELAY}, 126 { "throughput", IPTOS_THROUGHPUT}, 127 { "reliability", IPTOS_RELIABILITY}, 128 { "mincost", IPTOS_MINCOST}, 129 { "congestion", IPTOS_CE}, 130 { "ecntransport", IPTOS_ECT}, 131 { "ip tos option", 0}, 132 { NULL, 0 } 133 }; 134 135 static struct _s_x limit_masks[] = { 136 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT}, 137 {"src-addr", DYN_SRC_ADDR}, 138 {"src-port", DYN_SRC_PORT}, 139 {"dst-addr", DYN_DST_ADDR}, 140 {"dst-port", DYN_DST_PORT}, 141 {NULL, 0} 142 }; 143 144 /* 145 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines 146 * This is only used in this code. 147 */ 148 #define IPPROTO_ETHERTYPE 0x1000 149 static struct _s_x ether_types[] = { 150 /* 151 * Note, we cannot use "-:&/" in the names because they are field 152 * separators in the type specifications. Also, we use s = NULL as 153 * end-delimiter, because a type of 0 can be legal. 154 */ 155 { "ip", 0x0800 }, 156 { "ipv4", 0x0800 }, 157 { "ipv6", 0x86dd }, 158 { "arp", 0x0806 }, 159 { "rarp", 0x8035 }, 160 { "vlan", 0x8100 }, 161 { "loop", 0x9000 }, 162 { "trail", 0x1000 }, 163 { "pppoe_disc", 0x8863 }, 164 { "pppoe_sess", 0x8864 }, 165 { "ipx_8022", 0x00E0 }, 166 { "ipx_8023", 0x0000 }, 167 { "ipx_ii", 0x8137 }, 168 { "ipx_snap", 0x8137 }, 169 { "ipx", 0x8137 }, 170 { "ns", 0x0600 }, 171 { NULL, 0 } 172 }; 173 174 static void show_usage(void); 175 176 enum tokens { 177 TOK_NULL=0, 178 179 TOK_OR, 180 TOK_NOT, 181 TOK_STARTBRACE, 182 TOK_ENDBRACE, 183 184 TOK_ACCEPT, 185 TOK_COUNT, 186 TOK_DEFRAG, 187 TOK_PIPE, 188 TOK_QUEUE, 189 TOK_DIVERT, 190 TOK_TEE, 191 TOK_FORWARD, 192 TOK_SKIPTO, 193 TOK_DENY, 194 TOK_REJECT, 195 TOK_RESET, 196 TOK_UNREACH, 197 TOK_CHECKSTATE, 198 199 TOK_UID, 200 TOK_GID, 201 TOK_IN, 202 TOK_LIMIT, 203 TOK_KEEPSTATE, 204 TOK_REDIRECT, 205 TOK_LAYER2, 206 TOK_OUT, 207 TOK_XMIT, 208 TOK_RECV, 209 TOK_VIA, 210 TOK_FRAG, 211 TOK_IPFRAG, 212 TOK_IPOPTS, 213 TOK_IPLEN, 214 TOK_IPID, 215 TOK_IPPRECEDENCE, 216 TOK_IPTOS, 217 TOK_IPTTL, 218 TOK_IPVER, 219 TOK_ESTAB, 220 TOK_SETUP, 221 TOK_TCPFLAGS, 222 TOK_TCPOPTS, 223 TOK_TCPSEQ, 224 TOK_TCPACK, 225 TOK_TCPWIN, 226 TOK_ICMPCODES, 227 TOK_ICMPTYPES, 228 TOK_MAC, 229 TOK_MACTYPE, 230 231 TOK_PLR, 232 TOK_NOERROR, 233 TOK_BUCKETS, 234 TOK_DSTIP, 235 TOK_SRCIP, 236 TOK_DSTPORT, 237 TOK_SRCPORT, 238 TOK_ALL, 239 TOK_MASK, 240 TOK_BW, 241 TOK_DELAY, 242 TOK_RED, 243 TOK_GRED, 244 TOK_DROPTAIL, 245 TOK_PROTO, 246 TOK_WEIGHT, 247 }; 248 249 struct _s_x dummynet_params[] = { 250 { "plr", TOK_PLR }, 251 { "noerror", TOK_NOERROR }, 252 { "buckets", TOK_BUCKETS }, 253 { "dst-ip", TOK_DSTIP }, 254 { "src-ip", TOK_SRCIP }, 255 { "dst-port", TOK_DSTPORT }, 256 { "src-port", TOK_SRCPORT }, 257 { "proto", TOK_PROTO }, 258 { "weight", TOK_WEIGHT }, 259 { "all", TOK_ALL }, 260 { "mask", TOK_MASK }, 261 { "droptail", TOK_DROPTAIL }, 262 { "red", TOK_RED }, 263 { "gred", TOK_GRED }, 264 { "bw", TOK_BW }, 265 { "bandwidth", TOK_BW }, 266 { "delay", TOK_DELAY }, 267 { "pipe", TOK_PIPE }, 268 { "queue", TOK_QUEUE }, 269 { "dummynet-params", TOK_NULL }, 270 { NULL, 0 } 271 }; 272 273 struct _s_x rule_actions[] = { 274 { "accept", TOK_ACCEPT }, 275 { "pass", TOK_ACCEPT }, 276 { "allow", TOK_ACCEPT }, 277 { "permit", TOK_ACCEPT }, 278 { "count", TOK_COUNT }, 279 { "pipe", TOK_PIPE }, 280 { "queue", TOK_QUEUE }, 281 { "divert", TOK_DIVERT }, 282 { "tee", TOK_TEE }, 283 { "fwd", TOK_FORWARD }, 284 { "forward", TOK_FORWARD }, 285 { "skipto", TOK_SKIPTO }, 286 { "deny", TOK_DENY }, 287 { "drop", TOK_DENY }, 288 { "reject", TOK_REJECT }, 289 { "reset", TOK_RESET }, 290 { "unreach", TOK_UNREACH }, 291 { "check-state", TOK_CHECKSTATE }, 292 { "defrag", TOK_DEFRAG }, 293 { NULL, TOK_NULL }, 294 { NULL, 0 } 295 }; 296 297 struct _s_x rule_options[] = { 298 { "uid", TOK_UID }, 299 { "gid", TOK_GID }, 300 { "in", TOK_IN }, 301 { "limit", TOK_LIMIT }, 302 { "keep-state", TOK_KEEPSTATE }, 303 { "redirect", TOK_REDIRECT }, 304 { "rdr", TOK_REDIRECT }, 305 { "layer2", TOK_LAYER2 }, 306 { "out", TOK_OUT }, 307 { "xmit", TOK_XMIT }, 308 { "recv", TOK_RECV }, 309 { "via", TOK_VIA }, 310 { "fragment", TOK_FRAG }, 311 { "frag", TOK_FRAG }, 312 { "ipfrag", TOK_IPFRAG }, 313 { "ipoptions", TOK_IPOPTS }, 314 { "ipopts", TOK_IPOPTS }, 315 { "iplen", TOK_IPLEN }, 316 { "ipid", TOK_IPID }, 317 { "ipprecedence", TOK_IPPRECEDENCE }, 318 { "iptos", TOK_IPTOS }, 319 { "ipttl", TOK_IPTTL }, 320 { "ipversion", TOK_IPVER }, 321 { "ipver", TOK_IPVER }, 322 { "estab", TOK_ESTAB }, 323 { "established", TOK_ESTAB }, 324 { "setup", TOK_SETUP }, 325 { "tcpflags", TOK_TCPFLAGS }, 326 { "tcpflgs", TOK_TCPFLAGS }, 327 { "tcpoptions", TOK_TCPOPTS }, 328 { "tcpopts", TOK_TCPOPTS }, 329 { "tcpseq", TOK_TCPSEQ }, 330 { "tcpack", TOK_TCPACK }, 331 { "tcpwin", TOK_TCPWIN }, 332 { "icmpcode", TOK_ICMPCODES }, 333 { "icmpcodes", TOK_ICMPCODES }, 334 { "icmptype", TOK_ICMPTYPES }, 335 { "icmptypes", TOK_ICMPTYPES }, 336 { "dst-ip", TOK_DSTIP }, 337 { "src-ip", TOK_SRCIP }, 338 { "dst-port", TOK_DSTPORT }, 339 { "src-port", TOK_SRCPORT }, 340 { "proto", TOK_PROTO }, 341 { "MAC", TOK_MAC }, 342 { "mac", TOK_MAC }, 343 { "mac-type", TOK_MACTYPE }, 344 345 { "not", TOK_NOT }, /* pseudo option */ 346 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */ 347 { "or", TOK_OR }, /* pseudo option */ 348 { "|", /* escape */ TOK_OR }, /* pseudo option */ 349 { "{", TOK_STARTBRACE }, /* pseudo option */ 350 { "(", TOK_STARTBRACE }, /* pseudo option */ 351 { "}", TOK_ENDBRACE }, /* pseudo option */ 352 { ")", TOK_ENDBRACE }, /* pseudo option */ 353 { NULL, TOK_NULL }, 354 { NULL, 0 } 355 }; 356 357 /** 358 * match_token takes a table and a string, returns the value associated 359 * with the string (0 meaning an error in most cases) 360 */ 361 static int 362 match_token(struct _s_x *table, char *string) 363 { 364 struct _s_x *pt; 365 int i = strlen(string); 366 367 for (pt = table ; i && pt->s != NULL ; pt++) 368 if ((int)strlen(pt->s) == i && !bcmp(string, pt->s, i)) 369 return pt->x; 370 return -1; 371 }; 372 373 static const char * 374 match_value(struct _s_x *p, u_int32_t value) 375 { 376 for (; p->s != NULL; p++) 377 if (p->x == value) 378 return p->s; 379 return NULL; 380 } 381 382 /* 383 * prints one port, symbolic or numeric 384 */ 385 static void 386 print_port(int proto, u_int16_t port) 387 { 388 389 if (proto == IPPROTO_ETHERTYPE) { 390 const char *str; 391 392 if (do_resolv && (str = match_value(ether_types, port)) ) 393 printf("%s", str); 394 else 395 printf("0x%04x", port); 396 } else { 397 struct servent *se = NULL; 398 if (do_resolv) { 399 struct protoent *pe = getprotobynumber(proto); 400 401 se = getservbyport(htons(port), pe ? pe->p_name : NULL); 402 } 403 if (se) 404 printf("%s", se->s_name); 405 else 406 printf("%d", port); 407 } 408 } 409 410 /* 411 * print the values in a list of ports 412 * XXX todo: add support for mask. 413 */ 414 static void 415 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode) 416 { 417 u_int16_t *p = cmd->ports; 418 int i; 419 const char *sep= " "; 420 421 if (cmd->o.len & F_NOT) 422 printf(" not"); 423 if (opcode != 0) 424 printf ("%s", opcode == O_MAC_TYPE ? " mac-type" : 425 (opcode == O_IP_DSTPORT ? " dst-port" : " src-port")); 426 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) { 427 printf("%s", sep); 428 print_port(proto, p[0]); 429 if (p[0] != p[1]) { 430 printf("-"); 431 print_port(proto, p[1]); 432 } 433 sep = ","; 434 } 435 } 436 437 /* 438 * Like strtol, but also translates service names into port numbers 439 * for some protocols. 440 * In particular: 441 * proto == -1 disables the protocol check; 442 * proto == IPPROTO_ETHERTYPE looks up an internal table 443 * proto == <some value in /etc/protocols> matches the values there. 444 * Returns *end == s in case the parameter is not found. 445 */ 446 static int 447 strtoport(char *str, char **end, int base, int proto) 448 { 449 char *p, *buf; 450 char *s1; 451 int i; 452 453 *end = str; /* default - not found */ 454 if (*str == '\0') 455 return 0; /* not found */ 456 457 if (isdigit(*str)) 458 return strtol(str, end, base); 459 460 /* 461 * find separator. '\\' escapes the next char. 462 */ 463 for (s1 = str; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) 464 if (*s1 == '\\' && s1[1] != '\0') 465 s1++; 466 467 buf = malloc(s1 - str + 1); 468 if (buf == NULL) 469 return 0; 470 471 /* 472 * copy into a buffer skipping backslashes 473 */ 474 for (p = str, i = 0; p != s1 ; p++) 475 if ( *p != '\\') 476 buf[i++] = *p; 477 buf[i++] = '\0'; 478 479 if (proto == IPPROTO_ETHERTYPE) { 480 i = match_token(ether_types, buf); 481 free(buf); 482 if (i != -1) { /* found */ 483 *end = s1; 484 return i; 485 } 486 } else { 487 struct protoent *pe = NULL; 488 struct servent *se; 489 490 if (proto != 0) 491 pe = getprotobynumber(proto); 492 setservent(1); 493 se = getservbyname(buf, pe ? pe->p_name : NULL); 494 free(buf); 495 if (se != NULL) { 496 *end = s1; 497 return ntohs(se->s_port); 498 } 499 } 500 return 0; /* not found */ 501 } 502 503 /* 504 * fill the body of the command with the list of port ranges. 505 * At the moment it only understands numeric ranges. 506 */ 507 static int 508 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto) 509 { 510 u_int16_t *p = cmd->ports; 511 int i = 0; 512 char *str = av; 513 514 while (*str) { 515 u_int16_t a, b; 516 517 a = strtoport(av, &str, 0, proto); 518 if (str == av) /* no parameter */ 519 break; 520 if (*str == '-') { /* a range */ 521 av = str+1; 522 b = strtoport(av, &str, 0, proto); 523 if (str == av) /* no parameter */ 524 break; 525 p[0] = a; 526 p[1] = b; 527 } else if (*str == ',' || *str == '\0' ) { 528 p[0] = p[1] = a; 529 } else { /* invalid separator */ 530 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n", 531 *str, av); 532 } 533 i++; 534 p += 2; 535 av = str+1; 536 } 537 if (i > 0) { 538 if (i+1 > F_LEN_MASK) 539 errx(EX_DATAERR, "too many ports/ranges\n"); 540 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */ 541 } 542 return i; 543 } 544 545 static struct _s_x icmpcodes[] = { 546 { "net", ICMP_UNREACH_NET }, 547 { "host", ICMP_UNREACH_HOST }, 548 { "protocol", ICMP_UNREACH_PROTOCOL }, 549 { "port", ICMP_UNREACH_PORT }, 550 { "needfrag", ICMP_UNREACH_NEEDFRAG }, 551 { "srcfail", ICMP_UNREACH_SRCFAIL }, 552 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN }, 553 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN }, 554 { "isolated", ICMP_UNREACH_ISOLATED }, 555 { "net-prohib", ICMP_UNREACH_NET_PROHIB }, 556 { "host-prohib", ICMP_UNREACH_HOST_PROHIB }, 557 { "tosnet", ICMP_UNREACH_TOSNET }, 558 { "toshost", ICMP_UNREACH_TOSHOST }, 559 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB }, 560 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE }, 561 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF }, 562 { NULL, 0 } 563 }; 564 565 static void 566 fill_reject_code(u_short *codep, char *str) 567 { 568 int val; 569 char *s1; 570 571 val = strtoul(str, &s1, 0); 572 if (s1 == str || *s1 != '\0' || val >= 0x100) 573 val = match_token(icmpcodes, str); 574 if (val < 0) 575 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str); 576 *codep = val; 577 return; 578 } 579 580 static void 581 print_reject_code(u_int16_t code) 582 { 583 const char *str = match_value(icmpcodes, code); 584 585 if (str != NULL) 586 printf("unreach %s", str); 587 else 588 printf("unreach %u", code); 589 } 590 591 /* 592 * Returns the number of bits set (from left) in a contiguous bitmask, 593 * or -1 if the mask is not contiguous. 594 * XXX this needs a proper fix. 595 * This effectively works on masks in big-endian (network) format. 596 * when compiled on little endian architectures. 597 * 598 * First bit is bit 7 of the first byte -- note, for MAC addresses, 599 * the first bit on the wire is bit 0 of the first byte. 600 * len is the max length in bits. 601 */ 602 static int 603 contigmask(u_char *p, int len) 604 { 605 int i, n; 606 for (i=0; i<len ; i++) 607 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */ 608 break; 609 for (n=i+1; n < len; n++) 610 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0) 611 return -1; /* mask not contiguous */ 612 return i; 613 } 614 615 /* 616 * print flags set/clear in the two bitmasks passed as parameters. 617 * There is a specialized check for f_tcpflags. 618 */ 619 static void 620 print_flags(const char *name, ipfw_insn *cmd, struct _s_x *list) 621 { 622 const char *comma=""; 623 int i; 624 u_char set = cmd->arg1 & 0xff; 625 u_char clear = (cmd->arg1 >> 8) & 0xff; 626 627 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) { 628 printf(" setup"); 629 return; 630 } 631 632 printf(" %s ", name); 633 for (i=0; list[i].x != 0; i++) { 634 if (set & list[i].x) { 635 set &= ~list[i].x; 636 printf("%s%s", comma, list[i].s); 637 comma = ","; 638 } 639 if (clear & list[i].x) { 640 clear &= ~list[i].x; 641 printf("%s!%s", comma, list[i].s); 642 comma = ","; 643 } 644 } 645 } 646 647 /* 648 * Print the ip address contained in a command. 649 */ 650 static void 651 print_ip(ipfw_insn_ip *cmd, const char *str) 652 { 653 struct hostent *he = NULL; 654 int mb; 655 656 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", str); 657 658 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) { 659 printf("me"); 660 return; 661 } 662 if (cmd->o.opcode == O_IP_SRC_TABLE || 663 cmd->o.opcode == O_IP_DST_TABLE) { 664 printf("<%u>", cmd->o.arg1); 665 return; 666 } 667 if (cmd->o.opcode == O_IP_SRC_IFIP || 668 cmd->o.opcode == O_IP_DST_IFIP) { 669 printf("[%s%s]", ((ipfw_insn_ifip *)cmd)->ifname, 670 (cmd->o.arg1 & IPFW_IFIP_NET) ? ":net" : ""); 671 return; 672 } 673 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) { 674 u_int32_t x, *d; 675 int i; 676 char comma = '{'; 677 678 x = cmd->o.arg1 - 1; 679 x = htonl( ~x ); 680 cmd->addr.s_addr = htonl(cmd->addr.s_addr); 681 printf("%s/%d", inet_ntoa(cmd->addr), 682 contigmask((u_char *)&x, 32)); 683 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr); 684 x &= 0xff; /* base */ 685 d = (u_int32_t *)&(cmd->mask); 686 for (i=0; i < cmd->o.arg1; i++) 687 if (d[ i/32] & (1<<(i & 31))) { 688 printf("%c%d", comma, i+x); 689 comma = ','; 690 } 691 printf("}"); 692 return; 693 } 694 if (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) 695 mb = 32; 696 else 697 mb = contigmask((u_char *)&(cmd->mask.s_addr), 32); 698 if (mb == 32 && do_resolv) 699 he = gethostbyaddr(&(cmd->addr.s_addr), sizeof(u_long), 700 AF_INET); 701 if (he != NULL) /* resolved to name */ 702 printf("%s", he->h_name); 703 else if (mb == 0) /* any */ 704 printf("any"); 705 else { /* numeric IP followed by some kind of mask */ 706 printf("%s", inet_ntoa(cmd->addr)); 707 if (mb < 0) 708 printf(":%s", inet_ntoa(cmd->mask)); 709 else if (mb < 32) 710 printf("/%d", mb); 711 } 712 } 713 714 /* 715 * prints a MAC address/mask pair 716 */ 717 static void 718 print_mac(u_char *addr, u_char *mask) 719 { 720 int l = contigmask(mask, 48); 721 722 if (l == 0) 723 printf(" any"); 724 else { 725 printf(" %02x:%02x:%02x:%02x:%02x:%02x", 726 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 727 if (l == -1) 728 printf("&%02x:%02x:%02x:%02x:%02x:%02x", 729 mask[0], mask[1], mask[2], 730 mask[3], mask[4], mask[5]); 731 else if (l < 48) 732 printf("/%d", l); 733 } 734 } 735 736 static void 737 fill_icmp(enum ipfw_opcodes op, ipfw_insn_u32 *cmd, char *av) 738 { 739 u_int8_t type; 740 int idx_max = 0, idx; 741 742 /* 256 / 32, (max icmp types / 32 bits). */ 743 for (idx = 0; idx < 8; ++idx) 744 cmd->d[idx] = 0; 745 746 while (*av) { 747 if (*av == ',') 748 av++; 749 750 type = strtoul(av, &av, 0); 751 if (*av != ',' && *av != '\0') { 752 errx(EX_DATAERR, "invalid ICMP %s", 753 op == O_ICMPTYPE ? "types" : "codes"); 754 } 755 756 idx = type / 32; 757 cmd->d[idx] |= 1 << (type % 32); 758 759 if (idx > idx_max) 760 idx_max = idx; 761 } 762 cmd->o.opcode = op; 763 cmd->o.len |= (F_INSN_SIZE(ipfw_insn_u32) + idx_max); 764 } 765 766 static void 767 print_icmp(ipfw_insn_u32 *cmd) 768 { 769 int idx, idx_max; 770 char sep= ' '; 771 772 idx_max = F_LEN(&cmd->o) - F_INSN_SIZE(ipfw_insn); 773 774 if (cmd->o.opcode == O_ICMPTYPE) 775 printf(" icmptypes"); 776 else 777 printf(" icmpcodes"); 778 for (idx = 0; idx < idx_max; ++idx) { 779 uint32_t types = cmd->d[idx]; 780 781 while (types != 0) { 782 int type_shift = ffs(types) - 1; 783 784 types &= ~(1 << type_shift); 785 printf("%c%d", sep, (idx * 32) + type_shift); 786 sep = ','; 787 } 788 } 789 } 790 791 /* 792 * show_ipfw() prints the body of an ipfw rule. 793 * Because the standard rule has at least proto src_ip dst_ip, we use 794 * a helper function to produce these entries if not provided explicitly. 795 * The first argument is the list of fields we have, the second is 796 * the list of fields we want to be printed. 797 * 798 * Special cases if we have provided a MAC header: 799 * + if the rule does not contain IP addresses/ports, do not print them; 800 * + if the rule does not contain an IP proto, print "all" instead of "ip"; 801 * 802 * Once we have 'have_options', IP header fields are printed as options. 803 */ 804 #define HAVE_PROTO 0x0001 805 #define HAVE_SRCIP 0x0002 806 #define HAVE_DSTIP 0x0004 807 #define HAVE_MAC 0x0008 808 #define HAVE_MACTYPE 0x0010 809 #define HAVE_OPTIONS 0x8000 810 811 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP) 812 static void 813 show_prerequisites(int *flags, int want, int cmd) 814 { 815 if ( (*flags & HAVE_IP) == HAVE_IP) 816 *flags |= HAVE_OPTIONS; 817 818 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC && 819 cmd != O_MAC_TYPE) { 820 /* 821 * mac-type was optimized out by the compiler, 822 * restore it 823 */ 824 printf(" any"); 825 *flags |= HAVE_MACTYPE | HAVE_OPTIONS; 826 return; 827 } 828 if ( !(*flags & HAVE_OPTIONS)) { 829 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) 830 printf(" ip"); 831 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP)) 832 printf(" from any"); 833 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP)) 834 printf(" to any"); 835 } 836 *flags |= want; 837 } 838 839 static void 840 show_ipfw(struct ipfw_ioc_rule *rule, int pcwidth, int bcwidth) 841 { 842 static int twidth = 0; 843 int l; 844 ipfw_insn *cmd; 845 int proto = 0; /* default */ 846 int flags = 0; /* prerequisites */ 847 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */ 848 int or_block = 0; /* we are in an or block */ 849 850 u_int32_t set_disable = rule->set_disable; 851 852 if (set_disable & (1 << rule->set)) { /* disabled */ 853 if (!show_sets) 854 return; 855 else 856 printf("# DISABLED "); 857 } 858 printf("%05u ", rule->rulenum); 859 860 if (do_acct) 861 printf("%*ju %*ju ", pcwidth, (uintmax_t)rule->pcnt, bcwidth, 862 (uintmax_t)rule->bcnt); 863 864 if (do_time) { 865 char timestr[30]; 866 867 if (twidth == 0) { 868 time_t t0 = 0; 869 870 strcpy(timestr, ctime((time_t *)&t0)); 871 *strchr(timestr, '\n') = '\0'; 872 twidth = strlen(timestr); 873 } 874 if (rule->timestamp) { 875 time_t t = _long_to_time(rule->timestamp); 876 877 strcpy(timestr, ctime(&t)); 878 *strchr(timestr, '\n') = '\0'; 879 printf("%s ", timestr); 880 } else { 881 printf("%*s ", twidth, " "); 882 } 883 } 884 885 if (show_sets) 886 printf("set %d ", rule->set); 887 888 /* 889 * print the optional "match probability" 890 */ 891 if (rule->cmd_len > 0) { 892 cmd = rule->cmd ; 893 if (cmd->opcode == O_PROB) { 894 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd; 895 double d = 1.0 * p->d[0]; 896 897 d = (d / 0x7fffffff); 898 printf("prob %f ", d); 899 } 900 } 901 902 /* 903 * first print actions 904 */ 905 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule); 906 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) { 907 switch(cmd->opcode) { 908 case O_CHECK_STATE: 909 printf("check-state"); 910 flags = HAVE_IP; /* avoid printing anything else */ 911 break; 912 913 case O_ACCEPT: 914 printf("allow"); 915 break; 916 917 case O_COUNT: 918 printf("count"); 919 break; 920 921 case O_DEFRAG: 922 printf("defrag"); 923 break; 924 925 case O_DENY: 926 printf("deny"); 927 break; 928 929 case O_REJECT: 930 if (cmd->arg1 == ICMP_REJECT_RST) 931 printf("reset"); 932 else if (cmd->arg1 == ICMP_UNREACH_HOST) 933 printf("reject"); 934 else 935 print_reject_code(cmd->arg1); 936 break; 937 938 case O_SKIPTO: 939 printf("skipto %u", cmd->arg1); 940 break; 941 942 case O_PIPE: 943 printf("pipe %u", cmd->arg1); 944 break; 945 946 case O_QUEUE: 947 printf("queue %u", cmd->arg1); 948 break; 949 950 case O_DIVERT: 951 printf("divert %u", cmd->arg1); 952 break; 953 954 case O_TEE: 955 printf("tee %u", cmd->arg1); 956 break; 957 958 case O_FORWARD_IP: 959 { 960 ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd; 961 962 printf("fwd %s", inet_ntoa(sa->sa.sin_addr)); 963 if (sa->sa.sin_port) 964 printf(",%d", sa->sa.sin_port); 965 } 966 break; 967 968 case O_LOG: /* O_LOG is printed last */ 969 logptr = (ipfw_insn_log *)cmd; 970 break; 971 972 default: 973 printf("** unrecognized action %d len %d", 974 cmd->opcode, cmd->len); 975 } 976 } 977 if (logptr) { 978 if (logptr->max_log > 0) 979 printf(" log logamount %d", logptr->max_log); 980 else 981 printf(" log"); 982 } 983 984 /* 985 * then print the body. 986 */ 987 if (rule->usr_flags & IPFW_USR_F_NORULE) { 988 /* empty rules before options */ 989 if (!do_compact) 990 printf(" ip from any to any"); 991 flags |= HAVE_IP | HAVE_OPTIONS; 992 } 993 994 for (l = rule->act_ofs, cmd = rule->cmd ; 995 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 996 /* useful alias */ 997 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; 998 999 show_prerequisites(&flags, 0, cmd->opcode); 1000 1001 switch(cmd->opcode) { 1002 case O_PROB: 1003 break; /* done already */ 1004 1005 case O_PROBE_STATE: 1006 break; /* no need to print anything here */ 1007 1008 case O_MACADDR2: { 1009 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd; 1010 1011 if ((cmd->len & F_OR) && !or_block) 1012 printf(" {"); 1013 if (cmd->len & F_NOT) 1014 printf(" not"); 1015 printf(" MAC"); 1016 flags |= HAVE_MAC; 1017 print_mac( m->addr, m->mask); 1018 print_mac( m->addr + 6, m->mask + 6); 1019 } 1020 break; 1021 1022 case O_MAC_TYPE: 1023 if ((cmd->len & F_OR) && !or_block) 1024 printf(" {"); 1025 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE, 1026 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1027 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS; 1028 break; 1029 1030 case O_IP_SRC: 1031 case O_IP_SRC_MASK: 1032 case O_IP_SRC_ME: 1033 case O_IP_SRC_SET: 1034 case O_IP_SRC_TABLE: 1035 case O_IP_SRC_IFIP: 1036 show_prerequisites(&flags, HAVE_PROTO, 0); 1037 if (!(flags & HAVE_SRCIP)) 1038 printf(" from"); 1039 if ((cmd->len & F_OR) && !or_block) 1040 printf(" {"); 1041 print_ip((ipfw_insn_ip *)cmd, 1042 (flags & HAVE_OPTIONS) ? " src-ip" : ""); 1043 flags |= HAVE_SRCIP; 1044 break; 1045 1046 case O_IP_DST: 1047 case O_IP_DST_MASK: 1048 case O_IP_DST_ME: 1049 case O_IP_DST_SET: 1050 case O_IP_DST_TABLE: 1051 case O_IP_DST_IFIP: 1052 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1053 if (!(flags & HAVE_DSTIP)) 1054 printf(" to"); 1055 if ((cmd->len & F_OR) && !or_block) 1056 printf(" {"); 1057 print_ip((ipfw_insn_ip *)cmd, 1058 (flags & HAVE_OPTIONS) ? " dst-ip" : ""); 1059 flags |= HAVE_DSTIP; 1060 break; 1061 1062 case O_IP_DSTPORT: 1063 show_prerequisites(&flags, HAVE_IP, 0); 1064 case O_IP_SRCPORT: 1065 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1066 if ((cmd->len & F_OR) && !or_block) 1067 printf(" {"); 1068 print_newports((ipfw_insn_u16 *)cmd, proto, 1069 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1070 break; 1071 1072 case O_PROTO: { 1073 struct protoent *pe; 1074 1075 if ((cmd->len & F_OR) && !or_block) 1076 printf(" {"); 1077 if (cmd->len & F_NOT) 1078 printf(" not"); 1079 proto = cmd->arg1; 1080 pe = getprotobynumber(cmd->arg1); 1081 if (flags & HAVE_OPTIONS) 1082 printf(" proto"); 1083 if (pe) 1084 printf(" %s", pe->p_name); 1085 else 1086 printf(" %u", cmd->arg1); 1087 } 1088 flags |= HAVE_PROTO; 1089 break; 1090 1091 default: /*options ... */ 1092 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0); 1093 if ((cmd->len & F_OR) && !or_block) 1094 printf(" {"); 1095 if (cmd->len & F_NOT && cmd->opcode != O_IN) 1096 printf(" not"); 1097 switch(cmd->opcode) { 1098 case O_FRAG: 1099 printf(" frag"); 1100 break; 1101 1102 case O_IPFRAG: 1103 printf(" ipfrag"); 1104 break; 1105 1106 case O_IN: 1107 printf(cmd->len & F_NOT ? " out" : " in"); 1108 break; 1109 1110 case O_LAYER2: 1111 printf(" layer2"); 1112 break; 1113 case O_XMIT: 1114 case O_RECV: 1115 case O_VIA: { 1116 const char *dir; 1117 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd; 1118 1119 if (cmd->opcode == O_XMIT) 1120 dir = "xmit"; 1121 else if (cmd->opcode == O_RECV) 1122 dir = "recv"; 1123 else if (cmd->opcode == O_VIA) 1124 dir = "via"; 1125 else 1126 dir = "?huh?"; 1127 if (cmdif->name[0] == '\0') 1128 printf(" %s %s", dir, 1129 inet_ntoa(cmdif->p.ip)); 1130 printf(" %s %s", dir, cmdif->name); 1131 } 1132 break; 1133 1134 case O_IPID: 1135 printf(" ipid %u", cmd->arg1 ); 1136 break; 1137 1138 case O_IPTTL: 1139 printf(" ipttl %u", cmd->arg1 ); 1140 break; 1141 1142 case O_IPVER: 1143 printf(" ipver %u", cmd->arg1 ); 1144 break; 1145 1146 case O_IPPRECEDENCE: 1147 printf(" ipprecedence %u", (cmd->arg1) >> 5 ); 1148 break; 1149 1150 case O_IPLEN: 1151 printf(" iplen %u", cmd->arg1 ); 1152 break; 1153 1154 case O_IPOPT: 1155 print_flags("ipoptions", cmd, f_ipopts); 1156 break; 1157 1158 case O_IPTOS: 1159 print_flags("iptos", cmd, f_iptos); 1160 break; 1161 1162 case O_ICMPCODE: 1163 case O_ICMPTYPE: 1164 print_icmp((ipfw_insn_u32 *)cmd); 1165 break; 1166 1167 case O_ESTAB: 1168 printf(" established"); 1169 break; 1170 1171 case O_TCPFLAGS: 1172 print_flags("tcpflags", cmd, f_tcpflags); 1173 break; 1174 1175 case O_TCPOPTS: 1176 print_flags("tcpoptions", cmd, f_tcpopts); 1177 break; 1178 1179 case O_TCPWIN: 1180 printf(" tcpwin %d", ntohs(cmd->arg1)); 1181 break; 1182 1183 case O_TCPACK: 1184 printf(" tcpack %u", ntohl(cmd32->d[0])); 1185 break; 1186 1187 case O_TCPSEQ: 1188 printf(" tcpseq %u", ntohl(cmd32->d[0])); 1189 break; 1190 1191 case O_UID: 1192 { 1193 struct passwd *pwd = getpwuid(cmd32->d[0]); 1194 1195 if (pwd) 1196 printf(" uid %s", pwd->pw_name); 1197 else 1198 printf(" uid %u", cmd32->d[0]); 1199 } 1200 break; 1201 1202 case O_GID: 1203 { 1204 struct group *grp = getgrgid(cmd32->d[0]); 1205 1206 if (grp) 1207 printf(" gid %s", grp->gr_name); 1208 else 1209 printf(" gid %u", cmd32->d[0]); 1210 } 1211 break; 1212 1213 case O_KEEP_STATE: 1214 printf(" keep-state"); 1215 break; 1216 1217 case O_REDIRECT: 1218 { 1219 ipfw_insn_rdr *c = (ipfw_insn_rdr *)cmd; 1220 1221 printf(" rdr %s", inet_ntoa(c->addr)); 1222 if (c->port != 0) 1223 printf(",%u", ntohs(c->port)); 1224 break; 1225 } 1226 1227 case O_LIMIT: 1228 { 1229 struct _s_x *p = limit_masks; 1230 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 1231 u_int8_t x = c->limit_mask; 1232 const char *comma = " "; 1233 1234 printf(" limit"); 1235 for ( ; p->x != 0 ; p++) 1236 if ((x & p->x) == p->x) { 1237 x &= ~p->x; 1238 printf("%s%s", comma, p->s); 1239 comma = ","; 1240 } 1241 printf(" %d", c->conn_limit); 1242 } 1243 break; 1244 1245 default: 1246 printf(" [opcode %d len %d]", 1247 cmd->opcode, cmd->len); 1248 } 1249 } 1250 if (cmd->len & F_OR) { 1251 printf(" or"); 1252 or_block = 1; 1253 } else if (or_block) { 1254 printf(" }"); 1255 or_block = 0; 1256 } 1257 } 1258 show_prerequisites(&flags, HAVE_IP, 0); 1259 1260 printf("\n"); 1261 } 1262 1263 static void 1264 show_dyn_ipfw(struct ipfw_ioc_state *d, int pcwidth, int bcwidth) 1265 { 1266 struct protoent *pe; 1267 struct in_addr a; 1268 1269 if (!do_expired) { 1270 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT)) 1271 return; 1272 } 1273 1274 printf("%05u %*ju %*ju (%ds)", d->rulenum, pcwidth, (uintmax_t)d->pcnt, 1275 bcwidth, (uintmax_t)d->bcnt, d->expire); 1276 switch (d->dyn_type) { 1277 case O_LIMIT_PARENT: 1278 printf(" PARENT %d", d->count); 1279 break; 1280 case O_LIMIT: 1281 printf(" LIMIT"); 1282 break; 1283 case O_KEEP_STATE: /* bidir, no mask */ 1284 printf(" STATE"); 1285 break; 1286 case O_REDIRECT: 1287 printf(" REDIRECT"); 1288 break; 1289 } 1290 1291 if ((pe = getprotobynumber(d->id.u.ip.proto)) != NULL) 1292 printf(" %s", pe->p_name); 1293 else 1294 printf(" proto %u", d->id.u.ip.proto); 1295 1296 a.s_addr = htonl(d->id.u.ip.src_ip); 1297 printf(" %s %d", inet_ntoa(a), d->id.u.ip.src_port); 1298 1299 a.s_addr = htonl(d->id.u.ip.dst_ip); 1300 printf(" <-> %s %d", inet_ntoa(a), d->id.u.ip.dst_port); 1301 1302 if (d->dyn_type == O_REDIRECT) { 1303 struct in_addr xlat_addr; 1304 1305 xlat_addr.s_addr = htonl(d->xlat_addr); 1306 printf(" => %s %d", inet_ntoa(xlat_addr), d->xlat_port); 1307 } 1308 printf("\n"); 1309 } 1310 1311 static int 1312 sort_q(const void *pa, const void *pb) 1313 { 1314 int rev = (do_sort < 0); 1315 int field = rev ? -do_sort : do_sort; 1316 long long res = 0; 1317 const struct dn_ioc_flowqueue *a = pa; 1318 const struct dn_ioc_flowqueue *b = pb; 1319 1320 switch (field) { 1321 case 1: /* pkts */ 1322 res = a->len - b->len; 1323 break; 1324 case 2: /* bytes */ 1325 res = a->len_bytes - b->len_bytes; 1326 break; 1327 1328 case 3: /* tot pkts */ 1329 res = a->tot_pkts - b->tot_pkts; 1330 break; 1331 1332 case 4: /* tot bytes */ 1333 res = a->tot_bytes - b->tot_bytes; 1334 break; 1335 } 1336 if (res < 0) 1337 res = -1; 1338 if (res > 0) 1339 res = 1; 1340 return (int)(rev ? res : -res); 1341 } 1342 1343 static void 1344 list_queues(struct dn_ioc_flowset *fs, struct dn_ioc_flowqueue *q) 1345 { 1346 int l; 1347 1348 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n", 1349 fs->flow_mask.u.ip.proto, 1350 fs->flow_mask.u.ip.src_ip, fs->flow_mask.u.ip.src_port, 1351 fs->flow_mask.u.ip.dst_ip, fs->flow_mask.u.ip.dst_port); 1352 if (fs->rq_elements == 0) 1353 return; 1354 1355 printf("BKT Prot ___Source IP/port____ " 1356 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n"); 1357 if (do_sort != 0) 1358 heapsort(q, fs->rq_elements, sizeof(*q), sort_q); 1359 for (l = 0; l < fs->rq_elements; l++) { 1360 struct in_addr ina; 1361 struct protoent *pe; 1362 1363 ina.s_addr = htonl(q[l].id.u.ip.src_ip); 1364 printf("%3d ", q[l].hash_slot); 1365 pe = getprotobynumber(q[l].id.u.ip.proto); 1366 if (pe) 1367 printf("%-4s ", pe->p_name); 1368 else 1369 printf("%4u ", q[l].id.u.ip.proto); 1370 printf("%15s/%-5d ", 1371 inet_ntoa(ina), q[l].id.u.ip.src_port); 1372 ina.s_addr = htonl(q[l].id.u.ip.dst_ip); 1373 printf("%15s/%-5d ", 1374 inet_ntoa(ina), q[l].id.u.ip.dst_port); 1375 printf("%4ju %8ju %2u %4u %3u\n", 1376 (uintmax_t)q[l].tot_pkts, (uintmax_t)q[l].tot_bytes, 1377 q[l].len, q[l].len_bytes, q[l].drops); 1378 if (verbose) 1379 printf(" S %20ju F %20ju\n", 1380 (uintmax_t)q[l].S, (uintmax_t)q[l].F); 1381 } 1382 } 1383 1384 static void 1385 print_flowset_parms(struct dn_ioc_flowset *fs, char *prefix) 1386 { 1387 int l; 1388 char qs[30]; 1389 char plr[30]; 1390 char red[90]; /* Display RED parameters */ 1391 1392 l = fs->qsize; 1393 if (fs->flags_fs & DN_QSIZE_IS_BYTES) { 1394 if (l >= 8192) 1395 sprintf(qs, "%d KB", l / 1024); 1396 else 1397 sprintf(qs, "%d B", l); 1398 } else 1399 sprintf(qs, "%3d sl.", l); 1400 if (fs->plr) 1401 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff)); 1402 else 1403 plr[0] = '\0'; 1404 if (fs->flags_fs & DN_IS_RED) /* RED parameters */ 1405 sprintf(red, 1406 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f", 1407 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ', 1408 1.0 * fs->w_q / (double)(1 << SCALE_RED), 1409 SCALE_VAL(fs->min_th), 1410 SCALE_VAL(fs->max_th), 1411 1.0 * fs->max_p / (double)(1 << SCALE_RED)); 1412 else 1413 sprintf(red, "droptail"); 1414 1415 printf("%s %s%s %d queues (%d buckets) %s\n", 1416 prefix, qs, plr, fs->rq_elements, fs->rq_size, red); 1417 } 1418 1419 static void 1420 list_pipes(void *data, int nbytes, int ac, char *av[]) 1421 { 1422 u_long rulenum; 1423 void *next = data; 1424 struct dn_ioc_pipe *p = (struct dn_ioc_pipe *)data; 1425 struct dn_ioc_flowset *fs; 1426 struct dn_ioc_flowqueue *q; 1427 int l; 1428 1429 if (ac > 0) 1430 rulenum = strtoul(*av++, NULL, 10); 1431 else 1432 rulenum = 0; 1433 for (; nbytes >= (int)sizeof(*p); p = (struct dn_ioc_pipe *)next) { 1434 double b = p->bandwidth; 1435 char buf[30]; 1436 char prefix[80]; 1437 1438 if (p->fs.fs_type != DN_IS_PIPE) 1439 break; /* done with pipes, now queues */ 1440 1441 /* 1442 * compute length, as pipe have variable size 1443 */ 1444 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q); 1445 next = (uint8_t *)p + l; 1446 nbytes -= l; 1447 1448 if (rulenum != 0 && rulenum != (u_long)p->pipe_nr) 1449 continue; 1450 1451 /* 1452 * Print rate 1453 */ 1454 if (b == 0) 1455 sprintf(buf, "unlimited"); 1456 else if (b >= 1000000) 1457 sprintf(buf, "%7.3f Mbit/s", b/1000000); 1458 else if (b >= 1000) 1459 sprintf(buf, "%7.3f Kbit/s", b/1000); 1460 else 1461 sprintf(buf, "%7.3f bit/s ", b); 1462 1463 sprintf(prefix, "%05d: %s %4d ms ", 1464 p->pipe_nr, buf, p->delay); 1465 print_flowset_parms(&p->fs, prefix); 1466 if (verbose) 1467 printf(" V %20ju\n", (uintmax_t)p->V >> MY_M); 1468 1469 q = (struct dn_ioc_flowqueue *)(p+1); 1470 list_queues(&p->fs, q); 1471 } 1472 for (fs = next; nbytes >= (int)sizeof(*fs); fs = next) { 1473 char prefix[80]; 1474 1475 if (fs->fs_type != DN_IS_QUEUE) 1476 break; 1477 l = sizeof(*fs) + fs->rq_elements * sizeof(*q); 1478 next = (uint8_t *)fs + l; 1479 nbytes -= l; 1480 q = (struct dn_ioc_flowqueue *)(fs+1); 1481 sprintf(prefix, "q%05d: weight %d pipe %d ", 1482 fs->fs_nr, fs->weight, fs->parent_nr); 1483 print_flowset_parms(fs, prefix); 1484 list_queues(fs, q); 1485 } 1486 } 1487 1488 /* 1489 * This one handles all set-related commands 1490 * ipfw set { show | enable | disable } 1491 * ipfw set swap X Y 1492 * ipfw set move X to Y 1493 * ipfw set move rule X to Y 1494 */ 1495 static void 1496 sets_handler(int ac, char *av[]) 1497 { 1498 u_int32_t set_disable, masks[2]; 1499 int i, nbytes; 1500 u_int16_t rulenum; 1501 u_int8_t cmd, new_set; 1502 1503 ac--; 1504 av++; 1505 1506 if (!ac) 1507 errx(EX_USAGE, "set needs command"); 1508 if (!strncmp(*av, "show", strlen(*av)) ) { 1509 void *data; 1510 const char *msg; 1511 1512 nbytes = sizeof(struct ipfw_ioc_rule); 1513 if ((data = malloc(nbytes)) == NULL) 1514 err(EX_OSERR, "malloc"); 1515 if (getsockopt(s, IPPROTO_IP, IP_FW_GET, data, &nbytes) < 0) 1516 err(EX_OSERR, "getsockopt(IP_FW_GET)"); 1517 set_disable = ((struct ipfw_ioc_rule *)data)->set_disable; 1518 1519 for (i = 0, msg = "disable" ; i < 31; i++) 1520 if ( (set_disable & (1<<i))) { 1521 printf("%s %d", msg, i); 1522 msg = ""; 1523 } 1524 msg = (set_disable) ? " enable" : "enable"; 1525 for (i = 0; i < 31; i++) 1526 if ( !(set_disable & (1<<i))) { 1527 printf("%s %d", msg, i); 1528 msg = ""; 1529 } 1530 printf("\n"); 1531 } else if (!strncmp(*av, "swap", strlen(*av))) { 1532 ac--; av++; 1533 if (ac != 2) 1534 errx(EX_USAGE, "set swap needs 2 set numbers\n"); 1535 rulenum = atoi(av[0]); 1536 new_set = atoi(av[1]); 1537 if (!isdigit(*(av[0])) || rulenum > 30) 1538 errx(EX_DATAERR, "invalid set number %s\n", av[0]); 1539 if (!isdigit(*(av[1])) || new_set > 30) 1540 errx(EX_DATAERR, "invalid set number %s\n", av[1]); 1541 masks[0] = (4 << 24) | (new_set << 16) | (rulenum); 1542 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, 1543 masks, sizeof(u_int32_t)); 1544 } else if (!strncmp(*av, "move", strlen(*av))) { 1545 ac--; av++; 1546 if (ac && !strncmp(*av, "rule", strlen(*av))) { 1547 cmd = 2; 1548 ac--; av++; 1549 } else 1550 cmd = 3; 1551 if (ac != 3 || strncmp(av[1], "to", strlen(*av))) 1552 errx(EX_USAGE, "syntax: set move [rule] X to Y\n"); 1553 rulenum = atoi(av[0]); 1554 new_set = atoi(av[2]); 1555 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > 30) || 1556 (cmd == 2 && rulenum == 65535) ) 1557 errx(EX_DATAERR, "invalid source number %s\n", av[0]); 1558 if (!isdigit(*(av[2])) || new_set > 30) 1559 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]); 1560 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum); 1561 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, 1562 masks, sizeof(u_int32_t)); 1563 } else if (!strncmp(*av, "disable", strlen(*av)) || 1564 !strncmp(*av, "enable", strlen(*av)) ) { 1565 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0; 1566 1567 ac--; av++; 1568 masks[0] = masks[1] = 0; 1569 1570 while (ac) { 1571 if (isdigit(**av)) { 1572 i = atoi(*av); 1573 if (i < 0 || i > 30) 1574 errx(EX_DATAERR, 1575 "invalid set number %d\n", i); 1576 masks[which] |= (1<<i); 1577 } else if (!strncmp(*av, "disable", strlen(*av))) 1578 which = 0; 1579 else if (!strncmp(*av, "enable", strlen(*av))) 1580 which = 1; 1581 else 1582 errx(EX_DATAERR, 1583 "invalid set command %s\n", *av); 1584 av++; ac--; 1585 } 1586 if ( (masks[0] & masks[1]) != 0 ) 1587 errx(EX_DATAERR, 1588 "cannot enable and disable the same set\n"); 1589 1590 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, masks, sizeof(masks)); 1591 if (i) 1592 warn("set enable/disable: setsockopt(IP_FW_DEL)"); 1593 } else 1594 errx(EX_USAGE, "invalid set command %s\n", *av); 1595 } 1596 1597 static void 1598 sysctl_handler(int ac, char *av[], int which) 1599 { 1600 ac--; 1601 av++; 1602 1603 if (*av == NULL) { 1604 warnx("missing keyword to enable/disable\n"); 1605 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) { 1606 sysctlbyname("net.inet.ip.fw.enable", NULL, 0, 1607 &which, sizeof(which)); 1608 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) { 1609 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0, 1610 &which, sizeof(which)); 1611 } else if (strncmp(*av, "debug", strlen(*av)) == 0) { 1612 sysctlbyname("net.inet.ip.fw.debug", NULL, 0, 1613 &which, sizeof(which)); 1614 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) { 1615 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0, 1616 &which, sizeof(which)); 1617 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) { 1618 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0, 1619 &which, sizeof(which)); 1620 } else { 1621 warnx("unrecognize enable/disable keyword: %s\n", *av); 1622 } 1623 } 1624 1625 static void 1626 list(int ac, char *av[]) 1627 { 1628 struct ipfw_ioc_rule *r; 1629 struct ipfw_ioc_state *dynrules, *d; 1630 1631 void *data = NULL; 1632 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width; 1633 int exitval = EX_OK; 1634 int lac; 1635 char **lav; 1636 u_long rnum; 1637 char *endptr; 1638 int seen = 0; 1639 1640 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET; 1641 int nalloc = 1024; /* start somewhere... */ 1642 1643 ac--; 1644 av++; 1645 1646 /* get rules or pipes from kernel, resizing array as necessary */ 1647 nbytes = nalloc; 1648 1649 while (nbytes >= nalloc) { 1650 nalloc = nalloc * 2 + 200; 1651 nbytes = nalloc; 1652 if ((data = realloc(data, nbytes)) == NULL) 1653 err(EX_OSERR, "realloc"); 1654 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0) 1655 err(EX_OSERR, "getsockopt(IP_%s_GET)", 1656 do_pipe ? "DUMMYNET" : "FW"); 1657 } 1658 1659 if (do_pipe) { 1660 list_pipes(data, nbytes, ac, av); 1661 goto done; 1662 } 1663 1664 /* 1665 * Count static rules. 1666 */ 1667 r = data; 1668 nstat = r->static_count; 1669 1670 /* 1671 * Count dynamic rules. This is easier as they have 1672 * fixed size. 1673 */ 1674 dynrules = (struct ipfw_ioc_state *)((uint8_t *)r + r->static_len); 1675 ndyn = (nbytes - r->static_len) / sizeof(*dynrules); 1676 1677 /* if showing stats, figure out column widths ahead of time */ 1678 bcwidth = pcwidth = 0; 1679 if (do_acct) { 1680 for (n = 0, r = data; n < nstat; n++, 1681 r = (struct ipfw_ioc_rule *)((uint8_t *)r + IOC_RULESIZE(r))) { 1682 /* packet counter */ 1683 width = snprintf(NULL, 0, "%ju", (uintmax_t)r->pcnt); 1684 if (width > pcwidth) 1685 pcwidth = width; 1686 1687 /* byte counter */ 1688 width = snprintf(NULL, 0, "%ju", (uintmax_t)r->bcnt); 1689 if (width > bcwidth) 1690 bcwidth = width; 1691 } 1692 } 1693 if (do_dynamic && ndyn) { 1694 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 1695 width = snprintf(NULL, 0, "%ju", (uintmax_t)d->pcnt); 1696 if (width > pcwidth) 1697 pcwidth = width; 1698 1699 width = snprintf(NULL, 0, "%ju", (uintmax_t)d->bcnt); 1700 if (width > bcwidth) 1701 bcwidth = width; 1702 } 1703 } 1704 /* if no rule numbers were specified, list all rules */ 1705 if (ac == 0) { 1706 for (n = 0, r = data; n < nstat; n++, 1707 r = (struct ipfw_ioc_rule *)((uint8_t *)r + IOC_RULESIZE(r))) 1708 show_ipfw(r, pcwidth, bcwidth); 1709 1710 if (do_dynamic && ndyn) { 1711 printf("## Dynamic rules (%d):\n", ndyn); 1712 for (n = 0, d = dynrules; n < ndyn; n++, d++) 1713 show_dyn_ipfw(d, pcwidth, bcwidth); 1714 } 1715 goto done; 1716 } 1717 1718 /* display specific rules requested on command line */ 1719 1720 for (lac = ac, lav = av; lac != 0; lac--) { 1721 /* convert command line rule # */ 1722 rnum = strtoul(*lav++, &endptr, 10); 1723 if (*endptr) { 1724 exitval = EX_USAGE; 1725 warnx("invalid rule number: %s", *(lav - 1)); 1726 continue; 1727 } 1728 for (n = seen = 0, r = data; n < nstat; n++, 1729 r = (struct ipfw_ioc_rule *)((uint8_t *)r + IOC_RULESIZE(r))) { 1730 if (r->rulenum > rnum) 1731 break; 1732 if (r->rulenum == rnum) { 1733 show_ipfw(r, pcwidth, bcwidth); 1734 seen = 1; 1735 } 1736 } 1737 if (!seen) { 1738 /* give precedence to other error(s) */ 1739 if (exitval == EX_OK) 1740 exitval = EX_UNAVAILABLE; 1741 warnx("rule %lu does not exist", rnum); 1742 } 1743 } 1744 1745 if (do_dynamic && ndyn) { 1746 printf("## Dynamic rules:\n"); 1747 for (lac = ac, lav = av; lac != 0; lac--) { 1748 rnum = strtoul(*lav++, &endptr, 10); 1749 if (*endptr) 1750 /* already warned */ 1751 continue; 1752 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 1753 if (d->rulenum > rnum) 1754 break; 1755 if (d->rulenum == rnum) 1756 show_dyn_ipfw(d, pcwidth, bcwidth); 1757 } 1758 } 1759 } 1760 1761 ac = 0; 1762 1763 done: 1764 free(data); 1765 1766 if (exitval != EX_OK) 1767 exit(exitval); 1768 } 1769 1770 static void 1771 show_usage(void) 1772 { 1773 fprintf(stderr, "usage: ipfw [options]\n" 1774 " add [number] rule\n" 1775 " pipe number config [pipeconfig]\n" 1776 " queue number config [queueconfig]\n" 1777 " [pipe] flush\n" 1778 " [pipe] delete number ...\n" 1779 " [pipe] {list|show} [number ...]\n" 1780 " {zero|resetlog} [number ...]\n" 1781 "do \"ipfw -h\" or see ipfw manpage for details\n" 1782 ); 1783 1784 exit(EX_USAGE); 1785 } 1786 1787 static void 1788 help(void) 1789 { 1790 1791 fprintf(stderr, "ipfw syntax summary:\n" 1792 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n" 1793 "ipfw {pipe|queue} N config BODY\n" 1794 "ipfw [pipe] {zero|delete|show} [N{,N}]\n" 1795 "\n" 1796 "RULE: [1..] [PROB] BODY\n" 1797 "RULENUM: INTEGER(1..65534)\n" 1798 "PROB: prob REAL(0..1)\n" 1799 "BODY: check-state [LOG] (no body) |\n" 1800 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n" 1801 "ACTION: check-state | allow | count | deny | reject | skipto N |\n" 1802 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n" 1803 "ADDR: [ MAC dst src ether_type ] \n" 1804 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n" 1805 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n" 1806 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n" 1807 "OPTION_LIST: OPTION [,OPTION_LIST]\n" 1808 ); 1809 exit(0); 1810 } 1811 1812 1813 static int 1814 lookup_host (char *host, struct in_addr *ipaddr) 1815 { 1816 struct hostent *he; 1817 1818 if (!inet_aton(host, ipaddr)) { 1819 if ((he = gethostbyname(host)) == NULL) 1820 return(-1); 1821 *ipaddr = *(struct in_addr *)he->h_addr_list[0]; 1822 } 1823 return(0); 1824 } 1825 1826 /* 1827 * fills the addr and mask fields in the instruction as appropriate from av. 1828 * Update length as appropriate. 1829 * The following formats are allowed: 1830 * any matches any IP. Actually returns an empty instruction. 1831 * me returns O_IP_*_ME 1832 * <table_id> O_IP_*_TABLE 1833 * [iface[:net]] O_IP_*_IFIP 1834 * 1.2.3.4 single IP address 1835 * 1.2.3.4:5.6.7.8 address:mask 1836 * 1.2.3.4/24 address/mask 1837 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet 1838 */ 1839 static void 1840 fill_ip(ipfw_insn_ip *cmd, char *av) 1841 { 1842 char *p = NULL, md = 0; 1843 u_int32_t i; 1844 1845 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 1846 1847 if (!strncmp(av, "any", strlen(av))) 1848 return; 1849 1850 if (!strncmp(av, "me", strlen(av))) { 1851 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 1852 return; 1853 } 1854 1855 if (strlen(av) >= 3 && av[0] == '<' && av[strlen(av) - 1] == '>') { 1856 int pos = strlen(av) - 1; 1857 uint16_t tableid; 1858 char *eptr; 1859 1860 /* 1861 * Table: "<tableid>" 1862 */ 1863 av[pos] = '\0'; 1864 tableid = strtoul(&av[1], &eptr, 0); 1865 if (*eptr != '\0') { 1866 av[pos] = '>'; 1867 errx(EX_DATAERR, "invalid tableid ``%s''", av); 1868 } 1869 av[pos] = '>'; 1870 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 1871 cmd->o.opcode = O_IP_DST_TABLE; 1872 cmd->o.arg1 = tableid; 1873 return; 1874 } 1875 1876 if (strlen(av) >= 3 && av[0] == '[' && av[strlen(av) - 1] == ']') { 1877 int pos = strlen(av) - 1; 1878 ipfw_insn_ifip *cmd1 = (ipfw_insn_ifip *)cmd; 1879 char *c; 1880 1881 /* 1882 * Interface IP: "[ifname[:net]]" 1883 */ 1884 cmd1->o.len |= F_INSN_SIZE(ipfw_insn_ifip); 1885 cmd1->o.opcode = O_IP_DST_IFIP; 1886 cmd1->o.arg1 = 0; 1887 cmd1->addr.s_addr = 0; 1888 cmd1->mask.s_addr = 0; 1889 1890 av[pos] = '\0'; 1891 c = strchr(av, ':'); 1892 if (c != NULL) { 1893 if (strcmp(c + 1, "net") == 0) { 1894 cmd1->o.arg1 |= IPFW_IFIP_NET; 1895 } else { 1896 errx(EX_DATAERR, "invalid ifname modifier: %s", 1897 c + 1); 1898 } 1899 *c = '\0'; 1900 } 1901 1902 strlcpy(cmd1->ifname, &av[1], sizeof(cmd1->ifname)); 1903 if (c != NULL) 1904 *c = ':'; 1905 av[pos] = ']'; 1906 return; 1907 } 1908 1909 p = strchr(av, '/'); 1910 if (!p) 1911 p = strchr(av, ':'); 1912 if (p) { 1913 md = *p; 1914 *p++ = '\0'; 1915 } 1916 1917 if (lookup_host(av, &cmd->addr) != 0) 1918 errx(EX_NOHOST, "hostname ``%s'' unknown", av); 1919 switch (md) { 1920 case ':': 1921 if (!inet_aton(p, &cmd->mask)) 1922 errx(EX_DATAERR, "bad netmask ``%s''", p); 1923 break; 1924 case '/': 1925 i = atoi(p); 1926 if (i == 0) 1927 cmd->mask.s_addr = htonl(0); 1928 else if (i > 32) 1929 errx(EX_DATAERR, "bad width ``%s''", p); 1930 else 1931 cmd->mask.s_addr = htonl(~0 << (32 - i)); 1932 break; 1933 default: 1934 cmd->mask.s_addr = htonl(~0); 1935 break; 1936 } 1937 cmd->addr.s_addr &= cmd->mask.s_addr; 1938 /* 1939 * now look if we have a set of addresses. They are stored as follows: 1940 * arg1 is the set size (powers of 2, 2..256) 1941 * addr is the base address IN HOST FORMAT 1942 * mask.. is an array of u_int32_t with bits set. 1943 */ 1944 if (p) 1945 p = strchr(p, '{'); 1946 if (p) { /* fetch addresses */ 1947 u_int32_t *d; 1948 int low, high; 1949 int ii = contigmask((u_char *)&(cmd->mask), 32); 1950 1951 if (ii < 24 || ii > 31) { 1952 fprintf(stderr, "invalid set with mask %d\n", 1953 ii); 1954 exit(0); 1955 } 1956 cmd->o.arg1 = 1<<(32-ii); 1957 cmd->addr.s_addr = ntohl(cmd->addr.s_addr); 1958 d = (u_int32_t *)&cmd->mask; 1959 cmd->o.opcode = O_IP_DST_SET; /* default */ 1960 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32; 1961 for (ii = 0; ii < (cmd->o.arg1+31)/32 ; ii++) 1962 d[ii] = 0; /* clear masks */ 1963 1964 av = p+1; 1965 low = cmd->addr.s_addr & 0xff; 1966 high = low + cmd->o.arg1 - 1; 1967 while (isdigit(*av)) { 1968 char *str; 1969 u_int16_t a = strtol(av, &str, 0); 1970 1971 if (str == av) /* no parameter */ 1972 break; 1973 if (a < low || a > high) { 1974 fprintf(stderr, "addr %d out of range [%d-%d]\n", 1975 a, low, high); 1976 exit(0); 1977 } 1978 a -= low; 1979 d[ a/32] |= 1<<(a & 31); 1980 if (*str != ',') 1981 break; 1982 av = str+1; 1983 } 1984 return; 1985 } 1986 1987 if (cmd->mask.s_addr == 0) { /* any */ 1988 if (cmd->o.len & F_NOT) 1989 errx(EX_DATAERR, "not any never matches"); 1990 else /* useless, nuke it */ 1991 return; 1992 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */ 1993 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 1994 else /* addr/mask */ 1995 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip); 1996 } 1997 1998 1999 /* 2000 * helper function to process a set of flags and set bits in the 2001 * appropriate masks. 2002 */ 2003 static void 2004 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode, 2005 struct _s_x *flags, char *p) 2006 { 2007 u_int8_t set=0, clear=0; 2008 2009 while (p && *p) { 2010 char *q; /* points to the separator */ 2011 int val; 2012 u_int8_t *which; /* mask we are working on */ 2013 2014 if (*p == '!') { 2015 p++; 2016 which = &clear; 2017 } else 2018 which = &set; 2019 q = strchr(p, ','); 2020 if (q) 2021 *q++ = '\0'; 2022 val = match_token(flags, p); 2023 if (val <= 0) 2024 errx(EX_DATAERR, "invalid flag %s", p); 2025 *which |= (u_int8_t)val; 2026 p = q; 2027 } 2028 cmd->opcode = opcode; 2029 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1; 2030 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8); 2031 } 2032 2033 2034 static void 2035 delete(int ac, char *av[]) 2036 { 2037 u_int32_t rulenum; 2038 struct dn_ioc_pipe pipe; 2039 int i; 2040 int exitval = EX_OK; 2041 int do_set = 0; 2042 2043 memset(&pipe, 0, sizeof pipe); 2044 2045 av++; ac--; 2046 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) { 2047 do_set = 1; /* delete set */ 2048 ac--; av++; 2049 } 2050 2051 /* Rule number */ 2052 while (ac && isdigit(**av)) { 2053 i = atoi(*av); av++; ac--; 2054 if (do_pipe) { 2055 if (do_pipe == 1) 2056 pipe.pipe_nr = i; 2057 else 2058 pipe.fs.fs_nr = i; 2059 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL, 2060 &pipe, sizeof pipe); 2061 if (i) { 2062 exitval = 1; 2063 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", 2064 do_pipe == 1 ? pipe.pipe_nr : 2065 pipe.fs.fs_nr); 2066 } 2067 } else { 2068 rulenum = (i & 0xffff) | (do_set << 24); 2069 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum, 2070 sizeof rulenum); 2071 if (i) { 2072 exitval = EX_UNAVAILABLE; 2073 warn("rule %u: setsockopt(IP_FW_DEL)", 2074 rulenum); 2075 } 2076 } 2077 } 2078 if (exitval != EX_OK) 2079 exit(exitval); 2080 } 2081 2082 2083 /* 2084 * fill the interface structure. We do not check the name as we can 2085 * create interfaces dynamically, so checking them at insert time 2086 * makes relatively little sense. 2087 * Interface names containing '*', '?', or '[' are assumed to be shell 2088 * patterns which match interfaces. 2089 */ 2090 static void 2091 fill_iface(ipfw_insn_if *cmd, char *arg) 2092 { 2093 cmd->name[0] = '\0'; 2094 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if); 2095 2096 /* Parse the interface or address */ 2097 if (!strcmp(arg, "any")) 2098 cmd->o.len = 0; /* effectively ignore this command */ 2099 else if (!isdigit(*arg)) { 2100 strlcpy(cmd->name, arg, sizeof(cmd->name)); 2101 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0; 2102 } else if (!inet_aton(arg, &cmd->p.ip)) 2103 errx(EX_DATAERR, "bad ip address ``%s''", arg); 2104 } 2105 2106 static unsigned long 2107 getbw(const char *str, u_short *flags, int kb) 2108 { 2109 char *end; 2110 unsigned long val; 2111 int inbytes = 0; 2112 2113 val = strtoul(str, &end, 0); 2114 if (*end == 'k' || *end == 'K') { 2115 ++end; 2116 val *= kb; 2117 } else if (*end == 'm' || *end == 'M') { 2118 ++end; 2119 val *= kb * kb; 2120 } 2121 2122 /* 2123 * Deal with bits or bytes or b(bits) or B(bytes). If there is no 2124 * trailer assume bits. 2125 */ 2126 if (strncasecmp(end, "bit", 3) == 0) { 2127 ; 2128 } else if (strncasecmp(end, "byte", 4) == 0) { 2129 inbytes = 1; 2130 } else if (*end == 'b') { 2131 ; 2132 } else if (*end == 'B') { 2133 inbytes = 1; 2134 } 2135 2136 /* 2137 * Return in bits if flags is NULL, else flag bits 2138 * or bytes in flags and return the unconverted value. 2139 */ 2140 if (inbytes && flags) 2141 *flags |= DN_QSIZE_IS_BYTES; 2142 else if (inbytes && flags == NULL) 2143 val *= 8; 2144 return(val); 2145 } 2146 2147 /* 2148 * the following macro returns an error message if we run out of 2149 * arguments. 2150 */ 2151 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);} 2152 2153 static void 2154 config_pipe(int ac, char **av) 2155 { 2156 struct dn_ioc_pipe pipe; 2157 int i; 2158 char *end; 2159 u_int32_t a; 2160 2161 memset(&pipe, 0, sizeof pipe); 2162 2163 av++; ac--; 2164 /* Pipe number */ 2165 if (ac && isdigit(**av)) { 2166 i = atoi(*av); av++; ac--; 2167 if (do_pipe == 1) 2168 pipe.pipe_nr = i; 2169 else 2170 pipe.fs.fs_nr = i; 2171 } 2172 while (ac > 0) { 2173 double d; 2174 int tok = match_token(dummynet_params, *av); 2175 ac--; av++; 2176 2177 switch(tok) { 2178 case TOK_NOERROR: 2179 pipe.fs.flags_fs |= DN_NOERROR; 2180 break; 2181 2182 case TOK_PLR: 2183 NEED1("plr needs argument 0..1\n"); 2184 d = strtod(av[0], NULL); 2185 if (d > 1) 2186 d = 1; 2187 else if (d < 0) 2188 d = 0; 2189 pipe.fs.plr = (int)(d*0x7fffffff); 2190 ac--; av++; 2191 break; 2192 2193 case TOK_QUEUE: 2194 NEED1("queue needs queue size\n"); 2195 end = NULL; 2196 pipe.fs.qsize = getbw(av[0], &pipe.fs.flags_fs, 1024); 2197 ac--; av++; 2198 break; 2199 2200 case TOK_BUCKETS: 2201 NEED1("buckets needs argument\n"); 2202 pipe.fs.rq_size = strtoul(av[0], NULL, 0); 2203 ac--; av++; 2204 break; 2205 2206 case TOK_MASK: 2207 NEED1("mask needs mask specifier\n"); 2208 /* 2209 * per-flow queue, mask is dst_ip, dst_port, 2210 * src_ip, src_port, proto measured in bits 2211 */ 2212 2213 pipe.fs.flow_mask.type = ETHERTYPE_IP; 2214 pipe.fs.flow_mask.u.ip.dst_ip = 0; 2215 pipe.fs.flow_mask.u.ip.src_ip = 0; 2216 pipe.fs.flow_mask.u.ip.dst_port = 0; 2217 pipe.fs.flow_mask.u.ip.src_port = 0; 2218 pipe.fs.flow_mask.u.ip.proto = 0; 2219 end = NULL; 2220 2221 while (ac >= 1) { 2222 u_int32_t *p32 = NULL; 2223 u_int16_t *p16 = NULL; 2224 2225 tok = match_token(dummynet_params, *av); 2226 ac--; av++; 2227 switch(tok) { 2228 case TOK_ALL: 2229 /* 2230 * special case, all bits significant 2231 */ 2232 pipe.fs.flow_mask.u.ip.dst_ip = ~0; 2233 pipe.fs.flow_mask.u.ip.src_ip = ~0; 2234 pipe.fs.flow_mask.u.ip.dst_port = ~0; 2235 pipe.fs.flow_mask.u.ip.src_port = ~0; 2236 pipe.fs.flow_mask.u.ip.proto = ~0; 2237 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK; 2238 goto end_mask; 2239 2240 case TOK_DSTIP: 2241 p32 = &pipe.fs.flow_mask.u.ip.dst_ip; 2242 break; 2243 2244 case TOK_SRCIP: 2245 p32 = &pipe.fs.flow_mask.u.ip.src_ip; 2246 break; 2247 2248 case TOK_DSTPORT: 2249 p16 = &pipe.fs.flow_mask.u.ip.dst_port; 2250 break; 2251 2252 case TOK_SRCPORT: 2253 p16 = &pipe.fs.flow_mask.u.ip.src_port; 2254 break; 2255 2256 case TOK_PROTO: 2257 break; 2258 2259 default: 2260 ac++; av--; /* backtrack */ 2261 goto end_mask; 2262 } 2263 if (ac < 1) 2264 errx(EX_USAGE, "mask: value missing"); 2265 if (*av[0] == '/') { 2266 a = strtoul(av[0]+1, &end, 0); 2267 a = (a == 32) ? ~0 : (1 << a) - 1; 2268 } else 2269 a = strtoul(av[0], &end, 0); 2270 if (p32 != NULL) 2271 *p32 = a; 2272 else if (p16 != NULL) { 2273 if (a > 65535) 2274 errx(EX_DATAERR, 2275 "mask: must be 16 bit"); 2276 *p16 = (u_int16_t)a; 2277 } else { 2278 if (a > 255) 2279 errx(EX_DATAERR, 2280 "mask: must be 8 bit"); 2281 pipe.fs.flow_mask.u.ip.proto = (uint8_t)a; 2282 } 2283 if (a != 0) 2284 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK; 2285 ac--; av++; 2286 } /* end while, config masks */ 2287 end_mask: 2288 break; 2289 2290 case TOK_RED: 2291 case TOK_GRED: 2292 NEED1("red/gred needs w_q/min_th/max_th/max_p\n"); 2293 pipe.fs.flags_fs |= DN_IS_RED; 2294 if (tok == TOK_GRED) 2295 pipe.fs.flags_fs |= DN_IS_GENTLE_RED; 2296 /* 2297 * the format for parameters is w_q/min_th/max_th/max_p 2298 */ 2299 if ((end = strsep(&av[0], "/"))) { 2300 double w_q = strtod(end, NULL); 2301 if (w_q > 1 || w_q <= 0) 2302 errx(EX_DATAERR, "0 < w_q <= 1"); 2303 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED)); 2304 } 2305 if ((end = strsep(&av[0], "/"))) { 2306 pipe.fs.min_th = strtoul(end, &end, 0); 2307 if (*end == 'K' || *end == 'k') 2308 pipe.fs.min_th *= 1024; 2309 } 2310 if ((end = strsep(&av[0], "/"))) { 2311 pipe.fs.max_th = strtoul(end, &end, 0); 2312 if (*end == 'K' || *end == 'k') 2313 pipe.fs.max_th *= 1024; 2314 } 2315 if ((end = strsep(&av[0], "/"))) { 2316 double max_p = strtod(end, NULL); 2317 if (max_p > 1 || max_p <= 0) 2318 errx(EX_DATAERR, "0 < max_p <= 1"); 2319 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED)); 2320 } 2321 ac--; av++; 2322 break; 2323 2324 case TOK_DROPTAIL: 2325 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED); 2326 break; 2327 2328 case TOK_BW: 2329 NEED1("bw needs bandwidth\n"); 2330 if (do_pipe != 1) 2331 errx(EX_DATAERR, "bandwidth only valid for pipes"); 2332 /* 2333 * set bandwidth value 2334 */ 2335 pipe.bandwidth = getbw(av[0], NULL, 1000); 2336 if (pipe.bandwidth < 0) 2337 errx(EX_DATAERR, "bandwidth too large"); 2338 ac--; av++; 2339 break; 2340 2341 case TOK_DELAY: 2342 if (do_pipe != 1) 2343 errx(EX_DATAERR, "delay only valid for pipes"); 2344 NEED1("delay needs argument 0..10000ms\n"); 2345 pipe.delay = strtoul(av[0], NULL, 0); 2346 ac--; av++; 2347 break; 2348 2349 case TOK_WEIGHT: 2350 if (do_pipe == 1) 2351 errx(EX_DATAERR,"weight only valid for queues"); 2352 NEED1("weight needs argument 0..100\n"); 2353 pipe.fs.weight = strtoul(av[0], &end, 0); 2354 ac--; av++; 2355 break; 2356 2357 case TOK_PIPE: 2358 if (do_pipe == 1) 2359 errx(EX_DATAERR,"pipe only valid for queues"); 2360 NEED1("pipe needs pipe_number\n"); 2361 pipe.fs.parent_nr = strtoul(av[0], &end, 0); 2362 ac--; av++; 2363 break; 2364 2365 default: 2366 errx(EX_DATAERR, "unrecognised option ``%s''", *av); 2367 } 2368 } 2369 if (do_pipe == 1) { 2370 if (pipe.pipe_nr == 0) 2371 errx(EX_DATAERR, "pipe_nr must be > 0"); 2372 if (pipe.delay > 10000) 2373 errx(EX_DATAERR, "delay must be < 10000"); 2374 } else { /* do_pipe == 2, queue */ 2375 if (pipe.fs.parent_nr == 0) 2376 errx(EX_DATAERR, "pipe must be > 0"); 2377 if (pipe.fs.weight >100) 2378 errx(EX_DATAERR, "weight must be <= 100"); 2379 } 2380 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) { 2381 if (pipe.fs.qsize > 1024*1024) 2382 errx(EX_DATAERR, "queue size must be < 1MB"); 2383 } else { 2384 if (pipe.fs.qsize > 100) 2385 errx(EX_DATAERR, "2 <= queue size <= 100"); 2386 } 2387 if (pipe.fs.flags_fs & DN_IS_RED) { 2388 size_t len; 2389 int lookup_depth, avg_pkt_size; 2390 double step, idle, weight, w_q; 2391 int clock_hz; 2392 int t; 2393 2394 if (pipe.fs.min_th >= pipe.fs.max_th) 2395 errx(EX_DATAERR, "min_th %d must be < than max_th %d", 2396 pipe.fs.min_th, pipe.fs.max_th); 2397 if (pipe.fs.max_th == 0) 2398 errx(EX_DATAERR, "max_th must be > 0"); 2399 2400 len = sizeof(int); 2401 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth", 2402 &lookup_depth, &len, NULL, 0) == -1) 2403 2404 errx(1, "sysctlbyname(\"%s\")", 2405 "net.inet.ip.dummynet.red_lookup_depth"); 2406 if (lookup_depth == 0) 2407 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth" 2408 " must be greater than zero"); 2409 2410 len = sizeof(int); 2411 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size", 2412 &avg_pkt_size, &len, NULL, 0) == -1) 2413 2414 errx(1, "sysctlbyname(\"%s\")", 2415 "net.inet.ip.dummynet.red_avg_pkt_size"); 2416 if (avg_pkt_size == 0) 2417 errx(EX_DATAERR, 2418 "net.inet.ip.dummynet.red_avg_pkt_size must" 2419 " be greater than zero"); 2420 2421 len = sizeof(clock_hz); 2422 if (sysctlbyname("net.inet.ip.dummynet.hz", &clock_hz, &len, 2423 NULL, 0) == -1) { 2424 errx(1, "sysctlbyname(\"%s\")", 2425 "net.inet.ip.dummynet.hz"); 2426 } 2427 2428 /* 2429 * Ticks needed for sending a medium-sized packet. 2430 * Unfortunately, when we are configuring a WF2Q+ queue, we 2431 * do not have bandwidth information, because that is stored 2432 * in the parent pipe, and also we have multiple queues 2433 * competing for it. So we set step=0, which is not very 2434 * correct. But on the other hand, why do we want RED with 2435 * WF2Q+ ? 2436 */ 2437 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */ 2438 step = 0; 2439 else 2440 step = clock_hz * avg_pkt_size * 8 / pipe.bandwidth; 2441 2442 /* 2443 * max idle time (in ticks) before avg queue size becomes 0. 2444 * NOTA: (3/w_q) is approx the value x so that 2445 * (1-w_q)^x < 10^-3. 2446 */ 2447 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED); 2448 idle = step * 3. / w_q; 2449 pipe.fs.lookup_step = (int)idle / lookup_depth; 2450 if (!pipe.fs.lookup_step) 2451 pipe.fs.lookup_step = 1; 2452 weight = 1 - w_q; 2453 for (t = pipe.fs.lookup_step; t > 0; --t) 2454 weight *= weight; 2455 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED)); 2456 } 2457 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe, 2458 sizeof pipe); 2459 if (i) 2460 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE"); 2461 } 2462 2463 static void 2464 get_mac_addr_mask(char *p, u_char *addr, u_char *mask) 2465 { 2466 int i, l; 2467 2468 for (i=0; i<6; i++) 2469 addr[i] = mask[i] = 0; 2470 if (!strcmp(p, "any")) 2471 return; 2472 2473 for (i=0; *p && i<6;i++, p++) { 2474 addr[i] = strtol(p, &p, 16); 2475 if (*p != ':') /* we start with the mask */ 2476 break; 2477 } 2478 if (*p == '/') { /* mask len */ 2479 l = strtol(p+1, &p, 0); 2480 for (i=0; l>0; l -=8, i++) 2481 mask[i] = (l >=8) ? 0xff : (~0) << (8-l); 2482 } else if (*p == '&') { /* mask */ 2483 for (i=0, p++; *p && i<6;i++, p++) { 2484 mask[i] = strtol(p, &p, 16); 2485 if (*p != ':') 2486 break; 2487 } 2488 } else if (*p == '\0') { 2489 for (i=0; i<6; i++) 2490 mask[i] = 0xff; 2491 } 2492 for (i=0; i<6; i++) 2493 addr[i] &= mask[i]; 2494 } 2495 2496 /* 2497 * helper function, updates the pointer to cmd with the length 2498 * of the current command, and also cleans up the first word of 2499 * the new command in case it has been clobbered before. 2500 */ 2501 static ipfw_insn * 2502 next_cmd(ipfw_insn *cmd) 2503 { 2504 cmd += F_LEN(cmd); 2505 bzero(cmd, sizeof(*cmd)); 2506 return cmd; 2507 } 2508 2509 /* 2510 * A function to fill simple commands of size 1. 2511 * Existing flags are preserved. 2512 */ 2513 static void 2514 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg) 2515 { 2516 cmd->opcode = opcode; 2517 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 2518 cmd->arg1 = arg; 2519 } 2520 2521 /* 2522 * Fetch and add the MAC address and type, with masks. This generates one or 2523 * two microinstructions, and returns the pointer to the last one. 2524 */ 2525 static ipfw_insn * 2526 add_mac(ipfw_insn *cmd, int ac, char *av[]) 2527 { 2528 ipfw_insn_mac *mac; 2529 2530 if (ac < 2) 2531 errx(EX_DATAERR, "MAC dst src"); 2532 2533 cmd->opcode = O_MACADDR2; 2534 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 2535 2536 mac = (ipfw_insn_mac *)cmd; 2537 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 2538 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */ 2539 return cmd; 2540 } 2541 2542 static ipfw_insn * 2543 add_mactype(ipfw_insn *cmd, int ac, char *av) 2544 { 2545 if (ac < 1) 2546 errx(EX_DATAERR, "missing MAC type"); 2547 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 2548 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 2549 cmd->opcode = O_MAC_TYPE; 2550 return cmd; 2551 } else 2552 return NULL; 2553 } 2554 2555 static ipfw_insn * 2556 add_proto(ipfw_insn *cmd, char *av) 2557 { 2558 struct protoent *pe; 2559 u_char proto = 0; 2560 2561 if (!strncmp(av, "all", strlen(av))) 2562 ; /* same as "ip" */ 2563 else if ((proto = atoi(av)) > 0) 2564 ; /* all done! */ 2565 else if ((pe = getprotobyname(av)) != NULL) 2566 proto = pe->p_proto; 2567 else 2568 return NULL; 2569 if (proto != IPPROTO_IP) 2570 fill_cmd(cmd, O_PROTO, 0, proto); 2571 return cmd; 2572 } 2573 2574 static ipfw_insn * 2575 add_srcip(ipfw_insn *cmd, char *av) 2576 { 2577 fill_ip((ipfw_insn_ip *)cmd, av); 2578 if (cmd->opcode == O_IP_DST_SET) /* set */ 2579 cmd->opcode = O_IP_SRC_SET; 2580 else if (cmd->opcode == O_IP_DST_TABLE) /* table */ 2581 cmd->opcode = O_IP_SRC_TABLE; 2582 else if (cmd->opcode == O_IP_DST_IFIP) /* iface's IP */ 2583 cmd->opcode = O_IP_SRC_IFIP; 2584 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 2585 cmd->opcode = O_IP_SRC_ME; 2586 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 2587 cmd->opcode = O_IP_SRC; 2588 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */ 2589 cmd->opcode = O_IP_SRC_MASK; 2590 return cmd; 2591 } 2592 2593 static ipfw_insn * 2594 add_dstip(ipfw_insn *cmd, char *av) 2595 { 2596 fill_ip((ipfw_insn_ip *)cmd, av); 2597 if (cmd->opcode == O_IP_DST_SET) /* set */ 2598 ; 2599 else if (cmd->opcode == O_IP_DST_TABLE) /* table */ 2600 ; 2601 else if (cmd->opcode == O_IP_DST_IFIP) /* iface's IP */ 2602 ; 2603 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 2604 cmd->opcode = O_IP_DST_ME; 2605 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 2606 cmd->opcode = O_IP_DST; 2607 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */ 2608 cmd->opcode = O_IP_DST_MASK; 2609 return cmd; 2610 } 2611 2612 static ipfw_insn * 2613 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 2614 { 2615 if (!strncmp(av, "any", strlen(av))) { 2616 return NULL; 2617 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 2618 /* XXX todo: check that we have a protocol with ports */ 2619 cmd->opcode = opcode; 2620 return cmd; 2621 } 2622 return NULL; 2623 } 2624 2625 static void 2626 fill_rdr(ipfw_insn *cmd, char *av) 2627 { 2628 ipfw_insn_rdr *c = (ipfw_insn_rdr *)cmd; 2629 char *p; 2630 2631 cmd->opcode = O_REDIRECT; 2632 cmd->len = F_INSN_SIZE(ipfw_insn_rdr); 2633 cmd->arg1 = 0; 2634 c->addr.s_addr = INADDR_ANY; 2635 c->port = 0; 2636 c->set = UINT16_MAX; 2637 2638 p = strchr(av, ','); 2639 if (p == NULL) 2640 p = strchr(av, ':'); 2641 if (p != NULL) 2642 *p = '\0'; 2643 lookup_host(av, &c->addr); 2644 2645 if (p != NULL && *(p + 1) != '\0') { 2646 char *ep; 2647 2648 c->port = strtoul(p + 1, &ep, 0); 2649 if (*ep != '\0') 2650 errx(EX_DATAERR, "illegal port %s", p + 1); 2651 c->port = htons(c->port); 2652 } 2653 } 2654 2655 /* 2656 * Parse arguments and assemble the microinstructions which make up a rule. 2657 * Rules are added into the 'rulebuf' and then copied in the correct order 2658 * into the actual rule. 2659 * 2660 * The syntax for a rule starts with the action, followed by an 2661 * optional log action, and the various match patterns. 2662 * In the assembled microcode, the first opcode must be a O_PROBE_STATE 2663 * (generated if the rule includes a keep-state option), then the 2664 * various match patterns, the "log" action, and the actual action. 2665 * 2666 */ 2667 static void 2668 add(int ac, char *av[]) 2669 { 2670 /* 2671 * rules are added into the 'rulebuf' and then copied in 2672 * the correct order into the actual rule. 2673 * Some things that need to go out of order (prob, action etc.) 2674 * go into actbuf[]. 2675 */ 2676 static uint32_t rulebuf[IPFW_RULE_SIZE_MAX]; 2677 static uint32_t actbuf[IPFW_RULE_SIZE_MAX]; 2678 static uint32_t cmdbuf[IPFW_RULE_SIZE_MAX]; 2679 2680 ipfw_insn *src, *dst, *cmd, *action, *prev = NULL; 2681 ipfw_insn *first_cmd; /* first match pattern */ 2682 2683 struct ipfw_ioc_rule *rule; 2684 2685 /* 2686 * various flags used to record that we entered some fields. 2687 */ 2688 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 2689 2690 int i; 2691 2692 int open_par = 0; /* open parenthesis ( */ 2693 2694 int has_dstport = 0; 2695 int has_recv = 0; 2696 2697 /* proto is here because it is used to fetch ports */ 2698 u_char proto = IPPROTO_IP; /* default protocol */ 2699 2700 double match_prob = 1; /* match probability, default is always match */ 2701 2702 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 2703 bzero(cmdbuf, sizeof(cmdbuf)); 2704 bzero(rulebuf, sizeof(rulebuf)); 2705 2706 rule = (struct ipfw_ioc_rule *)rulebuf; 2707 cmd = (ipfw_insn *)cmdbuf; 2708 action = (ipfw_insn *)actbuf; 2709 2710 av++; ac--; 2711 2712 /* [rule N] -- Rule number optional */ 2713 if (ac && isdigit(**av)) { 2714 rule->rulenum = atoi(*av); 2715 av++; 2716 ac--; 2717 } 2718 2719 /* [set N] -- set number (0..30), optional */ 2720 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) { 2721 int set = strtoul(av[1], NULL, 10); 2722 if (set < 0 || set > 30) 2723 errx(EX_DATAERR, "illegal set %s", av[1]); 2724 rule->set = set; 2725 av += 2; ac -= 2; 2726 } 2727 2728 /* [prob D] -- match probability, optional */ 2729 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) { 2730 match_prob = strtod(av[1], NULL); 2731 2732 if (match_prob <= 0 || match_prob > 1) 2733 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 2734 av += 2; ac -= 2; 2735 } 2736 2737 /* action -- mandatory */ 2738 NEED1("missing action"); 2739 i = match_token(rule_actions, *av); 2740 ac--; av++; 2741 action->len = 1; /* default */ 2742 switch(i) { 2743 case TOK_CHECKSTATE: 2744 have_state = action; 2745 action->opcode = O_CHECK_STATE; 2746 break; 2747 2748 case TOK_ACCEPT: 2749 action->opcode = O_ACCEPT; 2750 break; 2751 2752 case TOK_DEFRAG: 2753 action->opcode = O_DEFRAG; 2754 action->arg1 = 0; 2755 break; 2756 2757 case TOK_DENY: 2758 action->opcode = O_DENY; 2759 action->arg1 = 0; 2760 break; 2761 2762 case TOK_REJECT: 2763 action->opcode = O_REJECT; 2764 action->arg1 = ICMP_UNREACH_HOST; 2765 break; 2766 2767 case TOK_RESET: 2768 action->opcode = O_REJECT; 2769 action->arg1 = ICMP_REJECT_RST; 2770 break; 2771 2772 case TOK_UNREACH: 2773 action->opcode = O_REJECT; 2774 NEED1("missing reject code"); 2775 fill_reject_code(&action->arg1, *av); 2776 ac--; av++; 2777 break; 2778 2779 case TOK_COUNT: 2780 action->opcode = O_COUNT; 2781 break; 2782 2783 case TOK_QUEUE: 2784 case TOK_PIPE: 2785 action->len = F_INSN_SIZE(ipfw_insn_pipe); 2786 case TOK_SKIPTO: 2787 if (i == TOK_QUEUE) 2788 action->opcode = O_QUEUE; 2789 else if (i == TOK_PIPE) 2790 action->opcode = O_PIPE; 2791 else if (i == TOK_SKIPTO) 2792 action->opcode = O_SKIPTO; 2793 NEED1("missing skipto/pipe/queue number"); 2794 action->arg1 = strtoul(*av, NULL, 10); 2795 av++; ac--; 2796 break; 2797 2798 case TOK_DIVERT: 2799 case TOK_TEE: 2800 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE; 2801 NEED1("missing divert/tee port"); 2802 action->arg1 = strtoul(*av, NULL, 0); 2803 if (action->arg1 == 0) { 2804 struct servent *serv; 2805 setservent(1); 2806 serv = getservbyname(av[0], "divert"); 2807 if (serv != NULL) 2808 action->arg1 = ntohs(serv->s_port); 2809 else 2810 errx(EX_DATAERR, "illegal divert/tee port"); 2811 } 2812 ac--; av++; 2813 break; 2814 2815 case TOK_FORWARD: { 2816 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 2817 char *st, *end; 2818 2819 NEED1("missing forward address[:port]"); 2820 2821 action->opcode = O_FORWARD_IP; 2822 action->len = F_INSN_SIZE(ipfw_insn_sa); 2823 2824 p->sa.sin_len = sizeof(struct sockaddr_in); 2825 p->sa.sin_family = AF_INET; 2826 p->sa.sin_port = 0; 2827 /* 2828 * locate the address-port separator (':' or ',') 2829 */ 2830 st = strchr(*av, ':'); 2831 if (st == NULL) 2832 st = strchr(*av, ','); 2833 if (st != NULL) { 2834 *(st++) = '\0'; 2835 i = strtoport(st, &end, 0 /* base */, 0 /* proto */); 2836 if (st == end) 2837 errx(EX_DATAERR, 2838 "illegal forwarding port ``%s''", st); 2839 p->sa.sin_port = (u_short)i; 2840 } 2841 lookup_host(*av, &(p->sa.sin_addr)); 2842 } 2843 ac--; av++; 2844 break; 2845 2846 default: 2847 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 2848 } 2849 action = next_cmd(action); 2850 2851 /* 2852 * [log [logamount N]] -- log, optional 2853 * 2854 * If exists, it goes first in the cmdbuf, but then it is 2855 * skipped in the copy section to the end of the buffer. 2856 */ 2857 if (ac && !strncmp(*av, "log", strlen(*av))) { 2858 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 2859 2860 cmd->len = F_INSN_SIZE(ipfw_insn_log); 2861 cmd->opcode = O_LOG; 2862 av++; ac--; 2863 if (ac && !strncmp(*av, "logamount", strlen(*av))) { 2864 ac--; av++; 2865 NEED1("logamount requires argument"); 2866 c->max_log = atoi(*av); 2867 ac--; av++; 2868 } 2869 cmd = next_cmd(cmd); 2870 } 2871 2872 if (have_state) /* must be a check-state, we are done */ 2873 goto done; 2874 2875 #define OR_START(target) \ 2876 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 2877 if (open_par) \ 2878 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 2879 prev = NULL; \ 2880 open_par = 1; \ 2881 if ( (av[0])[1] == '\0') { \ 2882 ac--; av++; \ 2883 } else \ 2884 (*av)++; \ 2885 } \ 2886 target: \ 2887 2888 2889 #define CLOSE_PAR \ 2890 if (open_par) { \ 2891 if (ac && ( \ 2892 !strncmp(*av, ")", strlen(*av)) || \ 2893 !strncmp(*av, "}", strlen(*av)) )) { \ 2894 prev = NULL; \ 2895 open_par = 0; \ 2896 ac--; av++; \ 2897 } else \ 2898 errx(EX_USAGE, "missing \")\"\n"); \ 2899 } 2900 2901 #define NOT_BLOCK \ 2902 if (ac && !strncmp(*av, "not", strlen(*av))) { \ 2903 if (cmd->len & F_NOT) \ 2904 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 2905 cmd->len |= F_NOT; \ 2906 ac--; av++; \ 2907 } 2908 2909 #define OR_BLOCK(target) \ 2910 if (ac && !strncmp(*av, "or", strlen(*av))) { \ 2911 if (prev == NULL || open_par == 0) \ 2912 errx(EX_DATAERR, "invalid OR block"); \ 2913 prev->len |= F_OR; \ 2914 ac--; av++; \ 2915 goto target; \ 2916 } \ 2917 CLOSE_PAR; 2918 2919 first_cmd = cmd; 2920 2921 #if 0 2922 /* 2923 * MAC addresses, optional. 2924 * If we have this, we skip the part "proto from src to dst" 2925 * and jump straight to the option parsing. 2926 */ 2927 NOT_BLOCK; 2928 NEED1("missing protocol"); 2929 if (!strncmp(*av, "MAC", strlen(*av)) || 2930 !strncmp(*av, "mac", strlen(*av))) { 2931 ac--; av++; /* the "MAC" keyword */ 2932 add_mac(cmd, ac, av); /* exits in case of errors */ 2933 cmd = next_cmd(cmd); 2934 ac -= 2; av += 2; /* dst-mac and src-mac */ 2935 NOT_BLOCK; 2936 NEED1("missing mac type"); 2937 if (add_mactype(cmd, ac, av[0])) 2938 cmd = next_cmd(cmd); 2939 ac--; av++; /* any or mac-type */ 2940 goto read_options; 2941 } 2942 #endif 2943 2944 /* 2945 * protocol, mandatory 2946 */ 2947 OR_START(get_proto); 2948 NOT_BLOCK; 2949 NEED1("missing protocol"); 2950 if (add_proto(cmd, *av)) { 2951 av++; ac--; 2952 if (F_LEN(cmd) == 0) /* plain IP */ 2953 proto = 0; 2954 else { 2955 proto = cmd->arg1; 2956 prev = cmd; 2957 cmd = next_cmd(cmd); 2958 } 2959 } else if (first_cmd != cmd) { 2960 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 2961 } else 2962 goto read_options; 2963 OR_BLOCK(get_proto); 2964 2965 /* 2966 * "from", mandatory 2967 */ 2968 if (!ac || strncmp(*av, "from", strlen(*av))) 2969 errx(EX_USAGE, "missing ``from''"); 2970 ac--; av++; 2971 2972 /* 2973 * source IP, mandatory 2974 */ 2975 OR_START(source_ip); 2976 NOT_BLOCK; /* optional "not" */ 2977 NEED1("missing source address"); 2978 if (add_srcip(cmd, *av)) { 2979 ac--; av++; 2980 if (F_LEN(cmd) != 0) { /* ! any */ 2981 prev = cmd; 2982 cmd = next_cmd(cmd); 2983 } 2984 } 2985 OR_BLOCK(source_ip); 2986 2987 /* 2988 * source ports, optional 2989 */ 2990 NOT_BLOCK; /* optional "not" */ 2991 if (ac) { 2992 if (!strncmp(*av, "any", strlen(*av)) || 2993 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 2994 ac--; av++; 2995 if (F_LEN(cmd) != 0) 2996 cmd = next_cmd(cmd); 2997 } 2998 } 2999 3000 /* 3001 * "to", mandatory 3002 */ 3003 if (!ac || strncmp(*av, "to", strlen(*av))) 3004 errx(EX_USAGE, "missing ``to''"); 3005 av++; ac--; 3006 3007 /* 3008 * destination, mandatory 3009 */ 3010 OR_START(dest_ip); 3011 NOT_BLOCK; /* optional "not" */ 3012 NEED1("missing dst address"); 3013 if (add_dstip(cmd, *av)) { 3014 ac--; av++; 3015 if (F_LEN(cmd) != 0) { /* ! any */ 3016 prev = cmd; 3017 cmd = next_cmd(cmd); 3018 } 3019 } 3020 OR_BLOCK(dest_ip); 3021 3022 /* 3023 * dest. ports, optional 3024 */ 3025 NOT_BLOCK; /* optional "not" */ 3026 if (ac) { 3027 if (!strncmp(*av, "any", strlen(*av)) || 3028 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 3029 ac--; av++; 3030 if (F_LEN(cmd) != 0) { 3031 has_dstport = 1; 3032 cmd = next_cmd(cmd); 3033 } 3034 } 3035 } 3036 3037 read_options: 3038 if (ac && first_cmd == cmd) { 3039 /* 3040 * nothing specified so far, store in the rule to ease 3041 * printout later. 3042 */ 3043 rule->usr_flags = IPFW_USR_F_NORULE; 3044 } 3045 prev = NULL; 3046 while (ac) { 3047 char *s1; 3048 ipfw_insn_u32 *cmd32; /* alias for cmd */ 3049 3050 s1 = *av; 3051 cmd32 = (ipfw_insn_u32 *)cmd; 3052 3053 if (*s1 == '!') { /* alternate syntax for NOT */ 3054 if (cmd->len & F_NOT) 3055 errx(EX_USAGE, "double \"not\" not allowed\n"); 3056 cmd->len = F_NOT; 3057 s1++; 3058 } 3059 i = match_token(rule_options, s1); 3060 ac--; av++; 3061 switch(i) { 3062 case TOK_NOT: 3063 if (cmd->len & F_NOT) 3064 errx(EX_USAGE, "double \"not\" not allowed\n"); 3065 cmd->len = F_NOT; 3066 break; 3067 3068 case TOK_OR: 3069 if (open_par == 0 || prev == NULL) 3070 errx(EX_USAGE, "invalid \"or\" block\n"); 3071 prev->len |= F_OR; 3072 break; 3073 3074 case TOK_STARTBRACE: 3075 if (open_par) 3076 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 3077 open_par = 1; 3078 break; 3079 3080 case TOK_ENDBRACE: 3081 if (!open_par) 3082 errx(EX_USAGE, "+missing \")\"\n"); 3083 open_par = 0; 3084 prev = NULL; 3085 break; 3086 3087 case TOK_IN: 3088 fill_cmd(cmd, O_IN, 0, 0); 3089 break; 3090 3091 case TOK_OUT: 3092 cmd->len ^= F_NOT; /* toggle F_NOT */ 3093 fill_cmd(cmd, O_IN, 0, 0); 3094 break; 3095 3096 case TOK_FRAG: 3097 fill_cmd(cmd, O_FRAG, 0, 0); 3098 break; 3099 3100 case TOK_IPFRAG: 3101 fill_cmd(cmd, O_IPFRAG, 0, 0); 3102 break; 3103 3104 case TOK_LAYER2: 3105 fill_cmd(cmd, O_LAYER2, 0, 0); 3106 break; 3107 3108 case TOK_XMIT: 3109 case TOK_RECV: 3110 case TOK_VIA: 3111 NEED1("recv, xmit, via require interface name" 3112 " or address"); 3113 fill_iface((ipfw_insn_if *)cmd, av[0]); 3114 ac--; av++; 3115 if (F_LEN(cmd) == 0) /* not a valid address */ 3116 break; 3117 if (i == TOK_XMIT) 3118 cmd->opcode = O_XMIT; 3119 else if (i == TOK_RECV) { 3120 cmd->opcode = O_RECV; 3121 has_recv = 1; 3122 } else if (i == TOK_VIA) 3123 cmd->opcode = O_VIA; 3124 break; 3125 3126 case TOK_ICMPCODES: 3127 NEED1("icmpcodes requires list of codes"); 3128 fill_icmp(O_ICMPCODE, (ipfw_insn_u32 *)cmd, *av); 3129 av++; ac--; 3130 break; 3131 3132 case TOK_ICMPTYPES: 3133 NEED1("icmptypes requires list of types"); 3134 fill_icmp(O_ICMPTYPE, (ipfw_insn_u32 *)cmd, *av); 3135 av++; ac--; 3136 break; 3137 3138 case TOK_IPTTL: 3139 NEED1("ipttl requires TTL"); 3140 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 3141 ac--; av++; 3142 break; 3143 3144 case TOK_IPID: 3145 NEED1("ipid requires length"); 3146 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 3147 ac--; av++; 3148 break; 3149 3150 case TOK_IPLEN: 3151 NEED1("iplen requires length"); 3152 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 3153 ac--; av++; 3154 break; 3155 3156 case TOK_IPVER: 3157 NEED1("ipver requires version"); 3158 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 3159 ac--; av++; 3160 break; 3161 3162 case TOK_IPPRECEDENCE: 3163 NEED1("ipprecedence requires value"); 3164 fill_cmd(cmd, O_IPPRECEDENCE, 0, 3165 (strtoul(*av, NULL, 0) & 7) << 5); 3166 ac--; av++; 3167 break; 3168 3169 case TOK_IPOPTS: 3170 NEED1("missing argument for ipoptions"); 3171 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 3172 ac--; av++; 3173 break; 3174 3175 case TOK_IPTOS: 3176 NEED1("missing argument for iptos"); 3177 fill_flags(cmd, O_IPTOS, f_iptos, *av); 3178 ac--; av++; 3179 break; 3180 3181 case TOK_UID: 3182 NEED1("uid requires argument"); 3183 { 3184 char *end; 3185 uid_t uid; 3186 struct passwd *pwd; 3187 3188 cmd->opcode = O_UID; 3189 uid = strtoul(*av, &end, 0); 3190 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 3191 if (pwd == NULL) 3192 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 3193 cmd32->d[0] = pwd->pw_uid; 3194 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3195 ac--; av++; 3196 } 3197 break; 3198 3199 case TOK_GID: 3200 NEED1("gid requires argument"); 3201 { 3202 char *end; 3203 gid_t gid; 3204 struct group *grp; 3205 3206 cmd->opcode = O_GID; 3207 gid = strtoul(*av, &end, 0); 3208 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 3209 if (grp == NULL) 3210 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 3211 cmd32->d[0] = grp->gr_gid; 3212 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3213 ac--; av++; 3214 } 3215 break; 3216 3217 case TOK_ESTAB: 3218 fill_cmd(cmd, O_ESTAB, 0, 0); 3219 break; 3220 3221 case TOK_SETUP: 3222 fill_cmd(cmd, O_TCPFLAGS, 0, 3223 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 3224 break; 3225 3226 case TOK_TCPOPTS: 3227 NEED1("missing argument for tcpoptions"); 3228 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 3229 ac--; av++; 3230 break; 3231 3232 case TOK_TCPSEQ: 3233 case TOK_TCPACK: 3234 NEED1("tcpseq/tcpack requires argument"); 3235 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3236 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 3237 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 3238 ac--; av++; 3239 break; 3240 3241 case TOK_TCPWIN: 3242 NEED1("tcpwin requires length"); 3243 fill_cmd(cmd, O_TCPWIN, 0, 3244 htons(strtoul(*av, NULL, 0))); 3245 ac--; av++; 3246 break; 3247 3248 case TOK_TCPFLAGS: 3249 NEED1("missing argument for tcpflags"); 3250 cmd->opcode = O_TCPFLAGS; 3251 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 3252 ac--; av++; 3253 break; 3254 3255 case TOK_REDIRECT: 3256 if (open_par) 3257 errx(EX_USAGE, "rdr cannot be part " 3258 "of an or block"); 3259 if (have_state) { 3260 errx(EX_USAGE, "only one of rdr, keep-state " 3261 "and limit is allowed"); 3262 } 3263 have_state = cmd; 3264 NEED1("rdr needs address and port"); 3265 fill_rdr(cmd, *av); 3266 ac--; av++; 3267 break; 3268 3269 case TOK_KEEPSTATE: 3270 if (open_par) 3271 errx(EX_USAGE, "keep-state cannot be part " 3272 "of an or block"); 3273 if (have_state) { 3274 errx(EX_USAGE, "only one of rdr, keep-state " 3275 "and limit is allowed"); 3276 } 3277 have_state = cmd; 3278 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 3279 break; 3280 3281 case TOK_LIMIT: 3282 if (open_par) 3283 errx(EX_USAGE, "limit cannot be part " 3284 "of an or block"); 3285 if (have_state) { 3286 errx(EX_USAGE, "only one of rdr, keep-state " 3287 "and limit is allowed"); 3288 } 3289 NEED1("limit needs mask and # of connections"); 3290 have_state = cmd; 3291 { 3292 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 3293 3294 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 3295 cmd->opcode = O_LIMIT; 3296 c->limit_mask = 0; 3297 c->conn_limit = 0; 3298 for (; ac >1 ;) { 3299 int val; 3300 3301 val = match_token(limit_masks, *av); 3302 if (val <= 0) 3303 break; 3304 c->limit_mask |= val; 3305 ac--; av++; 3306 } 3307 c->conn_limit = atoi(*av); 3308 if (c->conn_limit == 0) 3309 errx(EX_USAGE, "limit: limit must be >0"); 3310 if (c->limit_mask == 0) 3311 errx(EX_USAGE, "missing limit mask"); 3312 ac--; av++; 3313 } 3314 break; 3315 3316 case TOK_PROTO: 3317 NEED1("missing protocol"); 3318 if (add_proto(cmd, *av)) { 3319 proto = cmd->arg1; 3320 ac--; av++; 3321 } else 3322 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 3323 break; 3324 3325 case TOK_SRCIP: 3326 NEED1("missing source IP"); 3327 if (add_srcip(cmd, *av)) { 3328 ac--; av++; 3329 } 3330 break; 3331 3332 case TOK_DSTIP: 3333 NEED1("missing destination IP"); 3334 if (add_dstip(cmd, *av)) { 3335 ac--; av++; 3336 } 3337 break; 3338 3339 case TOK_SRCPORT: 3340 NEED1("missing source port"); 3341 if (!strncmp(*av, "any", strlen(*av)) || 3342 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 3343 ac--; av++; 3344 } else 3345 errx(EX_DATAERR, "invalid source port %s", *av); 3346 break; 3347 3348 case TOK_DSTPORT: 3349 NEED1("missing destination port"); 3350 if (!strncmp(*av, "any", strlen(*av)) || 3351 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 3352 if (F_LEN(cmd) != 0) 3353 has_dstport =1; 3354 ac--; av++; 3355 } else 3356 errx(EX_DATAERR, "invalid destination port %s", 3357 *av); 3358 break; 3359 3360 case TOK_MAC: 3361 if (ac < 2) 3362 errx(EX_USAGE, "MAC dst-mac src-mac"); 3363 if (add_mac(cmd, ac, av)) { 3364 ac -= 2; av += 2; 3365 } 3366 break; 3367 3368 case TOK_MACTYPE: 3369 NEED1("missing mac type"); 3370 if (!add_mactype(cmd, ac, *av)) 3371 errx(EX_DATAERR, "invalid mac type %s", *av); 3372 ac--; av++; 3373 break; 3374 3375 default: 3376 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s1); 3377 } 3378 if (F_LEN(cmd) > 0) { /* prepare to advance */ 3379 prev = cmd; 3380 cmd = next_cmd(cmd); 3381 } 3382 } 3383 3384 done: 3385 /* 3386 * Now copy stuff into the rule. 3387 * If we have a keep-state option, the first instruction 3388 * must be a PROBE_STATE (which is generated here). 3389 * If we have a LOG option, it was stored as the first command, 3390 * and now must be moved to the top of the action part. 3391 */ 3392 dst = (ipfw_insn *)rule->cmd; 3393 3394 /* 3395 * First thing to write into the command stream is the match probability. 3396 */ 3397 if (match_prob != 1) { /* 1 means always match */ 3398 dst->opcode = O_PROB; 3399 dst->len = 2; 3400 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 3401 dst += dst->len; 3402 } 3403 3404 /* 3405 * generate O_PROBE_STATE if necessary 3406 */ 3407 if (have_state && have_state->opcode != O_CHECK_STATE) { 3408 fill_cmd(dst, O_PROBE_STATE, 0, 0); 3409 dst = next_cmd(dst); 3410 } 3411 /* 3412 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_REDIRECT 3413 */ 3414 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 3415 i = F_LEN(src); 3416 3417 switch (src->opcode) { 3418 case O_LOG: 3419 case O_KEEP_STATE: 3420 case O_LIMIT: 3421 case O_REDIRECT: 3422 break; 3423 default: 3424 bcopy(src, dst, i * sizeof(u_int32_t)); 3425 dst += i; 3426 } 3427 } 3428 3429 /* 3430 * put back the have_state command as last opcode 3431 */ 3432 if (have_state && have_state->opcode != O_CHECK_STATE) { 3433 i = F_LEN(have_state); 3434 bcopy(have_state, dst, i * sizeof(u_int32_t)); 3435 dst += i; 3436 3437 if (have_state->opcode == O_REDIRECT && 3438 (!has_dstport || !has_recv)) 3439 errx(EX_USAGE, "missing \'dst-port\' or \'recv\'"); 3440 } 3441 /* 3442 * start action section 3443 */ 3444 rule->act_ofs = dst - rule->cmd; 3445 3446 /* 3447 * put back O_LOG if necessary 3448 */ 3449 src = (ipfw_insn *)cmdbuf; 3450 if ( src->opcode == O_LOG ) { 3451 i = F_LEN(src); 3452 bcopy(src, dst, i * sizeof(u_int32_t)); 3453 dst += i; 3454 } 3455 /* 3456 * copy all other actions 3457 */ 3458 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 3459 i = F_LEN(src); 3460 bcopy(src, dst, i * sizeof(u_int32_t)); 3461 dst += i; 3462 } 3463 3464 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd); 3465 i = (uint8_t *)dst - (uint8_t *)rule; 3466 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1) 3467 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 3468 if (!do_quiet) 3469 show_ipfw(rule, 10, 10); 3470 } 3471 3472 static void 3473 zero(int ac, char *av[]) 3474 { 3475 int rulenum; 3476 int failed = EX_OK; 3477 3478 av++; ac--; 3479 3480 if (!ac) { 3481 /* clear all entries */ 3482 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0) 3483 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO"); 3484 if (!do_quiet) 3485 printf("Accounting cleared.\n"); 3486 3487 return; 3488 } 3489 3490 while (ac) { 3491 /* Rule number */ 3492 if (isdigit(**av)) { 3493 rulenum = atoi(*av); 3494 av++; 3495 ac--; 3496 if (setsockopt(s, IPPROTO_IP, 3497 IP_FW_ZERO, &rulenum, sizeof rulenum)) { 3498 warn("rule %u: setsockopt(IP_FW_ZERO)", 3499 rulenum); 3500 failed = EX_UNAVAILABLE; 3501 } else if (!do_quiet) 3502 printf("Entry %d cleared\n", rulenum); 3503 } else { 3504 errx(EX_USAGE, "invalid rule number ``%s''", *av); 3505 } 3506 } 3507 if (failed != EX_OK) 3508 exit(failed); 3509 } 3510 3511 static void 3512 resetlog(int ac, char *av[]) 3513 { 3514 int rulenum; 3515 int failed = EX_OK; 3516 3517 av++; ac--; 3518 3519 if (!ac) { 3520 /* clear all entries */ 3521 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0) 3522 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)"); 3523 if (!do_quiet) 3524 printf("Logging counts reset.\n"); 3525 3526 return; 3527 } 3528 3529 while (ac) { 3530 /* Rule number */ 3531 if (isdigit(**av)) { 3532 rulenum = atoi(*av); 3533 av++; 3534 ac--; 3535 if (setsockopt(s, IPPROTO_IP, 3536 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) { 3537 warn("rule %u: setsockopt(IP_FW_RESETLOG)", 3538 rulenum); 3539 failed = EX_UNAVAILABLE; 3540 } else if (!do_quiet) 3541 printf("Entry %d logging count reset\n", 3542 rulenum); 3543 } else { 3544 errx(EX_DATAERR, "invalid rule number ``%s''", *av); 3545 } 3546 } 3547 if (failed != EX_OK) 3548 exit(failed); 3549 } 3550 3551 static void 3552 flush(void) 3553 { 3554 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 3555 3556 if (!do_force && !do_quiet) { /* need to ask user */ 3557 int c; 3558 3559 printf("Are you sure? [yn] "); 3560 fflush(stdout); 3561 do { 3562 c = toupper(getc(stdin)); 3563 while (c != '\n' && getc(stdin) != '\n') 3564 if (feof(stdin)) 3565 return; /* and do not flush */ 3566 } while (c != 'Y' && c != 'N'); 3567 printf("\n"); 3568 if (c == 'N') /* user said no */ 3569 return; 3570 } 3571 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0) 3572 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 3573 do_pipe ? "DUMMYNET" : "FW"); 3574 if (!do_quiet) 3575 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 3576 } 3577 3578 static void 3579 table_create(int ac, char **av) 3580 { 3581 struct ipfw_ioc_table tbl; 3582 char *eptr; 3583 3584 ac--; 3585 av++; 3586 3587 if (ac == 0) 3588 errx(EX_DATAERR, "missing table id"); 3589 3590 memset(&tbl, 0, sizeof(tbl)); 3591 tbl.tableid = strtoul(*av, &eptr, 0); 3592 if (*eptr != '\0') 3593 errx(EX_DATAERR, "invalid table id %s", *av); 3594 if (setsockopt(s, IPPROTO_IP, IP_FW_TBL_CREATE, &tbl, sizeof(tbl)) < 0) 3595 err(EX_UNAVAILABLE, "setsockopt(IP_FW_TBL_CREATE)"); 3596 if (!do_quiet) 3597 printf("Created table %d\n", tbl.tableid); 3598 } 3599 3600 static void 3601 table_flush(int ac, char **av, int opt) 3602 { 3603 struct ipfw_ioc_table tbl; 3604 char *eptr; 3605 3606 ac--; 3607 av++; 3608 3609 memset(&tbl, 0, sizeof(tbl)); 3610 3611 if (ac == 0) { 3612 if (opt == IP_FW_TBL_FLUSH) { 3613 /* Flush all tables */ 3614 tbl.tableid = -1; 3615 goto flush; 3616 } 3617 errx(EX_DATAERR, "missing table id"); 3618 } 3619 3620 tbl.tableid = strtoul(*av, &eptr, 0); 3621 if (*eptr != '\0') 3622 errx(EX_DATAERR, "invalid table id %s", *av); 3623 3624 flush: 3625 if (!do_force && !do_quiet) { /* need to ask user */ 3626 int c; 3627 3628 printf("Are you sure? [yn] "); 3629 fflush(stdout); 3630 do { 3631 c = toupper(getc(stdin)); 3632 while (c != '\n' && getc(stdin) != '\n') 3633 if (feof(stdin)) 3634 return; /* and do not flush */ 3635 } while (c != 'Y' && c != 'N'); 3636 printf("\n"); 3637 if (c == 'N') /* user said no */ 3638 return; 3639 } 3640 3641 if (setsockopt(s, IPPROTO_IP, opt, &tbl, sizeof(tbl)) < 0) { 3642 err(EX_UNAVAILABLE, "setsockopt(IP_FW_TBL_%s)", 3643 opt == IP_FW_TBL_FLUSH ? "FLUSH" : "DESTROY"); 3644 } 3645 if (!do_quiet) { 3646 if (tbl.tableid >= 0) { 3647 printf("%sed table %d\n", 3648 opt == IP_FW_TBL_FLUSH ? "Flush" : "Destroy", 3649 tbl.tableid); 3650 } else { 3651 printf("Flushed all tables\n"); 3652 } 3653 } 3654 } 3655 3656 static void 3657 table_list(void) 3658 { 3659 struct ipfw_ioc_tbllist *list; 3660 int table_max, i; 3661 size_t len; 3662 socklen_t len1; 3663 3664 len = sizeof(table_max); 3665 if (sysctlbyname("net.inet.ip.fw.table_max", &table_max, &len, 3666 NULL, 0) < 0) 3667 err(EX_UNAVAILABLE, "sysctl net.inet.ip.fw.table_max failed"); 3668 3669 len1 = __offsetof(struct ipfw_ioc_tbllist, tables[table_max]); 3670 list = malloc(len1); 3671 list->tableid = -1; 3672 3673 if (getsockopt(s, IPPROTO_IP, IP_FW_TBL_GET, list, &len1) < 0) 3674 err(EX_UNAVAILABLE, "getsockopt(IP_FW_TBL_GET)"); 3675 3676 for (i = 0; i < list->tablecnt; ++i) 3677 printf("%u\n", list->tables[i]); 3678 } 3679 3680 /* XXX copied from route(8) */ 3681 static void 3682 inet_makenetandmask(in_addr_t net, struct sockaddr_in *in, 3683 struct sockaddr_in *in_mask, int bits) 3684 { 3685 in_addr_t addr, mask = 0; 3686 char *cp; 3687 3688 /* 3689 * XXX: This approach unable to handle 0.0.0.1/32 correctly 3690 * as inet_network() converts 0.0.0.1 and 1 equally. 3691 */ 3692 if (net <= 0xff) 3693 addr = net << IN_CLASSA_NSHIFT; 3694 else if (net <= 0xffff) 3695 addr = net << IN_CLASSB_NSHIFT; 3696 else if (net <= 0xffffff) 3697 addr = net << IN_CLASSC_NSHIFT; 3698 else 3699 addr = net; 3700 3701 if (bits != 0) 3702 mask = 0xffffffff << (32 - bits); 3703 else if (net == 0) 3704 mask = 0; 3705 else if (IN_CLASSA(addr)) 3706 mask = IN_CLASSA_NET; 3707 else if (IN_CLASSB(addr)) 3708 mask = IN_CLASSB_NET; 3709 else if (IN_CLASSC(addr)) 3710 mask = IN_CLASSC_NET; 3711 else if (IN_MULTICAST(addr)) 3712 mask = IN_CLASSD_NET; 3713 else 3714 mask = 0xffffffff; 3715 3716 in->sin_family = AF_INET; 3717 in->sin_len = sizeof(struct sockaddr_in); 3718 in->sin_addr.s_addr = htonl(addr); 3719 3720 if (mask != 0xffffffff) { 3721 in_mask->sin_addr.s_addr = htonl(mask); 3722 cp = (char *)(&in_mask->sin_addr + 1); 3723 while (*--cp == 0 && cp > (char *)in_mask) 3724 ; 3725 in_mask->sin_len = 1 + cp - (char *)in_mask; 3726 } 3727 } 3728 3729 static void 3730 table_alt(int ac, char **av, int opt) 3731 { 3732 struct ipfw_ioc_tblcont ent; 3733 struct ipfw_ioc_tblent *te; 3734 char *eptr; 3735 3736 --ac; 3737 ++av; 3738 if (ac == 0) 3739 errx(EX_DATAERR, "missing table id"); 3740 3741 memset(&ent, 0, sizeof(ent)); 3742 ent.tableid = strtoul(*av, &eptr, 0); 3743 ent.entcnt = 1; 3744 te = &ent.ent[0]; 3745 if (*eptr != '\0') 3746 errx(EX_DATAERR, "invalid table id %s", *av); 3747 3748 --ac; 3749 ++av; 3750 if (ac == 0) 3751 errx(EX_DATAERR, "missing addresses"); 3752 3753 while (ac > 0) { 3754 char *q; 3755 3756 q = strchr(*av, '/'); 3757 if (q != NULL) { 3758 in_addr_t val; 3759 int bits; 3760 3761 *q = '\0'; 3762 val = inet_network(*av); 3763 *q = '/'; 3764 if (val == INADDR_NONE) { 3765 fflush(stdout); 3766 errx(EX_DATAERR, "invalid address %s", *av); 3767 } 3768 3769 bits = strtoul(q + 1, &eptr, 0); 3770 if (*eptr != '\0') { 3771 fflush(stdout); 3772 errx(EX_DATAERR, "invalid address %s", *av); 3773 } 3774 inet_makenetandmask(val, &te->key, &te->netmask, bits); 3775 } else { 3776 int n; 3777 3778 n = inet_pton(AF_INET, *av, &te->key.sin_addr); 3779 if (n == 0) { 3780 fflush(stdout); 3781 errx(EX_DATAERR, "invalid address %s", *av); 3782 } else if (n < 0) { 3783 fflush(stdout); 3784 err(EX_UNAVAILABLE, "inet_pton failed"); 3785 } 3786 te->key.sin_family = AF_INET; 3787 te->key.sin_len = sizeof(struct sockaddr_in); 3788 } 3789 3790 if (setsockopt(s, IPPROTO_IP, opt, &ent, sizeof(ent)) < 0) { 3791 if (opt == IP_FW_TBL_ADD && errno == EEXIST) { 3792 printf("Failed to add %s to table %d\n", 3793 *av, ent.tableid); 3794 } else if (opt == IP_FW_TBL_DEL && errno == ESRCH) { 3795 printf("Failed to delete %s from table %d\n", 3796 *av, ent.tableid); 3797 } else { 3798 fflush(stdout); 3799 err(EX_UNAVAILABLE, "setsockopt(IP_FW_TBL_%s)", 3800 opt == IP_FW_TBL_ADD ? "ADD" : "DEL"); 3801 } 3802 } else if (!do_quiet) { 3803 printf("%sed %s %s table %d\n", 3804 opt == IP_FW_TBL_ADD ? "Add" : "Delet", *av, 3805 opt == IP_FW_TBL_ADD ? "to" : "from", ent.tableid); 3806 } 3807 3808 --ac; 3809 ++av; 3810 } 3811 } 3812 3813 static void 3814 table_show(int ac, char **av) 3815 { 3816 struct ipfw_ioc_tblcont *cont = NULL; 3817 int tableid, count = 128, i, uwidth = 0, lwidth = 0; 3818 char *eptr; 3819 3820 --ac; 3821 ++av; 3822 if (ac == 0) 3823 errx(EX_DATAERR, "missing table id"); 3824 3825 tableid = strtoul(*av, &eptr, 0); 3826 if (*eptr != '\0') 3827 errx(EX_DATAERR, "invalid table id %s", *av); 3828 3829 for (;;) { 3830 socklen_t len; 3831 3832 len = __offsetof(struct ipfw_ioc_tblcont, ent[count]); 3833 cont = reallocf(cont, len); 3834 cont->tableid = tableid; 3835 3836 if (getsockopt(s, IPPROTO_IP, IP_FW_TBL_GET, cont, &len) < 0) { 3837 if (errno == E2BIG) { 3838 count *= 2; 3839 continue; 3840 } 3841 err(EX_UNAVAILABLE, "getsockopt(IP_FW_TBL_GET)"); 3842 } 3843 break; 3844 } 3845 if (cont->entcnt == 0) 3846 return; 3847 3848 if (do_acct) { 3849 for (i = 0; i < cont->entcnt; ++i) { 3850 int width; 3851 3852 width = snprintf(NULL, 0, "%ju", 3853 (uintmax_t)cont->ent[i].use); 3854 if (width > uwidth) 3855 uwidth = width; 3856 } 3857 } 3858 3859 for (i = 0; i < cont->entcnt; ++i) { 3860 const struct ipfw_ioc_tblent *te = &cont->ent[i]; 3861 char addr[INET_ADDRSTRLEN]; 3862 3863 if (do_acct) 3864 printf("%*ju ", uwidth, (uintmax_t)te->use); 3865 if (do_time) { 3866 char timestr[30]; 3867 3868 if (lwidth == 0) { 3869 time_t t0 = 0; 3870 3871 strcpy(timestr, ctime(&t0)); 3872 *strchr(timestr, '\n') = '\0'; 3873 lwidth = strlen(timestr); 3874 } 3875 if (te->last_used) { 3876 time_t t = _long_to_time(te->last_used); 3877 3878 strcpy(timestr, ctime(&t)); 3879 *strchr(timestr, '\n') = '\0'; 3880 printf("%s ", timestr); 3881 } else { 3882 printf("%*s ", lwidth, " "); 3883 } 3884 } 3885 3886 if (te->netmask.sin_len == 0) { 3887 printf("%s\n", inet_ntop(AF_INET, 3888 &te->key.sin_addr, addr, sizeof(addr))); 3889 } else { 3890 struct sockaddr_in mask; 3891 int b; 3892 3893 memset(&mask, 0, sizeof(mask)); 3894 memcpy(&mask, &te->netmask, 3895 te->netmask.sin_len); 3896 b = ffs(ntohl(te->netmask.sin_addr.s_addr)); 3897 b = 32 - (b - 1); 3898 3899 printf("%s/%d\n", inet_ntop(AF_INET, 3900 &te->key.sin_addr, addr, sizeof(addr)), b); 3901 } 3902 } 3903 } 3904 3905 static void 3906 table_zero(int ac, char **av) 3907 { 3908 struct ipfw_ioc_table tbl; 3909 3910 --ac; 3911 ++av; 3912 3913 memset(&tbl, 0, sizeof(tbl)); 3914 if (ac == 0) { 3915 tbl.tableid = -1; 3916 } else { 3917 char *eptr; 3918 3919 tbl.tableid = strtoul(*av, &eptr, 0); 3920 if (*eptr != '\0') 3921 errx(EX_DATAERR, "invalid table id %s", *av); 3922 } 3923 3924 if (setsockopt(s, IPPROTO_IP, IP_FW_TBL_ZERO, &tbl, sizeof(tbl)) < 0) 3925 err(EX_UNAVAILABLE, "setsockopt(IP_FW_TBL_ZERO)"); 3926 if (!do_quiet) 3927 printf("Accounting cleared\n"); 3928 } 3929 3930 static void 3931 table_expire(int ac, char **av) 3932 { 3933 struct ipfw_ioc_tblexp tbl; 3934 char *eptr; 3935 socklen_t len; 3936 3937 --ac; 3938 ++av; 3939 3940 memset(&tbl, 0, sizeof(tbl)); 3941 if (ac == 0) { 3942 errx(EX_DATAERR, "missing expire time"); 3943 } else if (ac == 1) { 3944 tbl.tableid = -1; 3945 } else { 3946 tbl.tableid = strtoul(*av, &eptr, 0); 3947 if (*eptr != '\0') 3948 errx(EX_DATAERR, "invalid table id %s", *av); 3949 --ac; 3950 ++av; 3951 } 3952 3953 tbl.expire = strtoul(*av, &eptr, 0); 3954 if (*eptr != '\0') 3955 errx(EX_DATAERR, "invalid expire timeout %s", *av); 3956 3957 if (!do_force && !do_quiet) { /* need to ask user */ 3958 int c; 3959 3960 printf("Are you sure? [yn] "); 3961 fflush(stdout); 3962 do { 3963 c = toupper(getc(stdin)); 3964 while (c != '\n' && getc(stdin) != '\n') 3965 if (feof(stdin)) 3966 return; /* and do not flush */ 3967 } while (c != 'Y' && c != 'N'); 3968 printf("\n"); 3969 if (c == 'N') /* user said no */ 3970 return; 3971 } 3972 3973 len = sizeof(tbl); 3974 if (getsockopt(s, IPPROTO_IP, IP_FW_TBL_EXPIRE, &tbl, &len) < 0) 3975 err(EX_UNAVAILABLE, "getsockopt(IP_FW_TBL_EXPIRE)"); 3976 if (!do_quiet) { 3977 printf("Expired %d address%s\n", tbl.expcnt, 3978 (tbl.expcnt == 0 || tbl.expcnt > 1) ? "es" : ""); 3979 } 3980 } 3981 3982 static int 3983 ipfw_main(int ac, char **av) 3984 { 3985 int ch; 3986 3987 if (ac == 1) 3988 show_usage(); 3989 3990 /* Set the force flag for non-interactive processes */ 3991 do_force = !isatty(STDIN_FILENO); 3992 3993 optind = optreset = 1; 3994 while ((ch = getopt(ac, av, "hs:acdefNqStv")) != -1) 3995 switch (ch) { 3996 case 'h': /* help */ 3997 help(); 3998 break; /* NOTREACHED */ 3999 4000 case 's': /* sort */ 4001 do_sort = atoi(optarg); 4002 break; 4003 case 'a': 4004 do_acct = 1; 4005 break; 4006 case 'c': 4007 do_compact = 1; 4008 break; 4009 case 'd': 4010 do_dynamic = 1; 4011 break; 4012 case 'e': 4013 do_expired = 1; 4014 break; 4015 case 'f': 4016 do_force = 1; 4017 break; 4018 case 'N': 4019 do_resolv = 1; 4020 break; 4021 case 'q': 4022 do_quiet = 1; 4023 break; 4024 case 'S': 4025 show_sets = 1; 4026 break; 4027 case 't': 4028 do_time = 1; 4029 break; 4030 case 'v': /* verbose */ 4031 verbose++; 4032 break; 4033 default: 4034 show_usage(); 4035 } 4036 4037 ac -= optind; 4038 av += optind; 4039 NEED1("bad arguments, for usage summary ``ipfw''"); 4040 4041 /* 4042 * Reset do_pipe and do_table. 4043 */ 4044 do_pipe = 0; 4045 do_table = 0; 4046 4047 /* 4048 * optional: pipe, queue or table 4049 */ 4050 if (!strncmp(*av, "pipe", strlen(*av))) { 4051 do_pipe = 1; 4052 ac--; 4053 av++; 4054 } else if (!strncmp(*av, "queue", strlen(*av))) { 4055 do_pipe = 2; 4056 ac--; 4057 av++; 4058 } else if (!strncmp(*av, "table", strlen(*av))) { 4059 do_table = 1; 4060 ac--; 4061 av++; 4062 } 4063 NEED1("missing command"); 4064 4065 /* 4066 * for pipes, queues and table we normally say 'pipe NN config' 4067 * but the code is easier to parse as 'pipe config NN' so we 4068 * swap the two arguments. 4069 */ 4070 if ((do_pipe > 0 || do_table > 0) && ac > 1 && 4071 *av[0] >= '0' && *av[0] <= '9') { 4072 char *p = av[0]; 4073 av[0] = av[1]; 4074 av[1] = p; 4075 } 4076 if (do_table) { 4077 if (!strncmp(*av, "create", strlen(*av))) 4078 table_create(ac, av); 4079 else if (!strncmp(*av, "destroy", strlen(*av))) 4080 table_flush(ac, av, IP_FW_TBL_DESTROY); 4081 else if (!strncmp(*av, "list", strlen(*av))) 4082 table_list(); 4083 else if (!strncmp(*av, "add", strlen(*av))) 4084 table_alt(ac, av, IP_FW_TBL_ADD); 4085 else if (!strncmp(*av, "delete", strlen(*av))) 4086 table_alt(ac, av, IP_FW_TBL_DEL); 4087 else if (!strncmp(*av, "flush", strlen(*av))) 4088 table_flush(ac, av, IP_FW_TBL_FLUSH); 4089 else if (!strncmp(*av, "print", strlen(*av))) 4090 table_show(ac, av); 4091 else if (!strncmp(*av, "show", strlen(*av))) { 4092 do_acct++; 4093 table_show(ac, av); 4094 } else if (!strncmp(*av, "zero", strlen(*av))) 4095 table_zero(ac, av); 4096 else if (!strncmp(*av, "expire", strlen(*av))) 4097 table_expire(ac, av); 4098 else 4099 errx(EX_USAGE, "bad command `%s'", *av); 4100 return 0; 4101 } 4102 if (!strncmp(*av, "add", strlen(*av))) 4103 add(ac, av); 4104 else if (do_pipe && !strncmp(*av, "config", strlen(*av))) 4105 config_pipe(ac, av); 4106 else if (!strncmp(*av, "delete", strlen(*av))) 4107 delete(ac, av); 4108 else if (!strncmp(*av, "flush", strlen(*av))) 4109 flush(); 4110 else if (!strncmp(*av, "zero", strlen(*av))) 4111 zero(ac, av); 4112 else if (!strncmp(*av, "resetlog", strlen(*av))) 4113 resetlog(ac, av); 4114 else if (!strncmp(*av, "print", strlen(*av)) || 4115 !strncmp(*av, "list", strlen(*av))) 4116 list(ac, av); 4117 else if (!strncmp(*av, "enable", strlen(*av))) 4118 sysctl_handler(ac, av, 1); 4119 else if (!strncmp(*av, "disable", strlen(*av))) 4120 sysctl_handler(ac, av, 0); 4121 else if (!strncmp(*av, "set", strlen(*av))) 4122 sets_handler(ac, av); 4123 else if (!strncmp(*av, "show", strlen(*av))) { 4124 do_acct++; 4125 list(ac, av); 4126 } else 4127 errx(EX_USAGE, "bad command `%s'", *av); 4128 return 0; 4129 } 4130 4131 4132 static void 4133 ipfw_readfile(int ac, char *av[]) 4134 { 4135 #define MAX_ARGS 32 4136 #define WHITESP " \t\f\v\n\r" 4137 char buf[BUFSIZ]; 4138 char *a, *p, *args[MAX_ARGS], *cmd = NULL; 4139 char linename[20]; 4140 int i=0, lineno=0, qflag=0, pflag=0, status; 4141 FILE *f = NULL; 4142 pid_t preproc = 0; 4143 int c; 4144 4145 while ((c = getopt(ac, av, "D:U:p:q")) != -1) 4146 switch(c) { 4147 case 'D': 4148 if (!pflag) 4149 errx(EX_USAGE, "-D requires -p"); 4150 if (i > MAX_ARGS - 2) 4151 errx(EX_USAGE, 4152 "too many -D or -U options"); 4153 args[i++] = __DECONST(char *, "-D"); 4154 args[i++] = optarg; 4155 break; 4156 4157 case 'U': 4158 if (!pflag) 4159 errx(EX_USAGE, "-U requires -p"); 4160 if (i > MAX_ARGS - 2) 4161 errx(EX_USAGE, 4162 "too many -D or -U options"); 4163 args[i++] = __DECONST(char *, "-U"); 4164 args[i++] = optarg; 4165 break; 4166 4167 case 'p': 4168 pflag = 1; 4169 cmd = optarg; 4170 args[0] = cmd; 4171 i = 1; 4172 break; 4173 4174 case 'q': 4175 qflag = 1; 4176 break; 4177 4178 default: 4179 errx(EX_USAGE, "bad arguments, for usage" 4180 " summary ``ipfw''"); 4181 } 4182 4183 av += optind; 4184 ac -= optind; 4185 if (ac != 1) 4186 errx(EX_USAGE, "extraneous filename arguments"); 4187 4188 if ((f = fopen(av[0], "r")) == NULL) 4189 err(EX_UNAVAILABLE, "fopen: %s", av[0]); 4190 4191 if (pflag) { 4192 /* pipe through preprocessor (cpp or m4) */ 4193 int pipedes[2]; 4194 4195 args[i] = NULL; 4196 4197 if (pipe(pipedes) == -1) 4198 err(EX_OSERR, "cannot create pipe"); 4199 4200 switch((preproc = fork())) { 4201 case -1: 4202 err(EX_OSERR, "cannot fork"); 4203 4204 case 0: 4205 /* child */ 4206 if (dup2(fileno(f), 0) == -1 4207 || dup2(pipedes[1], 1) == -1) 4208 err(EX_OSERR, "dup2()"); 4209 fclose(f); 4210 close(pipedes[1]); 4211 close(pipedes[0]); 4212 execvp(cmd, args); 4213 err(EX_OSERR, "execvp(%s) failed", cmd); 4214 4215 default: 4216 /* parent */ 4217 fclose(f); 4218 close(pipedes[1]); 4219 if ((f = fdopen(pipedes[0], "r")) == NULL) { 4220 int savederrno = errno; 4221 4222 kill(preproc, SIGTERM); 4223 errno = savederrno; 4224 err(EX_OSERR, "fdopen()"); 4225 } 4226 } 4227 } 4228 4229 while (fgets(buf, BUFSIZ, f)) { 4230 lineno++; 4231 snprintf(linename, sizeof(linename), "Line %d", lineno); 4232 args[0] = linename; 4233 4234 if (*buf == '#') 4235 continue; 4236 if ((p = strchr(buf, '#')) != NULL) 4237 *p = '\0'; 4238 i = 1; 4239 if (qflag) 4240 args[i++] = __DECONST(char *, "-q"); 4241 for (a = strtok(buf, WHITESP); 4242 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++) 4243 args[i] = a; 4244 if (i == (qflag? 2: 1)) 4245 continue; 4246 if (i == MAX_ARGS) 4247 errx(EX_USAGE, "%s: too many arguments", 4248 linename); 4249 args[i] = NULL; 4250 4251 ipfw_main(i, args); 4252 } 4253 fclose(f); 4254 if (pflag) { 4255 if (waitpid(preproc, &status, 0) == -1) 4256 errx(EX_OSERR, "waitpid()"); 4257 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 4258 errx(EX_UNAVAILABLE, 4259 "preprocessor exited with status %d", 4260 WEXITSTATUS(status)); 4261 else if (WIFSIGNALED(status)) 4262 errx(EX_UNAVAILABLE, 4263 "preprocessor exited with signal %d", 4264 WTERMSIG(status)); 4265 } 4266 } 4267 4268 int 4269 main(int ac, char *av[]) 4270 { 4271 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 4272 if (s < 0) 4273 err(EX_UNAVAILABLE, "socket"); 4274 4275 /* 4276 * If the last argument is an absolute pathname, interpret it 4277 * as a file to be preprocessed. 4278 */ 4279 4280 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 4281 ipfw_readfile(ac, av); 4282 else 4283 ipfw_main(ac, av); 4284 return EX_OK; 4285 } 4286